Decompiled source of BNYS mod v1.3.2
Bunject.Difficulty.Contracts.dll
Decompiled 2 days agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using Bunject.Levels; using Levels; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Bunject.Difficulty.Contracts")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+0eddd3790f0056a92947bfc95a9e9166555bfa48")] [assembly: AssemblyProduct("Bunject.Difficulty.Contracts")] [assembly: AssemblyTitle("Bunject.Difficulty.Contracts")] [assembly: AssemblyVersion("1.0.0.0")] namespace Bunject.Difficulty; public static class LevelDifficultyExtensions { public const int MaxDifficulty = 10; private const string PropertyKey = "sergedev.bunject.difficulty"; public static void SetDifficulty(this LevelObject level, int? difficulty) { LevelProperties.SetProperty(level, "sergedev.bunject.difficulty", (object)Math.Max(0, Math.Min(10, difficulty.GetValueOrDefault()))); } public static int GetDifficulty(this LevelObject level) { int result = default(int); if (!LevelProperties.TryGetProperty<int>(level, "sergedev.bunject.difficulty", ref result)) { return 0; } return result; } }
Bunject.NewYardSystem.dll
Decompiled 2 days agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Logging; using Bunburrows; using Bunject.Computer; using Bunject.Dialogue; using Bunject.Difficulty; using Bunject.Internal; using Bunject.Levels; using Bunject.Menu; using Bunject.Monitoring; using Bunject.NewYardSystem.Computer; using Bunject.NewYardSystem.Internal; using Bunject.NewYardSystem.Levels; using Bunject.NewYardSystem.Levels.Archive; using Bunject.NewYardSystem.Levels.Local; using Bunject.NewYardSystem.Levels.Web; using Bunject.NewYardSystem.Menu; using Bunject.NewYardSystem.Model; using Bunject.NewYardSystem.Resources; using Bunject.NewYardSystem.Sources; using Bunject.NewYardSystem.Utility; using Bunject.Progression; using Bunject.Rules; using Bunject.Tiling; using Characters.Bunny.Data; using Computer.Paquerette.Rules; using Dialogue; using HarmonyLib; using Levels; using Misc; using Newtonsoft.Json; using SharpCompress.Archives; using SharpCompress.Common; using SharpCompress.Readers; using Tiling.Behaviour; using UnityEngine; using UnityEngine.Tilemaps; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("BunjectNewYardSystem")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BunjectNewYardSystem")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("72607052-293c-42fa-b044-aed2841c5102")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyVersion("1.0.0.0")] namespace Bunject.NewYardSystem { [BepInPlugin("sergedev.bunject.newyardsystem", "BNYS", "1.3.2")] public class BNYSPlugin : BaseUnityPlugin, IBunjectorPlugin, IMonitor, IMenuSource, IComputerPageSource { public const string pluginGuid = "sergedev.bunject.newyardsystem"; public const string pluginName = "BNYS"; public const string pluginVersion = "1.3.2"; public static string pluginsDirectory = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "..\\")); public static string rootDirectory = Path.GetFullPath(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); public static string inlineDirectory = Path.Combine(rootDirectory, "BNYS"); private BNYSWorld CurrentCustomWorld; private WorldMenu menu; private EmergencyLevelsList emergencyList; public ManualLogSource Logger => ((BaseUnityPlugin)this).Logger; internal WorldSources Sources { get; private set; } internal IEnumerable<BNYSWorld> Worlds => Sources.Worlds; public string MenuTitle => "BNYS"; public void Awake() { Logger.LogInfo((object)"Bunject New Yard System [BNYS] Plugin Awakened. v1.3.2"); Sources = new WorldSources(this); Sources.Load(); menu = new WorldMenu(this); BunjectAPI.RegisterPlugin((IBunjectorPlugin)(object)this); if (Worlds.Any()) { Logger.LogInfo((object)"Initial Load Finished!"); } else { Logger.LogInfo((object)"All worlds empty! Please configure a burrow with a surface entrance, and depth of at least 1, or add a world from the BNYS menu!"); } } public void OnAssetsLoaded() { } public void OnProgressionLoaded(GeneralProgression progression) { //IL_0059: Unknown result type (might be due to invalid IL or missing references) if (CurrentCustomWorld != null) { progression.HandleBunburrowSignsDiscovery(); progression.HandleBackToSurfaceUnlock(); progression.HandleOphelinePortableComputerUnlock(); progression.HandleMapUnlock(); progression.HandleSeenBootAnimation(); progression.HandleHerbeDialoguePlayed("HerbeFoundInTemple"); progression.HandleElevatorUsed(); if (CurrentCustomWorld.Config.TeleportAnywhereUnlocked) { progression.HandleTeleportAnywhereUnlock(); } GameRules.SetGameCompatibility(progression, CurrentCustomWorld.Compatibility); ProgressionExtensions.UnlockHerbeEarly(progression); progression.HandleHerbeDialoguePlayed("HerbeBackOnSurface"); progression.HandleHerbeDialoguePlayed("HerbeIntro"); progression.HandleOphelineDialoguePlayed("OphelinePostHerbeEncounter"); progression.HandleOphelineDialoguePlayed("OphelineHint"); progression.HandleOneShotDialoguePlayed("Hanger"); progression.HandleOneShotDialoguePlayed("Hanger2"); progression.HandleOneShotDialoguePlayed("HayStack"); progression.HandleOneShotDialoguePlayed("HayStack2"); progression.HandleWitnessedTrespassing(); progression.HandleWitnessedBunnyTrespassing(); progression.HandleAccidentallyFell(); ProgressionExtensions.HandleBeenStuckOnALevel(progression); ProgressionExtensions.HandleWitnessedAReproduction(progression); ProgressionExtensions.HandleWitnessedExistingCoupleReunion(progression); ProgressionExtensions.HandleWitnessedABunnyFall(progression); ProgressionExtensions.HandleWitnessedABunnyGoingBackUp(progression); progression.HandleRuleConditionUnlocked((RuleUnlockCondition)14); progression.HandleRuleConditionUnlocked((RuleUnlockCondition)15); progression.HandleRuleConditionUnlocked((RuleUnlockCondition)17); } } public LevelObject OnLevelLoad(LevelObject level, LevelIdentity identity) { return level; } public string OnLevelTitle(string title, LevelIdentity identity, bool useWhite) { return title; } public void OnBunnyCapture(BunnyIdentity bunnyIdentity, bool wasHomeCapture) { } public Bunburrow? GetDefaultMapBunburrow(Bunburrow? bunburrow) { //IL_0055: Unknown result type (might be due to invalid IL or missing references) if (CurrentCustomWorld == null) { return bunburrow; } Burrow first = CurrentCustomWorld.Burrows.FirstOrDefault(); BNYSModBunburrowBase bNYSModBunburrowBase = CurrentCustomWorld.ModBurrows?.FirstOrDefault(delegate(BNYSModBunburrowBase b) { string localName = b.LocalName; Burrow obj = first; return localName == ((obj != null) ? obj.Name : null); }); if (bNYSModBunburrowBase == null) { return bunburrow; } return BunburrowExtension.ToBunburrow(bNYSModBunburrowBase.ID); } public void OnPowerTile(PowerUnlockTile tile, LevelIdentity identity, Action dismiss) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) if (!CustomBunburrowExtension.IsCustomBunburrow(identity.Bunburrow)) { return; } if (GameManager.GeneralProgression.HasUnlockedTeleportAnywhere) { dismiss(); return; } GameManager.UIController.DisplayDialogue((DialogueObject)(object)BuildTeleportUnlockDialogue(), (BunburrowStyle)null, true, false); Action<bool> onDialogueEnd = null; onDialogueEnd = delegate { GameManager.UIController.OnDialogueEnd -= onDialogueEnd; dismiss(); }; GameManager.UIController.OnDialogueEnd += onDialogueEnd; } public bool TryResolvePowerTileSprite(PowerUnlockTile tile, LevelIdentity identity, out TileBase sprite) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) if (!CustomBunburrowExtension.IsCustomBunburrow(identity.Bunburrow)) { sprite = null; return false; } sprite = (TileBase)(object)(GameManager.GeneralProgression.HasUnlockedTeleportAnywhere ? null : AssetsManager.TeleportAnywherePowerUnlockAnimatedTile); return true; } private static CustomDialogueObject BuildTeleportUnlockDialogue() { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Expected O, but got Unknown CustomDialogueObject obj = ScriptableObject.CreateInstance<CustomDialogueObject>(); ((Object)obj).name = "BNYS::TeleportAnywhereUnlock"; obj.DialogueLines = new List<DialogueLine> { (DialogueLine)new CustomDialogueLine { Headshot = "PaqueretteHappy", Content = "Teleport Powers Unlocked!" } }; Traverse.Create((object)obj).Field("unlocksTeleportAnywhere").SetValue((object)true); return obj; } public void OnMainMenu() { if (CurrentCustomWorld != null) { BunjectAPI.ClearRegisters(); Traverse obj = Traverse.Create(typeof(AssetsManager)); LevelObject value = obj.Field<LevelObject>("surfaceMiddleLevelBase").Value; LevelObject value2 = obj.Field<LevelObject>("surfaceMiddleLevelExpanded").Value; LevelObject value3 = obj.Field<LevelObject>("surfaceMiddleLevelExpanded2NoHerbe").Value; LevelObject value4 = obj.Field<LevelObject>("surfaceMiddleLevelExpanded2Herbe").Value; ExtendedSurfaceLevelGenerator.LinkSurface(value, AssetsManager.SurfaceRightLevel); ExtendedSurfaceLevelGenerator.LinkSurface(value2, AssetsManager.SurfaceRightLevel); ExtendedSurfaceLevelGenerator.LinkSurface(value3, AssetsManager.SurfaceRightLevel); ExtendedSurfaceLevelGenerator.LinkSurface(value4, AssetsManager.SurfaceRightLevel); CurrentCustomWorld = null; } } public void OnShowCredits() { } public LevelsList LoadEmergencyLevelsList(LevelsList original) { if ((Object)(object)emergencyList == (Object)null) { emergencyList = ScriptableObject.CreateInstance<EmergencyLevelsList>(); emergencyList.Bnys = this; } return (LevelsList)(object)emergencyList; } public void LoadBurrowSurfaceLevel(string listName, LevelObject otherwise) { Burrow burrow = Worlds.SelectMany((BNYSWorld cw) => cw.Burrows).FirstOrDefault((Func<Burrow, bool>)((Burrow b) => b.Name == listName)); if (burrow != null) { Worlds.FirstOrDefault((BNYSWorld cw) => cw.Burrows.Contains(burrow)).Burrows.Where((Burrow b) => b.Depth > 0 && b.HasSurfaceEntry).ToList().IndexOf(burrow); Logger.LogWarning((object)"Burrow was not surfaceable / not in the list of generated surface levels!"); } } internal BNYSWorld LoadLocalWorld(string configFile) { BNYSWorld bNYSWorld = LoadWorldConfig(configFile); if (bNYSWorld == null || !IsLoadable(bNYSWorld, configFile)) { return null; } if (bNYSWorld is WebWorld) { return bNYSWorld; } foreach (Burrow burrow in bNYSWorld.Burrows) { PatchBurrowDetails(Path.GetDirectoryName(configFile), burrow); } return bNYSWorld; } internal BNYSWorld LoadArchiveWorld(string archivePath) { BNYSWorld bNYSWorld = LoadWorldConfigFromArchive(archivePath); if (bNYSWorld == null || !IsLoadable(bNYSWorld, archivePath)) { return null; } return bNYSWorld; } private bool IsLoadable(BNYSWorld world, string source) { if (!world.Config.Enabled) { Logger.LogInfo((object)("SKIPPED: World '" + world.Title + "' is disabled. (" + source + ")")); return false; } if (world.Burrows == null || world.Burrows.Count == 0) { Logger.LogWarning((object)("SKIPPED: World '" + world.Title + "' has no Burrows. (" + source + ")")); return false; } if (!world.Burrows.Any((Burrow b) => b.HasSurfaceEntry && b.Depth > 0)) { Logger.LogWarning((object)("SKIPPED: World '" + world.Title + "' has no burrow with HasSurfaceEntry and a Depth of at least 1, so there's no way in. (" + source + ")")); return false; } return true; } private BNYSWorld LoadWorldConfig(string filename) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown CustomWorld val = null; try { using StreamReader streamReader = new StreamReader(filename); val = (CustomWorld)new JsonSerializer().Deserialize((TextReader)streamReader, typeof(CustomWorld)); } catch (Exception ex) { Logger.LogError((object)"Following file could not be parsed"); Logger.LogError((object)filename); Logger.LogError((object)ex.Message); Logger.LogError((object)ex); } if (val == null) { Logger.LogError((object)("SKIPPED: World config couldn't be loaded. (" + filename + ")")); return null; } if (string.IsNullOrEmpty(val.Title)) { val.Title = "Untitled"; } if (!string.IsNullOrEmpty(val.ProxyURL)) { try { return LoadProxyWorld(val); } catch (Exception ex2) { Logger.LogError((object)"Error loading Proxy World config.json"); Logger.LogError((object)filename); Logger.LogError((object)ex2.Message); Logger.LogError((object)ex2); } } return new LocalWorld(val); } private BNYSWorld LoadWorldConfigFromArchive(string archivePath) { //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Expected O, but got Unknown Logger.LogInfo((object)("Opening World Archive: " + archivePath)); WorldArchive worldArchive; try { worldArchive = WorldArchive.Load(archivePath); } catch (Exception ex) { Logger.LogError((object)("Archive " + Path.GetFileName(archivePath) + " could not be opened. Only .bnys files with zip or 7z format are supported.")); Logger.LogError((object)ex.Message); return null; } string text = ""; Stream stream = worldArchive.Open("config.json"); if (stream == null) { List<string> list = worldArchive.EntryNames.Select((string n) => n.Split('/')[0]).Distinct().ToList(); if (list.Count == 1) { text = list[0] + "/"; stream = worldArchive.Open(text + "config.json"); } } if (stream == null) { Logger.LogError((object)("Archive " + Path.GetFileName(archivePath) + " is missing config.json.")); Logger.LogError((object)"Please double check that config.json is at the root level of the .bnys (zip) file."); return null; } CustomWorld val = null; try { using (stream) { using StreamReader streamReader = new StreamReader(stream); val = (CustomWorld)new JsonSerializer().Deserialize((TextReader)streamReader, typeof(CustomWorld)); } } catch (Exception ex2) { Logger.LogError((object)("Archive " + Path.GetFileName(archivePath) + " config.json file could not be parsed: ")); Logger.LogError((object)ex2.Message); Logger.LogError((object)ex2); return null; } if (val == null) { Logger.LogError((object)("SKIPPED: World config couldn't be loaded. (" + archivePath + ")")); return null; } if (string.IsNullOrEmpty(val.Title)) { val.Title = "Untitled"; } if (!string.IsNullOrEmpty(val.ProxyURL)) { try { return LoadProxyWorld(val); } catch (Exception ex3) { Logger.LogError((object)("Error loading Archive Proxy World config.json - " + Path.GetFileName(archivePath))); Logger.LogError((object)ex3.Message); Logger.LogError((object)ex3); } } return new ArchiveWorld(val, worldArchive, text); } private WebWorld LoadProxyWorld(CustomWorld basis) { if (!basis.ProxyURL.EndsWith("/")) { basis.ProxyURL += "/"; } Uri uri = new Uri(basis.ProxyURL); CustomWorld val = new Uri(uri, "config.json").Load<CustomWorld>(); if (val != null) { val.ProxyURL = basis.ProxyURL; val.Enabled = val.Enabled || basis.Enabled; val.LiveReloading = false; if (string.IsNullOrEmpty(val.Title)) { val.Title = basis.Title; } if (val.Burrows != null && (val.SurfaceEntries == null || val.SurfaceEntries.Count == 0)) { val.SurfaceEntries = basis.SurfaceEntries; } if (string.IsNullOrEmpty(val.Title)) { val.Title = "Untitled"; } return new WebWorld(val, uri); } return null; } private void PatchBurrowDetails(string directory, Burrow burrow) { if (!Path.IsPathRooted(burrow.Directory)) { burrow.Directory = Path.Combine(directory, burrow.Directory); Logger.LogInfo((object)("Burrow Directory: " + burrow.Directory)); } } private void GenerateSurfaceLevels(BNYSWorld world) { Traverse obj = Traverse.Create(typeof(AssetsManager)); LevelObject value = obj.Field<LevelObject>("surfaceMiddleLevelBase").Value; LevelObject value2 = obj.Field<LevelObject>("surfaceMiddleLevelExpanded").Value; LevelObject value3 = obj.Field<LevelObject>("surfaceMiddleLevelExpanded2NoHerbe").Value; LevelObject value4 = obj.Field<LevelObject>("surfaceMiddleLevelExpanded2Herbe").Value; LevelObject val = value; try { ExtendedSurfaceLevelGenerator.CreateSurfaceLevels(world, world.ModBurrows, val); } catch (Exception ex) { Logger.LogError((object)("Error occurred while generating surface levels for world: " + world.Title)); Logger.LogError((object)ex.Message); Logger.LogError((object)ex); } val = world.GeneratedSurfaceLevels.LastOrDefault() ?? val; LevelObject rightOfShop = world.GeneratedSurfaceLevels.FirstOrDefault() ?? val; ExtendedSurfaceLevelGenerator.LinkSurface(value, rightOfShop); ExtendedSurfaceLevelGenerator.LinkSurface(value2, rightOfShop); ExtendedSurfaceLevelGenerator.LinkSurface(value3, rightOfShop); ExtendedSurfaceLevelGenerator.LinkSurface(value4, rightOfShop); PatchLevelAsEndcap(val); } private void PatchLevelAsEndcap(LevelObject endcapLevel) { Traverse.Create((object)endcapLevel).Field("specificBackground").SetValue((object)SurfaceBurrowsPatch.EndingBackground); } private List<BNYSModBunburrowBase> BuildBurrows(BNYSWorld world) { CustomBunburrowCache customBunburrowCache = new CustomBunburrowCache(); List<BNYSModBunburrowBase> burrows = new List<BNYSModBunburrowBase>(); foreach (CustomBunburrowModel cachedBurrow in customBunburrowCache.CustomBurrows.Where((CustomBunburrowModel cb) => cb.World == world.Title || string.IsNullOrEmpty(cb.World))) { Burrow burrowModel = ((IEnumerable<Burrow>)world.Burrows).FirstOrDefault((Func<Burrow, bool>)((Burrow b) => b.Name == cachedBurrow.Name)); if (burrowModel != null && !burrows.Any((BNYSModBunburrowBase b) => b.BurrowModel == burrowModel)) { cachedBurrow.World = world.Title; cachedBurrow.Prefix = world.Prefix; cachedBurrow.Indicator = burrowModel.Indicator; burrows.Add(world.GenerateBunburrow(this, burrowModel.Name)); } } foreach (Burrow item in world.Burrows.Where((Burrow m) => !burrows.Any((BNYSModBunburrowBase b) => b.BurrowModel == m)).ToList()) { BNYSModBunburrowBase bNYSModBunburrowBase = world.GenerateBunburrow(this, item.Name); burrows.Add(bNYSModBunburrowBase); customBunburrowCache.CacheBunburrow(bNYSModBunburrowBase); } customBunburrowCache.SaveCache(); LinkLevelLists(burrows); return burrows; } private void LinkLevelLists(List<BNYSModBunburrowBase> burrows) { foreach (BNYSModBunburrowBase burrow in burrows) { if (!string.IsNullOrEmpty(burrow.BurrowModel.Links.Left)) { BNYSModBunburrowBase bNYSModBunburrowBase = burrows.FirstOrDefault((BNYSModBunburrowBase bb) => bb.LocalName == burrow.BurrowModel.Links.Left); if (bNYSModBunburrowBase != null) { burrow.GetLevels().AdjacentBunburrows.SetPart((Direction)0, bNYSModBunburrowBase.GetLevels()); } } if (!string.IsNullOrEmpty(burrow.BurrowModel.Links.Up)) { BNYSModBunburrowBase bNYSModBunburrowBase2 = burrows.FirstOrDefault((BNYSModBunburrowBase bb) => bb.LocalName == burrow.BurrowModel.Links.Up); if (bNYSModBunburrowBase2 != null) { burrow.GetLevels().AdjacentBunburrows.SetPart((Direction)2, bNYSModBunburrowBase2.GetLevels()); } } if (!string.IsNullOrEmpty(burrow.BurrowModel.Links.Right)) { BNYSModBunburrowBase bNYSModBunburrowBase3 = burrows.FirstOrDefault((BNYSModBunburrowBase bb) => bb.LocalName == burrow.BurrowModel.Links.Right); if (bNYSModBunburrowBase3 != null) { burrow.GetLevels().AdjacentBunburrows.SetPart((Direction)1, bNYSModBunburrowBase3.GetLevels()); } } if (!string.IsNullOrEmpty(burrow.BurrowModel.Links.Down)) { BNYSModBunburrowBase bNYSModBunburrowBase4 = burrows.FirstOrDefault((BNYSModBunburrowBase bb) => bb.LocalName == burrow.BurrowModel.Links.Down); if (bNYSModBunburrowBase4 != null) { burrow.GetLevels().AdjacentBunburrows.SetPart((Direction)3, bNYSModBunburrowBase4.GetLevels()); } } } } public static BunburrowStyle ResolveStyle(string style) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Expected I4, but got Unknown BurrowStyle val = default(BurrowStyle); BurrowStyles.TryParse(style, ref val); switch ((int)val) { case 1: case 2: return AssetsManager.BunburrowsListOfStyles[(Bunburrow)1]; case 3: return AssetsManager.BunburrowsListOfStyles[(Bunburrow)2]; case 4: case 5: return AssetsManager.BunburrowsListOfStyles[(Bunburrow)4]; case 6: case 7: return AssetsManager.BunburrowsListOfStyles[(Bunburrow)3]; case 8: return AssetsManager.BunburrowsListOfStyles.VoidB; case 9: return AssetsManager.BunburrowsListOfStyles.Temple; case 10: return AssetsManager.BunburrowsListOfStyles.Hell; case 11: return AssetsManager.BunburrowsListOfStyles.PinkHell; case 12: case 13: return AssetsManager.BunburrowsListOfStyles.AquaticHell; case 14: return AssetsManager.BunburrowsListOfStyles.HayHell; case 15: case 16: return AssetsManager.BunburrowsListOfStyles.PurpleHell; case 17: case 18: return AssetsManager.BunburrowsListOfStyles.GhostlyHell; case 19: return AssetsManager.BunburrowsListOfStyles.HellTemple; default: return AssetsManager.BunburrowsListOfStyles[(Bunburrow)0]; } } public void DrawMenuOptions() { menu.Draw(); } internal void LoadWorld(BNYSWorld world) { BunjectAPI.BeginLoadingScreen(); try { SurfaceBurrowsPatch.PatchSurfaceBurrows(AssetsManager.SurfaceRightLevel, null); if (world.ModBurrows == null) { world.ModBurrows = BuildBurrows(world); } foreach (BNYSModBunburrowBase modBurrow in world.ModBurrows) { BunjectAPI.RegisterBunburrow((IModBunburrow)(object)modBurrow); foreach (int elevatorDepth in modBurrow.BurrowModel.ElevatorDepths) { BunjectAPI.RegisterElevator(modBurrow.ID, elevatorDepth); } } BunjectAPI.SetBunburrowOrder((IEnumerable<IModBunburrow>)world.ModBurrows.OrderBy((BNYSModBunburrowBase b) => world.Burrows.FindIndex((Burrow m) => m.Name == b.LocalName))); GenerateSurfaceLevels(world); BunjectAPI.LoadSave("BNYS", world.Title); CurrentCustomWorld = world; } catch (Exception ex) { Debug.LogException(ex); CurrentCustomWorld = null; BunjectAPI.ClearRegisters(); BunjectAPI.CancelLoadingScreen(); } } internal void DeleteWorldSave(BNYSWorld world) { if (SaveFileModUtility.PluginSaveExists("BNYS", world.Title)) { File.Delete(SaveFileModUtility.GetPluginSaveFilePath("BNYS", world.Title)); } } public void GeneratePages(ICustomPageGenerator pageMaker) { if (CurrentCustomWorld != null) { pageMaker.CreateComputerPage<CreditsPage>().World = CurrentCustomWorld.Config; } } } } namespace Bunject.NewYardSystem.Utility { public static class UriExtensions { public static string Load(this Uri uri) { Console.WriteLine("Loading: " + uri); using WebClient webClient = new WebClient(); return webClient.DownloadString(uri); } public static T Load<T>(this Uri uri) where T : class { //IL_002f: Unknown result type (might be due to invalid IL or missing references) Console.WriteLine("Loading: " + uri); using WebClient webClient = new WebClient(); using StreamReader streamReader = new StreamReader(webClient.OpenRead(uri)); return new JsonSerializer().Deserialize((TextReader)streamReader, typeof(T)) as T; } } } namespace Bunject.NewYardSystem.Sources { internal class WorldSource { public string Path { get; } public string Problem { get; set; } public List<BNYSWorld> Worlds { get; } = new List<BNYSWorld>(); public bool IsInstalled => Path == null; public WorldSource(string path) { Path = path; } } internal class WorldSourceList { private readonly string listPath; public List<string> Paths { get; private set; } = new List<string>(); public WorldSourceList(string listPath) { this.listPath = listPath; if (!File.Exists(listPath)) { return; } try { Paths = JsonConvert.DeserializeObject<List<string>>(File.ReadAllText(listPath)) ?? new List<string>(); } catch (Exception ex) { Debug.LogError((object)("[BNYS] " + listPath + " couldn't be read, so it was renamed to .bad and the list starts empty. " + ex.Message)); File.Copy(listPath, listPath + ".bad", overwrite: true); File.Delete(listPath); } } public void Save() { File.WriteAllText(listPath, JsonConvert.SerializeObject((object)Paths, (Formatting)1)); } } internal class WorldSources { private readonly BNYSPlugin plugin; private readonly WorldSourceList savedPaths; private readonly List<WorldSource> sources = new List<WorldSource>(); public IReadOnlyList<WorldSource> All => sources; public IEnumerable<WorldSource> Added => sources.Where((WorldSource s) => !s.IsInstalled); public IEnumerable<BNYSWorld> Worlds => sources.SelectMany((WorldSource s) => s.Worlds); public WorldSources(BNYSPlugin plugin) { this.plugin = plugin; savedPaths = new WorldSourceList(Path.Combine(Paths.ConfigPath, "BNYS.WorldSources.json")); } public void Load() { WorldSource worldSource = new WorldSource(null); sources.Add(worldSource); Reload(worldSource); foreach (string path in savedPaths.Paths) { WorldSource worldSource2 = new WorldSource(path); sources.Add(worldSource2); Reload(worldSource2); if (worldSource2.Problem != null) { plugin.Logger.LogWarning((object)("World source has a problem (" + worldSource2.Problem + "), it stays listed in the BNYS menu. (" + path + ")")); } } } public bool TryAdd(string input, out WorldSource added, out string error) { added = null; error = null; string path = input.Trim().Trim('"'); try { path = Path.GetFullPath(path); } catch (Exception) { error = "That isn't a path."; return false; } if (path.Length > Path.GetPathRoot(path).Length) { path = path.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); } if (string.Equals(Path.GetFileName(path), "config.json", StringComparison.OrdinalIgnoreCase)) { path = Path.GetDirectoryName(path); } if (!File.Exists(path) && !Directory.Exists(path)) { error = "Nothing found there."; return false; } WorldSource worldSource = Added.FirstOrDefault((WorldSource s) => string.Equals(s.Path, path, StringComparison.OrdinalIgnoreCase)); if (worldSource != null && worldSource.Problem == null) { error = "That's already in the list."; return false; } bool flag = worldSource == null; if (flag) { worldSource = new WorldSource(path); } Reload(worldSource); if (worldSource.Worlds.Count == 0) { error = "No worlds found there. The BepInEx log may say why."; return false; } if (flag) { sources.Add(worldSource); savedPaths.Paths.Add(path); savedPaths.Save(); } plugin.Logger.LogInfo((object)$"World source added with {worldSource.Worlds.Count} worlds. ({path})"); added = worldSource; return true; } public void Remove(WorldSource source) { sources.Remove(source); savedPaths.Paths.Remove(source.Path); savedPaths.Save(); } private void Reload(WorldSource source) { source.Worlds.Clear(); source.Problem = null; if (!source.IsInstalled && !File.Exists(source.Path) && !Directory.Exists(source.Path)) { source.Problem = "not found"; return; } string text = source.Path ?? "installed"; List<BNYSWorld> list; try { list = (source.IsInstalled ? LoadInstalledWorlds() : LoadWorldsAt(source.Path)); } catch (Exception ex) { plugin.Logger.LogError((object)("World source couldn't be read. (" + text + ")")); plugin.Logger.LogError((object)ex); list = new List<BNYSWorld>(); } int num = 0; foreach (BNYSWorld world in list) { if (Worlds.Any((BNYSWorld w) => string.Equals(w.Title, world.Title, StringComparison.OrdinalIgnoreCase))) { num++; plugin.Logger.LogWarning((object)("SKIPPED: World '" + world.Title + "' has the same title as a world already loaded, and would share its save. (" + text + ")")); } else { source.Worlds.Add(world); } } source.Worlds.Sort((BNYSWorld a, BNYSWorld b) => StringComparer.OrdinalIgnoreCase.Compare(a.Title, b.Title)); if (!source.IsInstalled && source.Worlds.Count == 0) { source.Problem = ((num > 0) ? "titles already loaded" : "no worlds loaded"); } } private List<BNYSWorld> LoadInstalledWorlds() { List<BNYSWorld> list = new List<BNYSWorld>(); if (Directory.Exists(BNYSPlugin.inlineDirectory)) { foreach (string item in Directory.EnumerateDirectories(BNYSPlugin.inlineDirectory)) { string text = Path.Combine(item, "config.json"); if (File.Exists(text)) { list.Add(plugin.LoadLocalWorld(text)); } } } foreach (string item2 in Directory.EnumerateDirectories(BNYSPlugin.pluginsDirectory)) { foreach (string item3 in Directory.EnumerateFiles(item2, "*.bnys")) { list.Add(plugin.LoadArchiveWorld(item3)); } } list.RemoveAll((BNYSWorld w) => w == null); return list; } private List<BNYSWorld> LoadWorldsAt(string path) { List<BNYSWorld> list = new List<BNYSWorld>(); string text = Path.Combine(path, "config.json"); if (File.Exists(path)) { list.Add(plugin.LoadArchiveWorld(path)); } else if (File.Exists(text)) { list.Add(plugin.LoadLocalWorld(text)); } else { foreach (string item in Directory.EnumerateDirectories(path)) { string text2 = Path.Combine(item, "config.json"); if (File.Exists(text2)) { list.Add(plugin.LoadLocalWorld(text2)); } } foreach (string item2 in Directory.EnumerateFiles(path, "*.bnys")) { list.Add(plugin.LoadArchiveWorld(item2)); } } list.RemoveAll((BNYSWorld w) => w == null); return list; } } } namespace Bunject.NewYardSystem.Resources { internal static class DefaultLevel { public static string Content = "T,T,T,T,T,T,T,T,T,T,T,T,T,T,T" + Environment.NewLine + "T,T,T,T,T,T,T,T,T,T,T,T,T,T,T" + Environment.NewLine + "T,T,T,T,T,T,T,T,T,T,T,T,T,T,T" + Environment.NewLine + "T,T,T,T,T,T,T,T,T,T,T,T,T,T,T" + Environment.NewLine + "T,T,T,T,T,T,T,S,T,T,T,T,T,T,T" + Environment.NewLine + "T,T,T,T,T,T,T,T,T,T,T,T,T,T,T" + Environment.NewLine + "T,T,T,T,T,T,T,T,T,T,T,T,T,T,T" + Environment.NewLine + "T,T,T,T,T,T,T,T,T,T,T,T,T,T,T" + Environment.NewLine + "T,T,T,T,T,T,T,T,T,T,T,T,T,T,T" + Environment.NewLine; } internal class ImportImage { public static Sprite ImportSprite(string name, string path, Vector2 pivot, float pixelsPerUnit) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) Texture2D val = ImportTexture(name, path); return Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), pivot, pixelsPerUnit); } public static Texture2D ImportTexture(string name, string path) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected O, but got Unknown //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown byte[] array = File.ReadAllBytes(path); Texture2D val = new Texture2D(2, 2); ImageConversion.LoadImage(val, array); ((Object)val).name = name; val.Apply(); return val; } } } namespace Bunject.NewYardSystem.Menu { internal class AddSourceBox { private readonly WorldMenu menu; private string input = ""; public AddSourceBox(WorldMenu menu) { this.menu = menu; } public void Draw() { GUILayout.Label("Add a world or a folder of worlds:", Array.Empty<GUILayoutOption>()); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); input = GUILayout.TextField(input, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.MinWidth(0f), GUILayout.ExpandWidth(true) }); if (GUILayout.Button("Add", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(100f) })) { menu.Pending.Set(Add); } GUILayout.EndHorizontal(); } private void Add() { if (input.Trim().Trim('"').Length != 0) { if (!menu.Plugin.Sources.TryAdd(input, out var added, out var error)) { menu.Status = error; return; } input = ""; menu.Status = $"Added {added.Worlds.Count} worlds from {menu.NameOf(added)}."; } } } internal class PendingMenuChange { private Action change; public void Set(Action action) { change = action; } public void ApplyOnLayout() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Invalid comparison between Unknown and I4 if ((int)Event.current.type == 8 && change != null) { Action action = change; change = null; action(); } } } internal static class SourceNames { public static string ShortName(string path, IEnumerable<string> allPaths) { string[] array = SplitPath(path); for (int count = 1; count < array.Length; count++) { string tail = PathTail(array, count); if (!allPaths.Any((string p) => p != path && string.Equals(PathTail(SplitPath(p), count), tail, StringComparison.OrdinalIgnoreCase))) { return ".." + Path.DirectorySeparatorChar + tail; } } return path; } private static string[] SplitPath(string path) { return path.Split(new char[2] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries); } private static string PathTail(string[] parts, int count) { return string.Join(Path.DirectorySeparatorChar.ToString(), parts.Skip(Math.Max(0, parts.Length - count))); } } internal class WorldList { private readonly WorldMenu menu; private readonly HashSet<WorldSource> collapsedSources = new HashSet<WorldSource>(); private WorldSource pendingRemoval; private GUIStyle headerStyle; public WorldList(WorldMenu menu) { this.menu = menu; } public void Draw() { WorldSources sources = menu.Plugin.Sources; if (!sources.Added.Any()) { foreach (BNYSWorld item in sources.Worlds.Where(menu.MatchesFilter)) { menu.Rows.Draw(item); } return; } foreach (WorldSource item2 in sources.All.ToList()) { if (!item2.IsInstalled || item2.Worlds.Count != 0) { DrawSource(item2); } } } private void DrawSource(WorldSource source) { List<BNYSWorld> list = source.Worlds.Where(menu.MatchesFilter).ToList(); if (menu.IsFiltering && list.Count == 0) { return; } if (pendingRemoval == source) { DrawRemoveConfirmation(source); } else { DrawHeader(source); } if ((collapsedSources.Contains(source) && !menu.IsFiltering) || list.Count == 0) { return; } GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Space(16f); GUILayout.BeginVertical(Array.Empty<GUILayoutOption>()); foreach (BNYSWorld item in list) { menu.Rows.Draw(item); } GUILayout.EndVertical(); GUILayout.EndHorizontal(); } private void DrawHeader(WorldSource source) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Expected O, but got Unknown if (headerStyle == null) { headerStyle = new GUIStyle(GUI.skin.label) { fontStyle = (FontStyle)1 }; } GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); if (GUILayout.Button(collapsedSources.Contains(source) ? "+" : "-", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(25f) })) { menu.Pending.Set(delegate { if (!collapsedSources.Remove(source)) { collapsedSources.Add(source); } }); } string text = menu.NameOf(source); if (source.Problem != null) { GUI.enabled = false; GUILayout.Label(text + " (" + source.Problem + ")", headerStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) }); GUI.enabled = true; } else { GUILayout.Label(text, headerStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) }); } if (!source.IsInstalled && GUILayout.Button("x", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(25f) })) { menu.Pending.Set(delegate { pendingRemoval = source; }); } GUILayout.EndHorizontal(); } private void DrawRemoveConfirmation(WorldSource source) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Remove " + menu.NameOf(source) + "? Saves are kept.", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) }); if (GUILayout.Button("Yes", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(60f) })) { menu.Pending.Set(delegate { Remove(source); }); } if (GUILayout.Button("No", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(60f) })) { menu.Pending.Set(delegate { pendingRemoval = null; }); } GUILayout.EndHorizontal(); } private void Remove(WorldSource source) { menu.Status = "Removed " + menu.NameOf(source) + ". Saves are kept."; menu.Plugin.Sources.Remove(source); menu.Rows.ForgetRemovedWorlds(); collapsedSources.Remove(source); pendingRemoval = null; } } internal class WorldMenu { private const int FilterThreshold = 8; private readonly WorldList worldList; private readonly AddSourceBox addSource; private string filter = ""; public BNYSPlugin Plugin { get; } public PendingMenuChange Pending { get; } = new PendingMenuChange(); public WorldRow Rows { get; } public string Status { get; set; } private bool IsFilterShown => Plugin.Worlds.Count() > 8; public bool IsFiltering { get { if (IsFilterShown) { return !string.IsNullOrEmpty(filter); } return false; } } public WorldMenu(BNYSPlugin plugin) { Plugin = plugin; Rows = new WorldRow(this); addSource = new AddSourceBox(this); worldList = new WorldList(this); } public void Draw() { Pending.ApplyOnLayout(); if (IsFilterShown) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Filter", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) }); filter = GUILayout.TextField(filter, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.MinWidth(0f) }); GUILayout.EndHorizontal(); } worldList.Draw(); addSource.Draw(); if (!string.IsNullOrEmpty(Status)) { GUILayout.Label(Status, Array.Empty<GUILayoutOption>()); } } public bool MatchesFilter(BNYSWorld world) { if (IsFiltering) { return world.Title.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0; } return true; } public string NameOf(WorldSource source) { if (source.IsInstalled) { return "Installed"; } return SourceNames.ShortName(source.Path, Plugin.Sources.Added.Select((WorldSource s) => s.Path)); } } internal class WorldRow { private readonly WorldMenu menu; private BNYSWorld pendingDeletion; public WorldRow(WorldMenu menu) { this.menu = menu; } public void Draw(BNYSWorld world) { if (pendingDeletion == world) { DrawDeleteConfirmation(world); return; } GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label(world.Title, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) }); if (GUILayout.Button("Load", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(100f) })) { menu.Plugin.LoadWorld(world); } if (GUILayout.Button("Delete", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(100f) })) { pendingDeletion = world; } GUILayout.EndHorizontal(); } public void ForgetRemovedWorlds() { if (pendingDeletion != null && !menu.Plugin.Worlds.Contains(pendingDeletion)) { pendingDeletion = null; } } private void DrawDeleteConfirmation(BNYSWorld world) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Delete save?", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) }); if (GUILayout.Button("Yes", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(100f) })) { menu.Plugin.DeleteWorldSave(world); pendingDeletion = null; } if (GUILayout.Button("No", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(100f) })) { pendingDeletion = null; } GUILayout.EndHorizontal(); } } } namespace Bunject.NewYardSystem.Internal { internal class CustomBunburrowCache { private string cachePath; public List<CustomBunburrowModel> CustomBurrows; public CustomBunburrowCache() { //IL_0046: Unknown result type (might be due to invalid IL or missing references) string rootSaveDataPath = SaveFileModUtility.GetRootSaveDataPath(); cachePath = Path.Combine(rootSaveDataPath, "mod-burrow-cache.json"); if (!Directory.Exists(rootSaveDataPath)) { Directory.CreateDirectory(rootSaveDataPath); } if (File.Exists(cachePath)) { using (StreamReader streamReader = new StreamReader(cachePath)) { CustomBurrows = new JsonSerializer().Deserialize((TextReader)streamReader, typeof(List<CustomBunburrowModel>)) as List<CustomBunburrowModel>; return; } } CustomBurrows = new List<CustomBunburrowModel>(); } public CustomBunburrowModel CacheBunburrow(IBNYSModBunburrow bunburrow) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown CustomBunburrowModel val = new CustomBunburrowModel { World = bunburrow.WorldName, Name = bunburrow.LocalName, Prefix = bunburrow.WorldPrefix, Indicator = bunburrow.LocalIndicator }; CustomBurrows.Add(val); return val; } public void SaveCache() { //IL_000c: Unknown result type (might be due to invalid IL or missing references) using StreamWriter streamWriter = new StreamWriter(cachePath); new JsonSerializer().Serialize((TextWriter)streamWriter, (object)CustomBurrows); } } } namespace Bunject.NewYardSystem.Levels { public class BNYSLevelObject : ModLevelObject { private bool shouldReload = true; public bool ShouldReload { get { if (!DelayReload) { return shouldReload; } if (shouldReload) { return LastReloadTime.Minute != DateTime.Now.Minute; } return false; } set { shouldReload = value; } } public DateTime LastReloadTime { get; set; } public bool DelayReload { get; set; } } public class BNYSLevelsList : ModLevelsList { public BNYSPlugin Bnys { get; set; } public BNYSModBunburrowBase ModBunburrow { get; set; } public bool PermitReloading { get; set; } = true; public bool DelayReloading { get; set; } public BNYSLevelObject this[int depth] { get { return ((ModLevelsList)this)[depth] as BNYSLevelObject; } set { ((ModLevelsList)this)[depth] = (ModLevelObject)(object)value; } } public override LevelObject LoadLevel(int depth, LoadingContext loadingContext) { //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Invalid comparison between Unknown and I4 if (depth > 0 && depth <= ((ModLevelsList)this).MaximumDepth) { BNYSLevelObject bNYSLevelObject = this[depth]; if ((Object)(object)bNYSLevelObject == (Object)null) { bNYSLevelObject = ScriptableObject.CreateInstance<BNYSLevelObject>(); ((ModLevelObject)bNYSLevelObject).BunburrowName = ModBunburrow.BurrowModel.Name; ((ModLevelObject)bNYSLevelObject).Depth = depth; ReloadLevel(depth, bNYSLevelObject); this[depth] = bNYSLevelObject; } else if (PermitReloading && bNYSLevelObject.ShouldReload && (int)loadingContext == 1) { ReloadLevel(depth, bNYSLevelObject); } return (LevelObject)(object)bNYSLevelObject; } Bnys.Logger.LogWarning((object)$"{ModBunburrow.Name}: Depth requested, {depth}, exceeds burrow depth of {((ModLevelsList)this).MaximumDepth}"); return null; } private void ReloadLevel(int depth, BNYSLevelObject levelObject) { LevelMetadata val = ModBunburrow.LoadLevel(depth); levelObject.ShouldReload = PermitReloading && (ModBunburrow.World.Config.LiveReloading || val.LiveReloading); levelObject.LastReloadTime = DateTime.Now; levelObject.DelayReload = DelayReloading; PopulateLevel(levelObject, val, depth); } private LevelMetadata CreateDefaultLevelMetadata() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown //IL_0031: Expected O, but got Unknown return new LevelMetadata { Name = "Failed Level Load", LiveReloading = true, IsHell = false, IsTemple = false, Tools = new LevelTools() }; } private void PopulateLevel(BNYSLevelObject levelObject, LevelMetadata levelConfig, int depth) { //IL_00e9: Unknown result type (might be due to invalid IL or missing references) ((Object)levelObject).name = "Level " + ModBunburrow.Name + " - " + levelConfig.Name; ((ModLevelObject)levelObject).CustomNameKey = levelConfig.Name; ((ModLevelObject)levelObject).BunburrowStyle = BNYSPlugin.ResolveStyle(levelConfig.Style); LevelTools tools = levelConfig.Tools; if (tools != null) { ((ModLevelObject)levelObject).NumberOfTraps = tools.Traps; ((ModLevelObject)levelObject).NumberOfPickaxes = tools.Pickaxes; ((ModLevelObject)levelObject).NumberOfCarrots = tools.Carrots; ((ModLevelObject)levelObject).NumberOfShovels = tools.Shovels; } ((ModLevelObject)levelObject).IsTemple = levelConfig.IsTemple; ((ModLevelObject)levelObject).IsHell = levelConfig.IsHell; LevelDifficultyExtensions.SetDifficulty((LevelObject)(object)levelObject, levelConfig.Difficulty); ((ModLevelObject)levelObject).Content = levelConfig.Content; List<LevelHint> hints = levelConfig.Hints; if (hints != null) { ((ModLevelObject)levelObject).Solutions = ((IEnumerable<LevelHint>)hints).Select((Func<LevelHint, Solution>)delegate(LevelHint hint) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Expected O, but got Unknown Solution val = new Solution(); Traverse obj = Traverse.Create((object)val); obj.Field<Vector2Int>("position").Value = new Vector2Int(hint.PositionX, hint.PositionY); obj.Field<Direction>("orientation").Value = (Direction)hint.Orientation; return val; }).ToList(); } ((ModLevelObject)levelObject).TeleportPosition = ToTeleportPosition(levelConfig); ((ModLevelObject)levelObject).Dialogues = new List<DialogueObject>(); ((ModLevelObject)levelObject).OphelineDialogues = new List<NPCDialogueObject>(); ((ModLevelObject)levelObject).HerbeDialogues = new List<NPCDialogueObject>(); if (levelConfig.Dialogues != null) { ((ModLevelObject)levelObject).Dialogues = levelConfig.Dialogues.ConvertAll((LevelDialogue dialogue) => (DialogueObject)(object)ToCustomDialogueObject(dialogue)); } if (levelConfig.OphelineDialogues != null) { ((ModLevelObject)levelObject).OphelineDialogues = levelConfig.OphelineDialogues.ConvertAll(ToNPCDialogueObject); } if (levelConfig.HerbeDialogues != null) { ((ModLevelObject)levelObject).HerbeDialogues = levelConfig.HerbeDialogues.ConvertAll(ToNPCDialogueObject); } } private static Vector2Int ToTeleportPosition(LevelMetadata levelConfig) { //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) if (levelConfig.TeleportX.HasValue && levelConfig.TeleportY.HasValue) { return new Vector2Int(levelConfig.TeleportX.Value, levelConfig.TeleportY.Value); } return new Vector2Int(-1, -1); } private static CustomDialogueObject ToCustomDialogueObject(LevelDialogue dialogue) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) CustomDialogueObject val = ScriptableObject.CreateInstance<CustomDialogueObject>(); if (dialogue.Lines != null) { val.DialogueLines = dialogue.Lines.ConvertAll(ToDialogueLine); } val.RequiresBunnyToPassBeforePlaying = dialogue.RequiresBunnyToPassBeforePlaying; val.RequiresNoBunnyCaptureThisLevel = dialogue.RequiresNoBunnyCaptureThisLevel; val.RequiresSpecificEntryDirection = dialogue.RequiresSpecificEntryDirection; val.SpecificEntryDirection = (Direction)dialogue.SpecificEntryDirection; val.RequiresBunnyAtSpecificRelativePosition = dialogue.RequiresBunnyAtSpecificRelativePosition; val.SpecificBunnyRelativePositions = new List<Vector2Int>(); if (dialogue.SpecificBunnyRelativePositions != null) { foreach (int[] specificBunnyRelativePosition in dialogue.SpecificBunnyRelativePositions) { if (specificBunnyRelativePosition.Length > 1) { val.SpecificBunnyRelativePositions.Add(new Vector2Int(specificBunnyRelativePosition[0], specificBunnyRelativePosition[1])); } } } val.ShouldForceTurnPaqueretteAtStart = dialogue.ShouldForceTurnPaqueretteAtStart; val.ForceTurnPaqueretteDirection = (Direction)dialogue.ForceTurnPaqueretteDirection; return val; } private static DialogueLine ToDialogueLine(LevelDialogueLine line) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown return (DialogueLine)new CustomDialogueLine { Headshot = line.Headshot, Content = line.Content }; } private static NPCDialogueObject ToNPCDialogueObject(LevelNPCDialogue dialogue) { NPCDialogueObject val = ScriptableObject.CreateInstance<NPCDialogueObject>(); ((Object)val).name = "BNYS::" + dialogue.Name; if (dialogue.Lines != null) { ((CustomDialogueObject)val).DialogueLines = dialogue.Lines.ConvertAll(ToDialogueLine); } val.RequiredCaptures = dialogue.RequiredCaptures; val.RequiredBabies = dialogue.RequiredBabies; val.RequiredHomeCaptures = dialogue.RequiredHomeCaptures; val.ShouldOnlyPlayOnce = dialogue.ShouldOnlyPlayOnce; return val; } } public abstract class BNYSModBunburrowBase : IBNYSModBunburrow, IModBunburrow { private BunburrowStyle style; private BunburrowRequirements requirements; private Vector2Int? customSignCoordinate; private LevelsList levelsList; protected BNYSPlugin Bnys { get; private set; } public BNYSWorld World { get; private set; } public Burrow BurrowModel { get; private set; } public string WorldName => World.Title; public string LocalName => BurrowModel.Name; public string WorldPrefix => World.Prefix; public string LocalIndicator => BurrowModel.Indicator; public bool IsVoid => BurrowModel.IsVoid; public int ID { get; set; } public string Name => WorldName + "::" + LocalName; public string Indicator => (string.IsNullOrEmpty(WorldPrefix) ? string.Empty : (WorldPrefix + "-")) + LocalIndicator; public BunburrowStyle Style { get { if ((Object)(object)style == (Object)null) { style = BNYSPlugin.ResolveStyle(BurrowModel.Style); } return style; } } public bool HasEntrance => BurrowModel.HasSurfaceEntry; public bool HasSign { get; private set; } = true; public BunburrowRequirements Requirements { get { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Expected O, but got Unknown if (requirements == null && BurrowModel.Requirements != null) { requirements = new BunburrowRequirements { Bunnies = BurrowModel.Requirements.Bunnies, Babies = BurrowModel.Requirements.Babies, HomeCaptures = BurrowModel.Requirements.HomeCaptures }; } return requirements; } } public LevelObject SurfaceLevel { get; set; } public BNYSModBunburrowBase(BNYSPlugin bnys, BNYSWorld worldModel, Burrow burrowModel) { Bnys = bnys; World = worldModel; BurrowModel = burrowModel; InitializeCustomSignCoordinate(); } public Vector2Int? OverrideSignCoordinate() { return customSignCoordinate; } private void InitializeCustomSignCoordinate() { //IL_00e3: Unknown result type (might be due to invalid IL or missing references) SurfaceCoordinate val = World.SurfaceEntries?.Where((SurfaceEntry se) => se.Coordinates != null)?.SelectMany((SurfaceEntry se) => se.Coordinates)?.Where((KeyValuePair<string, SurfaceCoordinate> kvp) => kvp.Key == LocalName)?.Select((KeyValuePair<string, SurfaceCoordinate> kvp) => kvp.Value)?.FirstOrDefault(); if (val == null) { return; } if (!val.NoSign) { if (val.Sign != null && val.Sign.Length > 1) { customSignCoordinate = new Vector2Int(val.Sign[0], val.Sign[1]); } } else { HasSign = false; } } public abstract LevelMetadata LoadLevel(int depth); public LevelsList GetLevels() { if ((Object)(object)levelsList == (Object)null) { levelsList = (LevelsList)(object)GenerateLevelsList(); } return levelsList; } public LevelObject GetSurfaceLevel() { return SurfaceLevel; } public List<Vector2Int> GetReleasePath() { return ((from kvp in World.SurfaceEntries?.Where((SurfaceEntry se) => se.ReleasePath != null).SelectMany((SurfaceEntry se) => se.ReleasePath) where kvp.Key == LocalName select kvp.Value).FirstOrDefault())?.Select((Func<int[], Vector2Int>)((int[] x) => new Vector2Int(x[0], -x[1]))).ToList(); } protected virtual BNYSLevelsList GenerateLevelsList() { BNYSLevelsList bNYSLevelsList = ScriptableObject.CreateInstance<BNYSLevelsList>(); bNYSLevelsList.ModBunburrow = this; bNYSLevelsList.Bnys = Bnys; ((Object)bNYSLevelsList).name = Name; ((ModLevelsList)bNYSLevelsList).MaximumDepth = BurrowModel.Depth; ((ModLevelsList)bNYSLevelsList).NumberOfRegularBunnies = BurrowModel.UpperBunnyCount; ((ModLevelsList)bNYSLevelsList).NumberOfTempleBunnies = BurrowModel.TempleBunnyCount; ((ModLevelsList)bNYSLevelsList).NumberOfHellBunnies = BurrowModel.HellBunnyCount; return bNYSLevelsList; } protected LevelMetadata CreateDefaultLevelMetadata() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown //IL_0031: Expected O, but got Unknown return new LevelMetadata { Name = "Failed Level Load", LiveReloading = true, IsHell = false, IsTemple = false, Tools = new LevelTools() }; } } public abstract class BNYSWorld { private GameCompatibility? compatibility; public CustomWorld Config { get; private set; } public string Title => Config.Title; public string Prefix => Config.Prefix; public List<Burrow> Burrows => Config.Burrows; public List<SurfaceEntry> SurfaceEntries => Config.SurfaceEntries; public List<BNYSModBunburrowBase> ModBurrows { get; set; } public List<LevelObject> GeneratedSurfaceLevels { get; set; } public GameCompatibility Compatibility { get { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) if (!compatibility.HasValue) { compatibility = ResolveCompatibility(); } return compatibility.Value; } } public BNYSWorld(CustomWorld config) { Config = config; } private GameCompatibility ResolveCompatibility() { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) try { GameCompatibility val = GameRules.ForVersion(Config.CompatibleVersion); if ((int)val != 0) { Debug.Log((object)("[BNYS] World '" + Title + "' is compatible with game " + Config.CompatibleVersion + ": using v" + GameRules.ToVersionString(val) + " rules.")); } return val; } catch (Exception ex) when (ex is FormatException || ex is ArgumentException || ex is OverflowException) { Debug.LogError((object)("[BNYS] World '" + Title + "' has an invalid CompatibleVersion '" + Config.CompatibleVersion + "'; using current game rules.")); return (GameCompatibility)0; } } public abstract BNYSModBunburrowBase GenerateBunburrow(BNYSPlugin pluginRef, string bunburrowName); } internal class ContentValidator { private const string RESTRICTED_TILES = "^(F|P[0-9]+|N[0-9]+|X|C|A|Y(?:{.*})?)|T\\{\\.*[PS].*\\}$"; private static readonly Regex restrictedTileRegex = new Regex("^(F|P[0-9]+|N[0-9]+|X|C|A|Y(?:{.*})?)|T\\{\\.*[PS].*\\}$"); public static List<LevelValidationError> ValidateLevelContent(string content) { List<string> tilesFromContent = TileValidator.GetTilesFromContent(content); List<LevelValidationError> list = new List<LevelValidationError>(); if (tilesFromContent.Count > 135) { list.Add(new LevelValidationError("Level has too many tiles", isWarning: true)); } if (tilesFromContent.Count < 135) { list.Add(new LevelValidationError("Level has too few tiles")); } foreach (var (text, num) in tilesFromContent.Select((string t, int i) => (t: t, i: i))) { if (restrictedTileRegex.IsMatch(text) || !TileValidator.ValidateTile(text)) { list.Add(new TileValidationError("Tile '" + text + "' is not valid", num / 15, num % 15)); } } return list; } } public class EmergencyLevelsList : ModLevelsList { private LevelObject defaultLevel; public BNYSPlugin Bnys { get; set; } public override LevelObject LoadLevel(int depth, LoadingContext loadingContext) { if ((Object)(object)defaultLevel == (Object)null) { defaultLevel = GenerateDefaultLevel(); } Bnys.Logger.LogError((object)"Something went wrong - loading default level!"); return defaultLevel; } private LevelObject GenerateDefaultLevel() { ModLevelObject obj = ScriptableObject.CreateInstance<ModLevelObject>(); obj.CustomNameKey = "Default Level"; obj.BunburrowName = "Emergency List"; obj.Depth = 1; obj.Content = DefaultLevel.Content; obj.BunburrowStyle = AssetsManager.BunburrowsListOfStyles[(Bunburrow)0]; return (LevelObject)(object)obj; } } internal class ExtendedSurfaceLevelGenerator { [Flags] private enum SurfaceType { None = 0, Coordinates = 1, Grid = 2 } public const string WallRow = "W,W,W,W,W,W,W,W,W,W,W,W,W,W,W"; public const string TopRow = "W,T,T,T,T,T,T,T,T,T,T,T,T,W,W"; public const string SpaceRow = "W,T,T,T,T,T,T,T,T,T,T,T,T,W,W"; public const string EntryRow = "W,T,T,T,{0},T,T,{1},T,T,{2},T,T,W,W"; public const string OpenRow = "T,T,T,T,T,T,T,T,T,T,T,T,T,T,T"; public static void CreateSurfaceLevels(BNYSWorld world, List<BNYSModBunburrowBase> modBunburrows, LevelObject precedingLevel) { if (world.GeneratedSurfaceLevels == null) { Dictionary<string, BNYSModBunburrowBase> burrows = modBunburrows.Where((BNYSModBunburrowBase b) => b.BurrowModel.Depth > 0).ToDictionary((BNYSModBunburrowBase b) => b.LocalName); world.GeneratedSurfaceLevels = GenerateLevels(precedingLevel, world.Config, burrows).ToList(); } else { LinkSurface(precedingLevel, world.GeneratedSurfaceLevels.First()); } } public static void LinkSurface(LevelObject shop, LevelObject rightOfShop) { shop.SideLevels.SetPart((Direction)1, rightOfShop); } private static IEnumerable<LevelObject> GenerateLevels(LevelObject precedingLevel, CustomWorld world, Dictionary<string, BNYSModBunburrowBase> burrows) { IEnumerable<SurfaceEntry> surfaceEntries = world.SurfaceEntries; foreach (SurfaceEntry item3 in surfaceEntries ?? Enumerable.Empty<SurfaceEntry>()) { string text = null; List<BNYSModBunburrowBase> list = null; switch (GetSurfaceType(item3)) { case SurfaceType.Coordinates: Console.WriteLine(world.Title + ": Creating Coordinate Surface World!"); (text, list) = GenerateCoordinatesSurfaceContent(item3.Coordinates, burrows); break; case SurfaceType.Grid: Console.WriteLine(world.Title + ": Creating Grid Surface World!"); (text, list) = GenerateGridSurfaceContent(item3.Grid, burrows); break; } if (list == null || string.IsNullOrEmpty(text) || list.Count <= 0) { continue; } Console.WriteLine($"{list.Count} burrows placed in surface world"); precedingLevel = GenerateLevel(world, text, precedingLevel); foreach (BNYSModBunburrowBase item4 in list) { item4.SurfaceLevel = precedingLevel; } yield return precedingLevel; } List<BNYSModBunburrowBase> enterableBurrows = burrows.Values.Where((BNYSModBunburrowBase b) => b.BurrowModel.HasSurfaceEntry).ToList(); while (enterableBurrows.Any()) { Console.WriteLine(world.Title + ": Creating DEFAULT Surface World"); (string, List<BNYSModBunburrowBase>) tuple3 = GenerateDefaultSurfaceLevel(enterableBurrows); string item = tuple3.Item1; List<BNYSModBunburrowBase> item2 = tuple3.Item2; precedingLevel = GenerateLevel(world, item, precedingLevel); foreach (BNYSModBunburrowBase item5 in item2) { item5.SurfaceLevel = precedingLevel; } yield return precedingLevel; } } private static LevelObject GenerateLevel(CustomWorld world, string levelContent, LevelObject previousLevel) { ModLevelObject val = ScriptableObject.CreateInstance<ModLevelObject>(); ((Object)val).name = "SurfaceRight BNYS"; val.Content = levelContent; val.IsSurface = true; val.CustomNameKey = world.Title; val.SpecificBackground = SurfaceBurrowsPatch.ExtendedBackground; val.BunburrowStyle = previousLevel.BunburrowStyle; val.SideLevels.SetPart((Direction)0, previousLevel); if ((Object)(object)previousLevel != (Object)null) { previousLevel.SideLevels.SetPart((Direction)1, (LevelObject)(object)val); } return (LevelObject)(object)val; } private static (string, List<BNYSModBunburrowBase>) GenerateCoordinatesSurfaceContent(Dictionary<string, SurfaceCoordinate> coordinates, Dictionary<string, BNYSModBunburrowBase> bunburrows) { string[][] emptyLevelContent = GetEmptyLevelContent(); List<BNYSModBunburrowBase> list = new List<BNYSModBunburrowBase>(); foreach (KeyValuePair<string, SurfaceCoordinate> coordinate in coordinates) { if (!bunburrows.TryGetValue(coordinate.Key, out var value)) { continue; } SurfaceCoordinate value2 = coordinate.Value; if (((value2 != null) ? value2.Hole : null) != null && coordinate.Value.Hole.Length != 0) { int num = coordinate.Value.Hole[0]; int num2 = 3; if (coordinate.Value.Hole.Length > 1) { num2 = coordinate.Value.Hole[1]; } emptyLevelContent[num2][num] = "N" + value.ID; list.Add(value); bunburrows.Remove(coordinate.Key); } } return (string.Join(",", emptyLevelContent.Select((string[] row) => string.Join(",", row)).ToArray()), list); } private static (string, List<BNYSModBunburrowBase>) GenerateGridSurfaceContent(SurfaceEntryGrid grid, Dictionary<string, BNYSModBunburrowBase> bunburrows) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Expected O, but got Unknown //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Expected O, but got Unknown //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Expected O, but got Unknown //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Expected O, but got Unknown //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Expected O, but got Unknown //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Expected O, but got Unknown //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Expected O, but got Unknown //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Expected O, but got Unknown //IL_012e: Unknown result type (might be due to invalid IL or missing references) //IL_0138: Expected O, but got Unknown Dictionary<string, SurfaceCoordinate> coordinates = new Dictionary<string, SurfaceCoordinate>(); Action<string, SurfaceCoordinate> action = delegate(string burrowName, SurfaceCoordinate coordinate) { if (!string.IsNullOrEmpty(burrowName)) { coordinates.Add(burrowName, coordinate); } }; action(grid.NW, new SurfaceCoordinate(new int[2] { 4, 1 })); action(grid.N, new SurfaceCoordinate(new int[2] { 7, 1 })); action(grid.NE, new SurfaceCoordinate(new int[2] { 10, 1 })); action(grid.W, new SurfaceCoordinate(new int[2] { 4, 3 })); action(grid.C, new SurfaceCoordinate(new int[2] { 7, 3 })); action(grid.E, new SurfaceCoordinate(new int[2] { 10, 3 })); action(grid.SW, new SurfaceCoordinate(new int[2] { 4, 5 })); action(grid.S, new SurfaceCoordinate(new int[2] { 7, 5 })); action(grid.SE, new SurfaceCoordinate(new int[2] { 10, 5 })); return GenerateCoordinatesSurfaceContent(coordinates, bunburrows); } private static (string, List<BNYSModBunburrowBase>) GenerateDefaultSurfaceLevel(List<BNYSModBunburrowBase> bunburrows) { List<BNYSModBunburrowBase> list = new List<BNYSModBunburrowBase>(); BNYSModBunburrowBase bNYSModBunburrowBase = bunburrows.FirstOrDefault(); if (bNYSModBunburrowBase != null) { bunburrows.Remove(bNYSModBunburrowBase); list.Add(bNYSModBunburrowBase); } BNYSModBunburrowBase bNYSModBunburrowBase2 = bunburrows.FirstOrDefault(); if (bNYSModBunburrowBase2 != null) { bunburrows.Remove(bNYSModBunburrowBase2); list.Add(bNYSModBunburrowBase2); } BNYSModBunburrowBase bNYSModBunburrowBase3 = bunburrows.FirstOrDefault(); if (bNYSModBunburrowBase3 != null) { bunburrows.Remove(bNYSModBunburrowBase3); list.Add(bNYSModBunburrowBase3); } return (GetBasicLevelContent(bNYSModBunburrowBase, bNYSModBunburrowBase2, bNYSModBunburrowBase3), list); } private static string[][] GetEmptyLevelContent() { return new string[9] { "W,W,W,W,W,W,W,W,W,W,W,W,W,W,W", "W,T,T,T,T,T,T,T,T,T,T,T,T,W,W", "W,T,T,T,T,T,T,T,T,T,T,T,T,W,W", string.Format("W,T,T,T,{0},T,T,{1},T,T,{2},T,T,W,W", "T", "T", "T"), "T,T,T,T,T,T,T,T,T,T,T,T,T,T,T", "T,T,T,T,T,T,T,T,T,T,T,T,T,T,T", "T,T,T,T,T,T,T,T,T,T,T,T,T,T,T", "W,W,W,W,W,W,W,W,W,W,W,W,W,W,W", "W,W,W,W,W,W,W,W,W,W,W,W,W,W,W" }.Select((string r) => r.Split(',')).ToArray(); } private static string GetBasicLevelContent(BNYSModBunburrowBase first, BNYSModBunburrowBase second, BNYSModBunburrowBase third) { string[] value = new string[9] { "W,W,W,W,W,W,W,W,W,W,W,W,W,W,W", "W,T,T,T,T,T,T,T,T,T,T,T,T,W,W", "W,T,T,T,T,T,T,T,T,T,T,T,T,W,W", $"W,T,T,T,{GetLevelEntryCode(first)},T,T,{GetLevelEntryCode(second)},T,T,{GetLevelEntryCode(third)},T,T,W,W", "T,T,T,T,T,T,T,T,T,T,T,T,T,T,T", "T,T,T,T,T,T,T,T,T,T,T,T,T,T,T", "T,T,T,T,T,T,T,T,T,T,T,T,T,T,T", "W,W,W,W,W,W,W,W,W,W,W,W,W,W,W", "W,W,W,W,W,W,W,W,W,W,W,W,W,W,W" }; return string.Join(Environment.NewLine, value); } private static string GetLevelEntryCode(BNYSModBunburrowBase burrow) { if (burrow != null) { return "N" + burrow.ID; } return "T"; } private static SurfaceType GetSurfaceType(SurfaceEntry surfaceEntry) { SurfaceType surfaceType = SurfaceType.None; int num = 0; if (surfaceEntry.Coordinates != null) { surfaceType |= SurfaceType.Coordinates; num++; } if (surfaceEntry.Grid != null) { surfaceType |= SurfaceType.Grid; num++; } if (num > 1) { List<string> list = new List<string>(); foreach (SurfaceType item in Enum.GetValues(typeof(SurfaceType)).Cast<SurfaceType>()) { if (surfaceType.HasFlag(item) && item != SurfaceType.None) { list.Add(Enum.GetName(typeof(SurfaceType), item)); } } throw new Exception("SurfaceEntry cannot have both a Coordinates and Grid - please select only one."); } return surfaceType; } private static int CountFlags<T>(T instance) where T : Enum { int num = 0; foreach (T item in Enum.GetValues(typeof(T)).Cast<T>()) { if (instance.HasFlag(item)) { num++; } } return num; } } public interface IBNYSModBunburrow { string WorldName { get; } string LocalName { get; } string WorldPrefix { get; } string LocalIndicator { get; } } public class LevelValidationError { public string Message { get; private set; } public bool IsWarning { get; private set; } public LevelValidationError(string message, bool isWarning) { Message = message; IsWarning = isWarning; } public LevelValidationError(string message) : this(message, isWarning: false) { } public override string ToString() { return Message; } } internal class SurfaceBurrowsPatch { private const string PatchedTexture = "PatchedTexture"; private const string PatchedTexturePath = "ExtendedRegion.png"; public static Sprite EndingBackground; public static Sprite ExtendedBackground; public static void PatchSurfaceBurrows(LevelObject originalBurrows, LevelObject newRightExit) { //IL_005d: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)EndingBackground == (Object)null) { EndingBackground = originalBurrows.SpecificBackground; } if ((Object)(object)ExtendedBackground == (Object)null) { string path = Path.Combine(BNYSPlugin.rootDirectory, "ExtendedRegion.png"); if (!File.Exists(path)) { path = Path.Combine(BNYSPlugin.inlineDirectory, "ExtendedRegion.png"); } ExtendedBackground = ImportImage.ImportSprite("PatchedTexture", path, new Vector2(0f, 1f), 16f); } } } public class TileValidationError : LevelValidationError { public TileValidationError(string message, int row, int column) : base($"Tile on Row {row}, Column {column}: {message}") { } } } namespace Bunject.NewYardSystem.Levels.Web { public class BNYSWebModBunburrow : BNYSModBunburrowBase { public new WebWorld World { get; private set; } private Uri BurrowUri => new Uri(World.ProxyUri, base.BurrowModel.Directory + "/"); public BNYSWebModBunburrow(BNYSPlugin bnys, WebWorld worldModel, Burrow burrowModel) : base(bnys, worldModel, burrowModel) { World = worldModel; } protected override BNYSLevelsList GenerateLevelsList() { BNYSLevelsList bNYSLevelsList = base.GenerateLevelsList(); bNYSLevelsList.PermitReloading = true; bNYSLevelsList.DelayReloading = true; return bNYSLevelsList; } public override LevelMetadata LoadLevel(int depth) { string text = null; LevelMetadata val = null; Uri uri = new Uri(BurrowUri, $"{depth}.json"); try { val = uri.Load<LevelMetadata>(); val.IsWebLevel = true; } catch (Exception ex) { base.Bnys.Logger.LogError((object)$"{base.Name} - {depth}: File doesn't exist, Level json failed to load from web. Ensure {depth}.json exists and conforms to JSON standards."); base.Bnys.Logger.LogError((object)"Error loading files related to level:"); base.Bnys.Logger.LogError((object)Path.Combine(base.BurrowModel.Directory, depth.ToString())); base.Bnys.Logger.LogError((object)"Expected web endpoint:"); base.Bnys.Logger.LogError((object)uri.ToString()); base.Bnys.Logger.LogError((object)ex.Message); base.Bnys.Logger.LogError((object)ex); val = CreateDefaultLevelMetadata(); } if (string.IsNullOrEmpty(val.Content)) { Uri uri2 = new Uri(BurrowUri, $"{depth}.level"); try { text = uri2.Load(); val.IsWebLevel = true; } catch (Exception ex2) { base.Bnys.Logger.LogError((object)"Error loading files related to level:"); base.Bnys.Logger.LogError((object)Path.Combine(base.BurrowModel.Directory, depth.ToString())); base.Bnys.Logger.LogError((object)"Expected web path:"); base.Bnys.Logger.LogError((object)uri2); base.Bnys.Logger.LogError((object)ex2.Message); base.Bnys.Logger.LogError((object)ex2); } } if (string.IsNullOrEmpty(text)) { base.Bnys.Logger.LogError((object)$"{base.Name} - {depth}: Level content failed to load. Ensure {depth}.level exists and is appropriately formatted."); text = DefaultLevel.Content; } else { List<LevelValidationError> list = ContentValidator.ValidateLevelContent(text); if (list.Count > 0) { base.Bnys.Logger.LogWarning((object)$"{base.Name} - {depth}: Invalid level content found: "); foreach (LevelValidationError item in list) { if (item.IsWarning) { base.Bnys.Logger.LogWarning((object)item); } else { base.Bnys.Logger.LogError((object)item); } } } if (list.Any((LevelValidationError ve) => !ve.IsWarning)) { text = DefaultLevel.Content; } } val.Style = val.Style ?? base.BurrowModel.Style; val.Content = text; return val; } } public class WebWorld : BNYSWorld { public Uri ProxyUri { get; private set; } public WebWorld(CustomWorld config, Uri proxyUri) : base(config) { ProxyUri = proxyUri; } public override BNYSModBunburrowBase GenerateBunburrow(BNYSPlugin pluginRef, string bunburrowName) { return new BNYSWebModBunburrow(pluginRef, this, base.Burrows.First((Burrow b) => b.Name == bunburrowName)); } } } namespace Bunject.NewYardSystem.Levels.Local { public class BNYSLocalModBunburrow : BNYSModBunburrowBase { public new LocalWorld World { get; private set; } public BNYSLocalModBunburrow(BNYSPlugin bnys, LocalWorld worldModel, Burrow burrowModel) : base(bnys, worldModel, burrowModel) { World = worldModel; } public override LevelMetadata LoadLevel(int depth) { //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Expected O, but got Unknown string path = Path.Combine(base.BurrowModel.Directory, $"{depth}.level"); string path2 = Path.Combine(base.BurrowModel.Directory, $"{depth}.json"); string text = null; LevelMetadata val = null; if (File.Exists(path2)) { try { using StreamReader streamReader = new StreamReader(path2); val = (LevelMetadata)new JsonSerializer().Deserialize((TextReader)streamReader, typeof(LevelMetadata)); } catch (Exception ex) { base.Bnys.Logger.LogError((object)$"{base.Name} - {depth}: Level json failed to load. Ensure {depth}.json exists and conforms to JSON standards."); base.Bnys.Logger.LogError((object)"Error loading files related to level:"); base.Bnys.Logger.LogError((object)Path.Combine(base.BurrowModel.Directory, depth.ToString())); base.Bnys.Logger.LogError((object)ex.Message); base.Bnys.Logger.LogError((object)ex); val = CreateDefaultLevelMetadata(); } } else { base.Bnys.Logger.LogError((object)$"{base.Name} - {depth}: Level json failed to load. Ensure {depth}.json exists and conforms to JSON standards."); base.Bnys.Logger.LogError((object)"Error loading files related to level:"); base.Bnys.Logger.LogError((object)Path.Combine(base.BurrowModel.Directory, depth.ToString())); val = CreateDefaultLevelMetadata(); } if (string.IsNullOrEmpty(val.Content) && File.Exists(path)) { try { text = File.ReadAllText(path); } catch (Exception ex2) { base.Bnys.Logger.LogError((object)"Error loading files related to level:"); base.Bnys.Logger.LogError((object)Path.Combine(base.BurrowModel.Directory, depth.ToString())); base.Bnys.Logger.LogError((object)ex2.Message); base.Bnys.Logger.LogError((object)ex2); } } if (string.IsNullOrEmpty(text)) { base.Bnys.Logger.LogError((object)$"{base.Name} - {depth}: Level content failed to load. Ensure {depth}.level exists and is appropriately formatted."); text = DefaultLevel.Content; } else { List<LevelValidationError> list = ContentValidator.ValidateLevelContent(text); if (list.Count > 0) { base.Bnys.Logger.LogWarning((object)$"{base.Name} - {depth}: Invalid level content found: "); foreach (LevelValidationError item in list) { if (item.IsWarning) { base.Bnys.Logger.LogWarning((object)item); } else { base.Bnys.Logger.LogError((object)item); } } } if (list.Any((LevelValidationError ve) => !ve.IsWarning)) { text = DefaultLevel.Content; } } val.Style = val.Style ?? base.BurrowModel.Style; val.Content = text; return val; } } public class LocalWorld : BNYSWorld { public LocalWorld(CustomWorld config) : base(config) { } public override BNYSModBunburrowBase GenerateBunburrow(BNYSPlugin pluginRef, string bunburrowName) { return new BNYSLocalModBunburrow(pluginRef, this, base.Burrows.First((Burrow b) => b.Name == bunburrowName)); } } } namespace Bunject.NewYardSystem.Levels.Archive { public class ArchiveWorld : BNYSWorld { public WorldArchive Archive { get; private set; } public string RootFolder { get; private set; } public ArchiveWorld(CustomWorld config, WorldArchive archive, string rootFolder) : base(config) { Archive = archive; RootFolder = rootFolder; } public Stream OpenEntry(string path) { return Archive.Open(RootFolder + path); } public override BNYSModBunburrowBase GenerateBunburrow(BNYSPlugin pluginRef, string bunburrowName) { return new BNYSArchiveModBunburrow(pluginRef, this, base.Burrows.First((Burrow b) => b.Name == bunburrowName)); } } public class BNYSArchiveModBunburrow : BNYSModBunburrowBase { public new ArchiveWorld World { get; private set; } public BNYSArchiveModBunburrow(BNYSPlugin bnys, ArchiveWorld worldModel, Burrow burrowModel) : base(bnys, worldModel, burrowModel) { World = worldModel; } protected override BNYSLevelsList GenerateLevelsList() { BNYSLevelsList bNYSLevelsList = base.GenerateLevelsList(); bNYSLevelsList.PermitReloading = false; return bNYSLevelsList; } public override LevelMetadata LoadLevel(int depth) { //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Expected O, but got Unknown string path = base.BurrowModel.Directory + "/" + $"{depth}.level"; string text = base.BurrowModel.Directory + "/" + $"{depth}.json"; string text2 = null; LevelMetadata val = null; Stream stream = World.OpenEntry(text); if (stream != null) { try { using (stream) { using StreamReader streamReader = new StreamReader(stream); val = (LevelMetadata)new JsonSerializer().Deserialize((TextReader)streamReader, typeof(LevelMetadata)); } } catch (Exception ex) { base.Bnys.Logger.LogError((object)$"{base.Name} - {depth}: Level json failed to load. Ensure {depth}.json exists and conforms to JSON standards."); base.Bnys.Logger.LogError((object)"Error reading zip file entry related to level:"); base.Bnys.Logger.LogError((object)text); base.Bnys.Logger.LogError((object)ex.Message); base.Bnys.Logger.LogError((object)ex); val = CreateDefaultLevelMetadata(); } } else { base.Bnys.Logger.LogError((object)$"{base.Name} - {depth}: Level json failed to load. Ensure {depth}.json exists and conforms to JSON standards."); base.Bnys.Logger.LogError((object)"Could not find zip file entry:"); base.Bnys.Logger.LogError((object)text); val = CreateDefaultLevelMetadata(); } if (string.IsNullOrEmpty(val.Content)) { Stream stream2 = World.OpenEntry(path); if (stream2 != null) { try { using (stream2) { using StreamReader streamReader2 = new StreamReader(stream2); text2 = streamReader2.ReadToEnd(); } } catch (Exception ex2) { base.Bnys.Logger.LogError((object)"Error reading archive entry related to level content:"); base.Bnys.Logger.LogError((object)Path.Combine(base.BurrowModel.Directory, depth.ToString())); base.Bnys.Logger.LogError((object)ex2.Message); base.Bnys.Logger.LogError((object)ex2); } } } if (string.IsNullOrEmpty(text2)) { base.Bnys.Logger.LogError((object)$"{base.Name} - {depth}: Level content failed to load. Ensure {depth}.level exists and is appropriately formatted."); text2 = DefaultLevel.Content; } else { List<LevelValidationError> list = ContentValidator.ValidateLevelContent(text2); if (list.Count > 0) { base.Bnys.Logger.LogWarning((object)$"{base.Name} - {depth}: Invalid level content found: "); foreach (LevelValidationError item in list) { if (item.IsWarning) { base.Bnys.Logger.LogWarning((object)item); } else { base.Bnys.Logger.LogError((object)item); } } } if (list.Any((LevelValidationError ve) => !ve.IsWarning)) { text2 = DefaultLevel.Content; } } val.Style = val.Style ?? base.BurrowModel.Style; val.Content = text2; return val; } } public class WorldArchive { private readonly Dictionary<string, byte[]> entries = new Dictionary<string, byte[]>(); private const long MaxUnpackedBytes = 67108864L; private const int CopyBufferSize = 81920; public IEnumerable<string> EntryNames => entries.Keys; public static WorldArchive Load(string path) { WorldArchive worldArchive = new WorldArchive(); byte[] array = new byte[81920]; long num = 0L; IArchive val = ArchiveFactory.OpenArchive(path, (ReaderOptions)null); try { foreach (IArchiveEntry item in val.Entries.Where((IArchiveEntry e) => !((IEntry)e).IsDirectory)) { using Stream stream = item.OpenEntryStream(); using MemoryStream memoryStream = new MemoryStream(); int num2; while ((num2 = stream.Read(array, 0, array.Length)) > 0) { num += num2; if (num > 67108864) { throw new InvalidDataException("Archive unpacks to more than 64 MB."); } memoryStream.Write(array, 0, num2); } worldArchive.entries[((IEntry)item).Key.Replace('\\', '/')] = memoryStream.ToArray(); } return worldArchive; } finally { ((IDisposable)val)?.Dispose(); } } public Stream Open(string name) { if (!entries.TryGetValue(name, out var value)) { return null; } return new MemoryStream(value, writable: false); } } } namespace Bunject.NewYardSystem.Exceptions { public class InvalidBurrowLinkException : Exception { public InvalidBurrowLinkException(string worldName, string burrowName, string linkDirection, string linkName) : base(worldName + " - " + burrowName + " has an invalid " + linkDirection + " burrow link: '" + linkName + "'") { } } } namespace Bunject.NewYardSystem.Computer { internal class CreditsPage : BasicCustomComputerPageController { private string content; public CustomWorld World { get; set; } public override string ButtonName => "BNYSCredits"; public override string ButtonText => "Level Credits"; protected override string HeaderText { get { string text = StartGold(); CustomWorld world = World; return text + ((world != null) ? world.Title : null) + EndColor(); } } protected override string ContentText => GetContentText(); public override bool ShouldShow() { return World != null; } private string GetContentText() { if (World != null && content == null) { content = "By " + StartGold() + GetAuthor() + EndColor() + Environment.NewLine + Environment.NewLine + GetDescription(World) + GetCompatibilityText(); } return content; } private string GetCompatibilityText() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) GameCompatibility compatibility = GameRules.Compatibility; if ((int)compatibility == 0) { return string.Empty; } return Environment.NewLine + Environment.NewLine + "Compatibility: v" + GameRules.ToVersionString(compatibility); } private string GetAuthor() { CustomWorld world = World; if (string.IsNullOrEmpty((world != null) ? world.Author : null)) { return "Bunknown Author"; } CustomWorld world2 = World; if (world2 == null) { return null; } return world2.Author; } private static string StartGold() { return "<color=#D3AF37>"; } private static string EndColor() { return "</color>"; } private static string GetDescription(CustomWorld world) { if (!string.IsNullOrWhiteSpace(world.Description)) { return world.Description; } return "A custom world lovingly crafted for your bunjoyment."; } } }
Bunject.NewYardSystem.Model.dll
Decompiled 2 days agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using Bunject.NewYardSystem.Model; using Bunject.NewYardSystem.Utility; using Newtonsoft.Json; using Newtonsoft.Json.Linq; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Bunject.NewYardSystem.Model")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+0eddd3790f0056a92947bfc95a9e9166555bfa48")] [assembly: AssemblyProduct("Bunject.NewYardSystem.Model")] [assembly: AssemblyTitle("Bunject.NewYardSystem.Model")] [assembly: AssemblyVersion("1.0.0.0")] namespace Bunject.NewYardSystem.Utility { public class CoordinateJsonConverter : JsonConverter<SurfaceCoordinate> { public override bool CanWrite => false; public override SurfaceCoordinate ReadJson(JsonReader reader, Type objectType, SurfaceCoordinate existingValue, bool hasExistingValue, JsonSerializer serializer) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Invalid comparison between Unknown and I4 //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Invalid comparison between Unknown and I4 JsonToken tokenType = reader.TokenType; if ((int)tokenType != 1) { if ((int)tokenType == 2) { return new SurfaceCoordinate(((JContainer)JArray.Load(reader)).Values<int>().ToArray()); } return new SurfaceCoordinate(); } JToken val = JToken.Load(reader); SurfaceCoordinate surfaceCoordinate = new SurfaceCoordinate(); JToken obj = val[(object)"Hole"]; surfaceCoordinate.Hole = ((obj == null) ? null : obj.Values<int>()?.ToArray()); JToken obj2 = val[(object)"Sign"]; surfaceCoordinate.Sign = ((obj2 == null) ? null : obj2.Values<int>()?.ToArray()); surfaceCoordinate.NoSign = val.Value<bool?>((object)"NoSign") == true; return surfaceCoordinate; } public override void WriteJson(JsonWriter writer, SurfaceCoordinate value, JsonSerializer serializer) { throw new NotImplementedException(); } } } namespace Bunject.NewYardSystem.Model { public class Burrow { public string Directory { get; set; } public string Name { get; set; } public string Indicator { get; set; } public string Style { get; set; } = "Pink"; public bool HasSurfaceEntry { get; set; } public bool IsVoid { get; set; } public int UpperBunnyCount { get; set; } public int TempleBunnyCount { get; set; } public int HellBunnyCount { get; set; } public int Depth { get; set; } public BurrowRequirements Requirements { get; set; } = new BurrowRequirements(); public BurrowLinks Links { get; set; } = new BurrowLinks(); public List<int> ElevatorDepths { get; set; } = new List<int>(); } public class BurrowLinks { public string Left { get; set; } public string Up { get; set; } public string Right { get; set; } public string Down { get; set; } } public class BurrowRequirements { public int Bunnies { get; set; } public int Babies { get; set; } public int HomeCaptures { get; set; } } public enum BurrowStyle { Pink, Aquatic, Sunken, Hay, Forgotten, Purple, Spooky, Ghostly, Void, Temple, Hell, PinkHell, AquaticHell, SunkenHell, HayHell, ForgottenHell, PurpleHell, SpookyHell, GhostlyHell, HellTemple } public static class BurrowStyles { public static bool TryParse(string name, out BurrowStyle style) { style = BurrowStyle.Pink; string text = Enum.GetNames(typeof(BurrowStyle)).FirstOrDefault((string n) => string.Equals(n, name, StringComparison.OrdinalIgnoreCase)); if (text == null) { return false; } style = (BurrowStyle)Enum.Parse(typeof(BurrowStyle), text); return true; } } public class CustomBunburrowModel { public string World { get; set; } public string Name { get; set; } public string Prefix { get; set; } public string Indicator { get; set; } [JsonIgnore] public int ID { get; set; } } public class CustomWorld { public string ProxyURL { get; set; } public bool Enabled { get; set; } = true; public bool LiveReloading { get; set; } public bool TeleportAnywhereUnlocked { get; set; } public string CompatibleVersion { get; set; } public string Title { get; set; } public string Prefix { get; set; } public string Author { get; set; } public string Description { get; set; } public List<Burrow> Burrows { get; set; } public List<SurfaceEntry> SurfaceEntries { get; set; } } public enum Direction { Left, Right, Up, Down } public class GlobalConfig { public List<string> WebBurrows { get; set; } } public class LevelMetadata { public string Name { get; set; } public bool LiveReloading { get; set; } public LevelTools Tools { get; set; } = new LevelTools(); public string Style { get; set; } public bool IsTemple { get; set; } public bool IsHell { get; set; } public int? Difficulty { get; set; } public string Content { get; set; } public bool IsWebLevel { get; set; } public List<LevelHint> Hints { get; set; } public int[] Teleport { get { if (TeleportX.HasValue && TeleportY.HasValue) { return new int[2] { TeleportX.Value, TeleportY.Value }; } return null; } set { if (value != null && value.Length == 2) { TeleportX = value[0]; TeleportY = value[1]; } else { TeleportX = null; TeleportY = null; } } } public int? TeleportX { get; set; } public int? TeleportY { get; set; } public List<LevelDialogue> Dialogues { get; set; } = new List<LevelDialogue>(); public List<LevelNPCDialogue> OphelineDialogues { get; set; } = new List<LevelNPCDialogue>(); public List<LevelNPCDialogue> HerbeDialogues { get; set; } = new List<LevelNPCDialogue>(); } public class LevelTools { public int Traps { get; set; } public int Pickaxes { get; set; } public int Carrots { get; set; } public int Shovels { get; set; } } public class LevelHint { public int[] Position { get { return new int[2] { PositionX, PositionY }; } set { if (value != null && value.Length == 2) { PositionX = value[0]; PositionY = value[1]; } else { PositionX = 0; PositionY = 0; } } } public int PositionX { get; set; } public int PositionY { get; set; } public Direction Orientation { get; set; } = Direction.Down; } public class LevelDialogueLine { public string Headshot { get; set; } public string Content { get; set; } } public class LevelDialogue { public List<LevelDialogueLine> Lines { get; set; } public bool RequiresBunnyToPassBeforePlaying { get; set; } public bool RequiresNoBunnyCaptureThisLevel { get; set; } public bool RequiresSpecificEntryDirection { get; set; } public Direction SpecificEntryDirection { get; set; } = Direction.Down; public bool RequiresBunnyAtSpecificRelativePosition { get; set; } public List<int[]> SpecificBunnyRelativePositions { get; set; } public bool ShouldForceTurnPaqueretteAtStart { get; set; } public Direction ForceTurnPaqueretteDirection { get; set; } } public class LevelNPCDialogue { public string Name { get; set; } = ""; public List<LevelDialogueLine> Lines { get; set; } public int RequiredCaptures { get; set; } public int RequiredBabies { get; set; } public int RequiredHomeCaptures { get; set; } public bool ShouldOnlyPlayOnce { get; set; } } public class SurfaceEntry { public Dictionary<string, SurfaceCoordinate> Coordinates { get; set; } public Dictionary<string, List<int[]>> ReleasePath { get; set; } public SurfaceEntryGrid Grid { get; set; } } [JsonConverter(typeof(CoordinateJsonConverter))] public class SurfaceCoordinate { public int[] Hole { get; set; } public int[] Sign { get; set; } public bool NoSign { get; set; } public SurfaceCoordinate() { } public SurfaceCoordinate(params int[] holeCoordinates) { Hole = holeCoordinates; } } public class SurfaceEntryGrid { public string NW { get; set; } public string N { get; set; } public string NE { get; set; } public string W { get; set; } public string C { get; set; } public string E { get; set; } public string SW { get; set; } public string S { get; set; } public string SE { get; set; } } }
SharpCompress.dll
Decompiled 2 days ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; using System.Buffers.Binary; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Numerics; 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.Security.Cryptography; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Sources; using Microsoft.CodeAnalysis; using SharpCompress.Algorithms; using SharpCompress.Archives; using SharpCompress.Archives.GZip; using SharpCompress.Archives.Rar; using SharpCompress.Archives.SevenZip; using SharpCompress.Archives.Tar; using SharpCompress.Archives.Zip; using SharpCompress.Common; using SharpCompress.Common.Ace; using SharpCompress.Common.Ace.Headers; using SharpCompress.Common.Arc; using SharpCompress.Common.Arj; using SharpCompress.Common.Arj.Headers; using SharpCompress.Common.GZip; using SharpCompress.Common.Lzw; using SharpCompress.Common.Options; using SharpCompress.Common.Rar; using SharpCompress.Common.Rar.Headers; using SharpCompress.Common.SevenZip; using SharpCompress.Common.Tar; using SharpCompress.Common.Tar.Headers; using SharpCompress.Common.Zip; using SharpCompress.Common.Zip.Headers; using SharpCompress.Compressors; using SharpCompress.Compressors.ArcLzw; using SharpCompress.Compressors.Arj; using SharpCompress.Compressors.BZip2; using SharpCompress.Compressors.Deflate; using SharpCompress.Compressors.Deflate64; using SharpCompress.Compressors.Explode; using SharpCompress.Compressors.Filters; using SharpCompress.Compressors.LZMA; using SharpCompress.Compressors.LZMA.LZ; using SharpCompress.Compressors.LZMA.RangeCoder; using SharpCompress.Compressors.LZMA.Utilities; using SharpCompress.Compressors.Lzw; using SharpCompress.Compressors.PPMd; using SharpCompress.Compressors.PPMd.H; using SharpCompress.Compressors.PPMd.I1; using SharpCompress.Compressors.RLE90; using SharpCompress.Compressors.Rar; using SharpCompress.Compressors.Rar.UnpackV1; using SharpCompress.Compressors.Rar.UnpackV1.Decode; using SharpCompress.Compressors.Rar.UnpackV1.PPM; using SharpCompress.Compressors.Rar.UnpackV2017; using SharpCompress.Compressors.Rar.VM; using SharpCompress.Compressors.Reduce; using SharpCompress.Compressors.Shrink; using SharpCompress.Compressors.Squeezed; using SharpCompress.Compressors.Xz; using SharpCompress.Compressors.Xz.Filters; using SharpCompress.Compressors.ZStandard; using SharpCompress.Compressors.ZStandard.Unsafe; using SharpCompress.Crypto; using SharpCompress.Factories; using SharpCompress.IO; using SharpCompress.Providers; using SharpCompress.Providers.Default; using SharpCompress.Readers; using SharpCompress.Readers.Ace; using SharpCompress.Readers.Arc; using SharpCompress.Readers.Arj; using SharpCompress.Readers.GZip; using SharpCompress.Readers.Lzw; using SharpCompress.Readers.Rar; using SharpCompress.Readers.Tar; using SharpCompress.Readers.Zip; using SharpCompress.Writers; using SharpCompress.Writers.GZip; using SharpCompress.Writers.SevenZip; using SharpCompress.Writers.Tar; using SharpCompress.Writers.Zip; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: CLSCompliant(false)] [assembly: InternalsVisibleTo("SharpCompress.Test,PublicKey=0024000004800000940000000602000000240000525341310004000001000100158bebf1433f76dffc356733c138babea7a47536c65ed8009b16372c6f4edbb20554db74a62687f56b97c20a6ce8c4b123280279e33c894e7b3aa93ab3c573656fde4db576cfe07dba09619ead26375b25d2c4a8e43f7be257d712b0dd2eb546f67adb09281338618a58ac834fc038dd7e2740a7ab3591826252e4f4516306dc")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Adam Hathcock")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright (c) 2025 Adam Hathcock")] [assembly: AssemblyDescription("SharpCompress is a compression library for NET 4.8/NET Standard 2.0/NET Standard 2.1/NET 5.0/NET 6.0/NET 7.0/NET 8.0/NET 9.0/NET 10.0 that can unrar, decompress 7zip, decompress xz, zip/unzip, tar/untar lzip/unlzip, bzip2/unbzip2 and gzip/ungzip with forward-only reading and file random access APIs. Write support for zip/tar/bzip2/gzip/7zip is implemented.")] [assembly: AssemblyFileVersion("0.50.12")] [assembly: AssemblyInformationalVersion("0.50.12")] [assembly: AssemblyMetadata("RepositoryUrl", "")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.50.12.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [CompilerGenerated] internal sealed class <>z__ReadOnlyArray<T> : IEnumerable, ICollection, IList, IEnumerable<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection<T>, IList<T> { int ICollection.Count => _items.Length; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => this; object IList.this[int index] { get { return _items[index]; } set { throw new NotSupportedException(); } } bool IList.IsFixedSize => true; bool IList.IsReadOnly => true; int IReadOnlyCollection<T>.Count => _items.Length; T IReadOnlyList<T>.this[int index] => _items[index]; int ICollection<T>.Count => _items.Length; bool ICollection<T>.IsReadOnly => true; T IList<T>.this[int index] { get { return _items[index]; } set { throw new NotSupportedException(); } } public <>z__ReadOnlyArray(T[] items) { _items = items; } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_items).GetEnumerator(); } void ICollection.CopyTo(Array array, int index) { ((ICollection)_items).CopyTo(array, index); } int IList.Add(object value) { throw new NotSupportedException(); } void IList.Clear() { throw new NotSupportedException(); } bool IList.Contains(object value) { return ((IList)_items).Contains(value); } int IList.IndexOf(object value) { return ((IList)_items).IndexOf(value); } void IList.Insert(int index, object value) { throw new NotSupportedException(); } void IList.Remove(object value) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return ((IEnumerable<T>)_items).GetEnumerator(); } void ICollection<T>.Add(T item) { throw new NotSupportedException(); } void ICollection<T>.Clear() { throw new NotSupportedException(); } bool ICollection<T>.Contains(T item) { return ((ICollection<T>)_items).Contains(item); } void ICollection<T>.CopyTo(T[] array, int arrayIndex) { ((ICollection<T>)_items).CopyTo(array, arrayIndex); } bool ICollection<T>.Remove(T item) { throw new NotSupportedException(); } int IList<T>.IndexOf(T item) { return ((IList<T>)_items).IndexOf(item); } void IList<T>.Insert(int index, T item) { throw new NotSupportedException(); } void IList<T>.RemoveAt(int index) { throw new NotSupportedException(); } } [CompilerGenerated] internal sealed class <>z__ReadOnlySingleElementList<T> : IEnumerable, ICollection, IList, IEnumerable<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection<T>, IList<T> { private sealed class Enumerator : IDisposable, IEnumerator, IEnumerator<T> { object IEnumerator.Current => _item; T IEnumerator<T>.Current => _item; public Enumerator(T item) { _item = item; } bool IEnumerator.MoveNext() { if (!_moveNextCalled) { return _moveNextCalled = true; } return false; } void IEnumerator.Reset() { _moveNextCalled = false; } void IDisposable.Dispose() { } } int ICollection.Count => 1; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => this; object IList.this[int index] { get { if (index != 0) { throw new IndexOutOfRangeException(); } return _item; } set { throw new NotSupportedException(); } } bool IList.IsFixedSize => true; bool IList.IsReadOnly => true; int IReadOnlyCollection<T>.Count => 1; T IReadOnlyList<T>.this[int index] { get { if (index != 0) { throw new IndexOutOfRangeException(); } return _item; } } int ICollection<T>.Count => 1; bool ICollection<T>.IsReadOnly => true; T IList<T>.this[int index] { get { if (index != 0) { throw new IndexOutOfRangeException(); } return _item; } set { throw new NotSupportedException(); } } public <>z__ReadOnlySingleElementList(T item) { _item = item; } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(_item); } void ICollection.CopyTo(Array array, int index) { array.SetValue(_item, index); } int IList.Add(object value) { throw new NotSupportedException(); } void IList.Clear() { throw new NotSupportedException(); } bool IList.Contains(object value) { return EqualityComparer<T>.Default.Equals(_item, (T)value); } int IList.IndexOf(object value) { if (!EqualityComparer<T>.Default.Equals(_item, (T)value)) { return -1; } return 0; } void IList.Insert(int index, object value) { throw new NotSupportedException(); } void IList.Remove(object value) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new Enumerator(_item); } void ICollection<T>.Add(T item) { throw new NotSupportedException(); } void ICollection<T>.Clear() { throw new NotSupportedException(); } bool ICollection<T>.Contains(T item) { return EqualityComparer<T>.Default.Equals(_item, item); } void ICollection<T>.CopyTo(T[] array, int arrayIndex) { array[arrayIndex] = _item; } bool ICollection<T>.Remove(T item) { throw new NotSupportedException(); } int IList<T>.IndexOf(T item) { if (!EqualityComparer<T>.Default.Equals(_item, item)) { return -1; } return 0; } void IList<T>.Insert(int index, T item) { throw new NotSupportedException(); } void IList<T>.RemoveAt(int index) { throw new NotSupportedException(); } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] internal sealed class IsUnmanagedAttribute : Attribute { } [CompilerGenerated] [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] [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] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NativeIntegerAttribute : Attribute { public readonly bool[] TransformFlags; public NativeIntegerAttribute() { TransformFlags = new bool[1] { true }; } public NativeIntegerAttribute(bool[] P_0) { TransformFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace Microsoft.CodeAnalysis { [Embedded] [AttributeUsage(AttributeTargets.All)] [ExcludeFromCodeCoverage] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Numerics { public static class BitOperations { public unsafe static readonly byte* TrailingZeroCountDeBruijn = UnsafeHelper.GetArrayPointer(new byte[32] { 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9 }); public unsafe static readonly byte* Log2DeBruijn = UnsafeHelper.GetArrayPointer(new byte[32] { 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31 }); [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static int Log2(uint value) { value |= 1; value |= value >> 1; value |= value >> 2; value |= value >> 4; value |= value >> 8; value |= value >> 16; return Log2DeBruijn[(int)(value * 130329821 >> 27)]; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int Log2(ulong value) { value |= 1; uint num = (uint)(value >> 32); if (num == 0) { return Log2((uint)value); } return 32 + Log2(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int TrailingZeroCount(int value) { return TrailingZeroCount((uint)value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static int TrailingZeroCount(uint value) { if (value == 0) { return 32; } return TrailingZeroCountDeBruijn[(int)((value & (0 - value)) * 125613361 >> 27)]; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int TrailingZeroCount(long value) { return TrailingZeroCount((ulong)value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int TrailingZeroCount(ulong value) { uint num = (uint)value; if (num == 0) { return 32 + TrailingZeroCount((uint)(value >> 32)); } return TrailingZeroCount(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint RotateLeft(uint value, int offset) { return (value << offset) | (value >> 32 - offset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong RotateLeft(ulong value, int offset) { return (value << offset) | (value >> 64 - offset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint RotateRight(uint value, int offset) { return (value >> offset) | (value << 32 - offset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong RotateRight(ulong value, int offset) { return (value >> offset) | (value << 64 - offset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static int LeadingZeroCount(uint value) { if (value == 0) { return 32; } value |= value >> 1; value |= value >> 2; value |= value >> 4; value |= value >> 8; value |= value >> 16; return 0x1F ^ Log2DeBruijn[(int)(value * 130329821 >> 27)]; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LeadingZeroCount(ulong value) { uint num = (uint)(value >> 32); if (num == 0) { return 32 + LeadingZeroCount((uint)value); } return LeadingZeroCount(num); } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = true)] internal sealed class MemberNotNullAttribute : Attribute { public MemberNotNullAttribute(string member) { } public MemberNotNullAttribute(params string[] members) { } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] [ExcludeFromCodeCoverage] [Embedded] internal sealed class ConstantExpectedAttribute : Attribute { public object? Min { get; set; } public object? Max { get; set; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] [ExcludeFromCodeCoverage] [Embedded] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)] [ExcludeFromCodeCoverage] [Embedded] internal sealed class ExperimentalAttribute : Attribute { public string DiagnosticId { get; } public string? UrlFormat { get; set; } public ExperimentalAttribute(string diagnosticId) { DiagnosticId = diagnosticId; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] [Embedded] internal sealed class UnscopedRefAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] [Embedded] internal sealed class StringSyntaxAttribute : Attribute { public const string CompositeFormat = "CompositeFormat"; public const string DateOnlyFormat = "DateOnlyFormat"; public const string DateTimeFormat = "DateTimeFormat"; public const string EnumFormat = "EnumFormat"; public const string GuidFormat = "GuidFormat"; public const string Json = "Json"; public const string NumericFormat = "NumericFormat"; public const string Regex = "Regex"; public const string TimeOnlyFormat = "TimeOnlyFormat"; public const string TimeSpanFormat = "TimeSpanFormat"; public const string Uri = "Uri"; public const string Xml = "Xml"; public string Syntax { get; } public object?[] Arguments { get; } public StringSyntaxAttribute(string syntax) { Syntax = syntax; Arguments = new object[0]; } public StringSyntaxAttribute(string syntax, params object?[] arguments) { Syntax = syntax; Arguments = arguments; } } [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] [Embedded] internal sealed class SetsRequiredMembersAttribute : Attribute { } } namespace System.Runtime.Versioning { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)] [ExcludeFromCodeCoverage] [Embedded] internal sealed class RequiresPreviewFeaturesAttribute : Attribute { public string? Message { get; } public string? Url { get; set; } public RequiresPreviewFeaturesAttribute() { } public RequiresPreviewFeaturesAttribute(string? message) { Message = message; } } } namespace System.Runtime.CompilerServices { [EditorBrowsable(EditorBrowsableState.Never)] internal static class IsExternalInit { } [EditorBrowsable(EditorBrowsableState.Never)] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)] [ExcludeFromCodeCoverage] [Embedded] internal sealed class ExtensionMarkerAttribute : Attribute { public string Name { get; } public ExtensionMarkerAttribute(string name) { Name = name; } } [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] [Embedded] internal sealed class CallerArgumentExpressionAttribute : Attribute { public string ParameterName { get; } public CallerArgumentExpressionAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, Inherited = false)] [ExcludeFromCodeCoverage] [Embedded] internal sealed class CollectionBuilderAttribute : Attribute { public Type BuilderType { get; } public string MethodName { get; } public CollectionBuilderAttribute(Type builderType, string methodName) { BuilderType = builderType; MethodName = methodName; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] [Embedded] internal sealed class InterpolatedStringHandlerAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] [Embedded] internal sealed class InterpolatedStringHandlerArgumentAttribute : Attribute { public string[] Arguments { get; } public InterpolatedStringHandlerArgumentAttribute(string argument) { Arguments = new string[1] { argument }; } public InterpolatedStringHandlerArgumentAttribute(params string[] arguments) { Arguments = arguments; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] [EditorBrowsable(EditorBrowsableState.Never)] [ExcludeFromCodeCoverage] [Embedded] internal sealed class RequiresLocationAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method, Inherited = false)] [ExcludeFromCodeCoverage] [Embedded] internal sealed class ModuleInitializerAttribute : Attribute { } [AttributeUsage(AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Interface, Inherited = false)] [ExcludeFromCodeCoverage] [Embedded] internal sealed class SkipLocalsInitAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = true, AllowMultiple = false)] [ExcludeFromCodeCoverage] [Embedded] internal sealed class ParamCollectionAttribute : Attribute { } [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] [Embedded] internal sealed class OverloadResolutionPriorityAttribute : Attribute { public int Priority { get; } public OverloadResolutionPriorityAttribute(int priority) { Priority = priority; } } [AttributeUsage(AttributeTargets.Class, Inherited = false)] [ExcludeFromCodeCoverage] [Embedded] internal sealed class CompilerLoweringPreserveAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] [Embedded] internal sealed class RequiredMemberAttribute : Attribute { } [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] [ExcludeFromCodeCoverage] [Embedded] internal sealed class CompilerFeatureRequiredAttribute : Attribute { public const string RefStructs = "RefStructs"; public const string RequiredMembers = "RequiredMembers"; public string FeatureName { get; } public bool IsOptional { get; set; } public CompilerFeatureRequiredAttribute(string featureName) { FeatureName = featureName; } } } namespace SharpCompress { internal sealed class LazyAsyncReadOnlyCollection<T> : IAsyncEnumerable<T> { private class LazyLoader(LazyAsyncReadOnlyCollection<T> lazyReadOnlyCollection, CancellationToken cancellationToken) : IAsyncEnumerator<T>, IAsyncDisposable { private bool _disposed; private int _index = -1; public T Current => <lazyReadOnlyCollection>P._backing[_index]; public ValueTask DisposeAsync() { if (!_disposed) { _disposed = true; } return default(ValueTask); } public async ValueTask<bool> MoveNextAsync() { <cancellationToken>P.ThrowIfCancellationRequested(); if (_index + 1 < <lazyReadOnlyCollection>P._backing.Count) { _index++; return true; } bool flag = !<lazyReadOnlyCollection>P._fullyLoaded; if (flag) { flag = await <lazyReadOnlyCollection>P._source.MoveNextAsync().ConfigureAwait(continueOnCapturedContext: false); } if (flag) { <lazyReadOnlyCollection>P._backing.Add(<lazyReadOnlyCollection>P._source.Current); _index++; return true; } <lazyReadOnlyCollection>P._fullyLoaded = true; return false; } public void Dispose() { if (!_disposed) { _disposed = true; } } } private readonly List<T> _backing = new List<T>(); private readonly IAsyncEnumerator<T> _source = source.GetAsyncEnumerator(); private bool _fullyLoaded; public bool IsReadOnly => true; public LazyAsyncReadOnlyCollection(IAsyncEnumerable<T> source) { } internal async ValueTask EnsureFullyLoaded() { if (!_fullyLoaded) { LazyLoader loader = new LazyLoader(this, CancellationToken.None); while (await loader.MoveNextAsync().ConfigureAwait(continueOnCapturedContext: false)) { } _fullyLoaded = true; } } internal IEnumerable<T> GetLoaded() { return _backing; } public void Add(T item) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } public bool Remove(T item) { throw new NotSupportedException(); } public IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = default(CancellationToken)) { return new LazyLoader(this, cancellationToken); } } internal sealed class LazyReadOnlyCollection<T> : ICollection<T>, IEnumerable<T>, IEnumerable { private class LazyLoader : IEnumerator<T>, IEnumerator, IDisposable { private readonly LazyReadOnlyCollection<T> _lazyReadOnlyCollection; private bool _disposed; private int _index = -1; public T Current => _lazyReadOnlyCollection._backing[_index]; object IEnumerator.Current => Current; internal LazyLoader(LazyReadOnlyCollection<T> lazyReadOnlyCollection) { _lazyReadOnlyCollection = lazyReadOnlyCollection; } public void Dispose() { if (!_disposed) { _disposed = true; } } public bool MoveNext() { if (_index + 1 < _lazyReadOnlyCollection._backing.Count) { _index++; return true; } if (!_lazyReadOnlyCollection._fullyLoaded && _lazyReadOnlyCollection._source.MoveNext()) { _lazyReadOnlyCollection._backing.Add(_lazyReadOnlyCollection._source.Current); _index++; return true; } _lazyReadOnlyCollection._fullyLoaded = true; return false; } public void Reset() { throw new NotSupportedException(); } } private readonly List<T> _backing = new List<T>(); private readonly IEnumerator<T> _source; private bool _fullyLoaded; public int Count { get { EnsureFullyLoaded(); return _backing.Count; } } public bool IsReadOnly => true; public LazyReadOnlyCollection(IEnumerable<T> source) { _source = source.GetEnumerator(); } internal void EnsureFullyLoaded() { if (!_fullyLoaded) { this.ForEach(delegate { }); _fullyLoaded = true; } } internal IEnumerable<T> GetLoaded() { return _backing; } public void Add(T item) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } public bool Contains(T item) { EnsureFullyLoaded(); return _backing.Contains(item); } public void CopyTo(T[] array, int arrayIndex) { EnsureFullyLoaded(); _backing.CopyTo(array, arrayIndex); } public bool Remove(T item) { throw new NotSupportedException(); } public IEnumerator<T> GetEnumerator() { return new LazyLoader(this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } internal static class NotNullExtensions { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static IEnumerable<T> Empty<T>(this IEnumerable<T>? source) { return source ?? Array.Empty<T>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static IEnumerable<T> Empty<T>(this T? source) { if (source == null) { return Array.Empty<T>(); } return source.AsEnumerable(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T NotNull<T>(this T? obj, string? message = null) where T : class { if (obj == null) { throw new ArgumentNullException(message ?? "Value is null"); } return obj; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T NotNull<T>(this T? obj, string? message = null) where T : struct { if (!obj.HasValue) { throw new ArgumentNullException(message ?? "Value is null"); } return obj.Value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static string NotNullOrEmpty(this string obj, string name) { obj.NotNull(name); if (obj.Length == 0) { throw new ArgumentException("String is empty.", name); } return obj; } } public static class AsyncEnumerableEx { public static async IAsyncEnumerable<T> Empty<T>() where T : notnull { await Task.Yield(); yield break; } } public static class EnumerableExtensions { public static async IAsyncEnumerable<T> ToAsyncEnumerable<T>(this IEnumerable<T> source) { foreach (T item in source) { yield return item; } } } public static class AsyncEnumerableExtensions { [SpecialName] public sealed class <G>$80073E1EF8BFBE3894A8F13DEEA08DF4<$T0> { [SpecialName] public static class <M>$24328A39342EAA4CDDFAEF4047A586E1 { } [ExtensionMarker("<M>$24328A39342EAA4CDDFAEF4047A586E1")] public IAsyncEnumerable<TResult> Select<TResult>(Func<$T0, TResult> selector) { throw new NotSupportedException(); } [ExtensionMarker("<M>$24328A39342EAA4CDDFAEF4047A586E1")] public ValueTask<int> CountAsync(CancellationToken cancellationToken = default(CancellationToken)) { throw new NotSupportedException(); } [ExtensionMarker("<M>$24328A39342EAA4CDDFAEF4047A586E1")] public IAsyncEnumerable<$T0> Take(int count) { throw new NotSupportedException(); } [ExtensionMarker("<M>$24328A39342EAA4CDDFAEF4047A586E1")] public ValueTask<List<$T0>> ToListAsync() { throw new NotSupportedException(); } [ExtensionMarker("<M>$24328A39342EAA4CDDFAEF4047A586E1")] public ValueTask<bool> AllAsync(Func<$T0, bool> predicate) { throw new NotSupportedException(); } [ExtensionMarker("<M>$24328A39342EAA4CDDFAEF4047A586E1")] public IAsyncEnumerable<$T0> Where(Func<$T0, bool> predicate) { throw new NotSupportedException(); } [ExtensionMarker("<M>$24328A39342EAA4CDDFAEF4047A586E1")] public ValueTask<$T0> SingleAsync(Func<$T0, bool>? predicate = null) { throw new NotSupportedException(); } [ExtensionMarker("<M>$24328A39342EAA4CDDFAEF4047A586E1")] public ValueTask<$T0> FirstAsync() { throw new NotSupportedException(); } [ExtensionMarker("<M>$24328A39342EAA4CDDFAEF4047A586E1")] public ValueTask<$T0?> FirstOrDefaultAsync(CancellationToken cancellationToken = default(CancellationToken)) { throw new NotSupportedException(); } } public static async IAsyncEnumerable<TResult> Select<T, TResult>(this IAsyncEnumerable<T> source, Func<T, TResult> selector) { await foreach (T item in source.ConfigureAwait(continueOnCapturedContext: false)) { yield return selector(item); } } public static async ValueTask<int> CountAsync<T>(this IAsyncEnumerable<T> source, CancellationToken cancellationToken = default(CancellationToken)) { int result; await using (IAsyncEnumerator<T> e = source.GetAsyncEnumerator(cancellationToken)) { int count = 0; while (await e.MoveNextAsync().ConfigureAwait(continueOnCapturedContext: false)) { count = checked(count + 1); } result = count; } return result; } public static async IAsyncEnumerable<T> Take<T>(this IAsyncEnumerable<T> source, int count) { await foreach (T item in source.ConfigureAwait(continueOnCapturedContext: false)) { yield return item; int num = count - 1; count = num; if (num == 0) { break; } } } public static async ValueTask<List<T>> ToListAsync<T>(this IAsyncEnumerable<T> source) { List<T> list = new List<T>(); await foreach (T item in source.ConfigureAwait(continueOnCapturedContext: false)) { list.Add(item); } return list; } public static async ValueTask<bool> AllAsync<T>(this IAsyncEnumerable<T> source, Func<T, bool> predicate) { await foreach (T item in source.ConfigureAwait(continueOnCapturedContext: false)) { if (!predicate(item)) { return false; } } return true; } public static async IAsyncEnumerable<T> Where<T>(this IAsyncEnumerable<T> source, Func<T, bool> predicate) { await foreach (T item in source.ConfigureAwait(continueOnCapturedContext: false)) { if (predicate(item)) { yield return item; } } } public static async ValueTask<T> SingleAsync<T>(this IAsyncEnumerable<T> source, Func<T, bool>? predicate = null) { IAsyncEnumerator<T> enumerator = ((predicate != null) ? source.Where(predicate).GetAsyncEnumerator() : source.GetAsyncEnumerator()); if (!(await enumerator.MoveNextAsync().ConfigureAwait(continueOnCapturedContext: false))) { throw new ArchiveOperationException("The source sequence is empty."); } T value = enumerator.Current; if (await enumerator.MoveNextAsync().ConfigureAwait(continueOnCapturedContext: false)) { throw new ArchiveOperationException("The source sequence contains more than one element."); } return value; } public static async ValueTask<T> FirstAsync<T>(this IAsyncEnumerable<T> source) { ConfiguredCancelableAsyncEnumerable<T>.Enumerator enumerator = source.ConfigureAwait(continueOnCapturedContext: false).GetAsyncEnumerator(); try { if (await enumerator.MoveNextAsync()) { return enumerator.Current; } } finally { IAsyncDisposable asyncDisposable = enumerator as IAsyncDisposable; if (asyncDisposable != null) { await asyncDisposable.DisposeAsync(); } } throw new ArchiveOperationException("The source sequence is empty."); } public static async ValueTask<T?> FirstOrDefaultAsync<T>(this IAsyncEnumerable<T> source, CancellationToken cancellationToken = default(CancellationToken)) { ConfiguredCancelableAsyncEnumerable<T>.Enumerator enumerator = source.WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false).GetAsyncEnumerator(); try { if (await enumerator.MoveNextAsync()) { return enumerator.Current; } } finally { IAsyncDisposable asyncDisposable = enumerator as IAsyncDisposable; if (asyncDisposable != null) { await asyncDisposable.DisposeAsync(); } } return default(T); } public static async IAsyncEnumerable<TResult> CastAsync<TResult>(this IAsyncEnumerable<object?> source) where TResult : class { await foreach (object item in source.ConfigureAwait(continueOnCapturedContext: false)) { yield return (item as TResult).NotNull(); } } public static async ValueTask<TAccumulate> AggregateAsync<TAccumulate, T>(this IAsyncEnumerable<T> source, TAccumulate seed, Func<TAccumulate, T, TAccumulate> func) { TAccumulate result = seed; await foreach (T item in source.ConfigureAwait(continueOnCapturedContext: false)) { result = func(result, item); } return result; } } public static class BinaryReaderExtensions { [SpecialName] public sealed class <G>$695D470279A3D0B0E149C7DC966C880D { [SpecialName] public static class <M>$EDB5B0AEA8AADEA6B0557AB86434CB65 { } [ExtensionMarker("<M>$EDB5B0AEA8AADEA6B0557AB86434CB65")] public ValueTask<byte> ReadByteAsync(CancellationToken cancellationToken = default(CancellationToken)) { throw new NotSupportedException(); } [ExtensionMarker("<M>$EDB5B0AEA8AADEA6B0557AB86434CB65")] public ValueTask<byte[]> ReadBytesAsync(int count, CancellationToken cancellationToken = default(CancellationToken)) { throw new NotSupportedException(); } } public static async ValueTask<byte> ReadByteAsync(this BinaryReader reader, CancellationToken cancellationToken = default(CancellationToken)) { byte[] buffer = new byte[1]; await reader.BaseStream.ReadExactAsync(buffer, 0, 1, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); return buffer[0]; } public static async ValueTask<byte[]> ReadBytesAsync(this BinaryReader reader, int count, CancellationToken cancellationToken = default(CancellationToken)) { if (count < 0) { throw new ArgumentOutOfRangeException("count", "Count must be non-negative."); } if (count == 0) { return Array.Empty<byte>(); } if (count <= 256) { byte[] bytes = new byte[count]; await reader.BaseStream.ReadExactAsync(bytes, 0, count, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); return bytes; } byte[] buffer = ArrayPool<byte>.Shared.Rent(count); try { await reader.BaseStream.ReadExactAsync(buffer, 0, count, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); byte[] array = new byte[count]; Array.Copy(buffer, 0, array, 0, count); return array; } finally { ArrayPool<byte>.Shared.Return(buffer); } } } public static class StreamExtensions { [SpecialName] public sealed class <G>$50F26341F4F164F9281EDEBBEB746904 { [SpecialName] public static class <M>$05FA4CA844D6F809592CA75BE4C36206 { } [ExtensionMarker("<M>$05FA4CA844D6F809592CA75BE4C36206")] public void Skip(long advanceAmount) { throw new NotSupportedException(); } [ExtensionMarker("<M>$05FA4CA844D6F809592CA75BE4C36206")] public void Skip() { throw new NotSupportedException(); } [ExtensionMarker("<M>$05FA4CA844D6F809592CA75BE4C36206")] public ValueTask SkipAsync(CancellationToken cancellationToken = default(CancellationToken)) { throw new NotSupportedException(); } [ExtensionMarker("<M>$05FA4CA844D6F809592CA75BE4C36206")] internal int Read(Span<byte> buffer) { throw new NotSupportedException(); } [ExtensionMarker("<M>$05FA4CA844D6F809592CA75BE4C36206")] internal void Write(ReadOnlySpan<byte> buffer) { throw new NotSupportedException(); } } public static void Skip(this Stream stream, long advanceAmount) { if (stream.CanSeek && !(stream is SharpCompressStream)) { stream.Position += advanceAmount; return; } using ReadOnlySubStream readOnlySubStream = new ReadOnlySubStream(stream, advanceAmount); readOnlySubStream.CopyTo(Stream.Null); } public static void Skip(this Stream stream) { stream.CopyTo(Stream.Null); } public static async ValueTask SkipAsync(this Stream stream, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); await stream.CopyToAsync(Stream.Null).ConfigureAwait(continueOnCapturedContext: false); } internal static int Read(this Stream stream, Span<byte> buffer) { byte[] array = ArrayPool<byte>.Shared.Rent(buffer.Length); try { int num = stream.Read(array, 0, buffer.Length); array.AsSpan(0, num).CopyTo(buffer); return num; } finally { ArrayPool<byte>.Shared.Return(array); } } internal static void Write(this Stream stream, ReadOnlySpan<byte> buffer) { byte[] array = ArrayPool<byte>.Shared.Rent(buffer.Length); buffer.CopyTo(array); try { stream.Write(array, 0, buffer.Length); } finally { ArrayPool<byte>.Shared.Return(array); } } } internal static class StringExtensions { internal static bool EndsWith(this string text, char value) { if (text.Length > 0) { return text[text.Length - 1] == value; } return false; } internal static bool Contains(this string text, char value) { return text.IndexOf(value) > -1; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue)] public class NotNullAttribute : Attribute { } internal static class StreamValidationExtensions { internal static void RequireReadable(this Stream stream) { stream.NotNull("stream"); if (!stream.CanRead) { throw new ArgumentException("Stream must be readable", "stream"); } } internal static void RequireSeekable(this Stream stream) { stream.NotNull("stream"); if (!stream.CanSeek) { throw new ArgumentException("Stream must be seekable", "stream"); } } internal static void RequireWritable(this Stream stream) { stream.NotNull("stream"); if (!stream.CanWrite) { throw new ArgumentException("Stream must be writable", "stream"); } } internal static IEnumerable<Stream> RequireSeekable(this IEnumerable<Stream> streams) { foreach (Stream stream in streams) { stream.RequireSeekable(); yield return stream; } } internal static IEnumerable<Stream> RequireReadable(this IEnumerable<Stream> streams) { foreach (Stream stream in streams) { stream.RequireReadable(); yield return stream; } } } internal static class ThrowHelper { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfNull([NotNull] object? argument, string? paramName = null) { if (argument == null) { throw new ArgumentNullException(paramName); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfNegative(int value, string? paramName = null) { if (value < 0) { throw new ArgumentOutOfRangeException(paramName); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfNegative(long value, string? paramName = null) { if (value < 0) { throw new ArgumentOutOfRangeException(paramName); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfNegativeOrZero(int value, string? paramName = null) { if (value <= 0) { throw new ArgumentOutOfRangeException(paramName); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfLessThan(int value, int other, string? paramName = null) { if (value < other) { throw new ArgumentOutOfRangeException(paramName); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfGreaterThan(int value, int other, string? paramName = null) { if (value > other) { throw new ArgumentOutOfRangeException(paramName); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfGreaterThan(long value, long other, string? paramName = null) { if (value > other) { throw new ArgumentOutOfRangeException(paramName); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfGreaterThan(uint value, uint other, string? paramName = null) { if (value > other) { throw new ArgumentOutOfRangeException(paramName); } } } internal static class Utility { [SpecialName] public sealed class <G>$50F26341F4F164F9281EDEBBEB746904 { [SpecialName] public static class <M>$B54B5D13E7CCFB46E3C6044C5D890D40 { } [ExtensionMarker("<M>$B54B5D13E7CCFB46E3C6044C5D890D40")] public ValueTask ReadExactAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken = default(CancellationToken)) { throw new NotSupportedException(); } [ExtensionMarker("<M>$B54B5D13E7CCFB46E3C6044C5D890D40")] public ValueTask<long> TransferToAsync(Stream destination, long maxLength, int? bufferSize = null, CancellationToken cancellationToken = default(CancellationToken)) { throw new NotSupportedException(); } [ExtensionMarker("<M>$B54B5D13E7CCFB46E3C6044C5D890D40")] public ValueTask<bool> ReadFullyAsync(byte[] buffer, CancellationToken cancellationToken = default(CancellationToken)) { throw new NotSupportedException(); } [ExtensionMarker("<M>$B54B5D13E7CCFB46E3C6044C5D890D40")] public ValueTask<bool> ReadFullyAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken = default(CancellationToken)) { throw new NotSupportedException(); } [ExtensionMarker("<M>$B54B5D13E7CCFB46E3C6044C5D890D40")] public long TransferTo(Stream destination, long maxLength, int? bufferSize) { throw new NotSupportedException(); } [ExtensionMarker("<M>$B54B5D13E7CCFB46E3C6044C5D890D40")] public ValueTask SkipAsync(long advanceAmount, CancellationToken cancellationToken = default(CancellationToken)) { throw new NotSupportedException(); } [ExtensionMarker("<M>$B54B5D13E7CCFB46E3C6044C5D890D40")] public bool ReadFully(byte[] buffer) { throw new NotSupportedException(); } [ExtensionMarker("<M>$B54B5D13E7CCFB46E3C6044C5D890D40")] public bool ReadFully(Span<byte> buffer) { throw new NotSupportedException(); } [ExtensionMarker("<M>$B54B5D13E7CCFB46E3C6044C5D890D40")] public void ReadExact(byte[] buffer, int offset, int length) { throw new NotSupportedException(); } } private static readonly HashSet<char> invalidChars = new HashSet<char>(Path.GetInvalidFileNameChars()); internal static StringComparison PathComparison { get { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return StringComparison.Ordinal; } return StringComparison.OrdinalIgnoreCase; } } public static async ValueTask ReadExactAsync(this Stream source, byte[] buffer, int offset, int length, CancellationToken cancellationToken = default(CancellationToken)) { if (source == null) { throw new ArgumentNullException(); } ThrowHelper.ThrowIfNull(buffer); if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset"); } if (length < 0 || length > buffer.Length - offset) { throw new ArgumentOutOfRangeException("length"); } while (length > 0) { int num = await source.ReadAsync(buffer.AsMemory(offset, length), cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (num <= 0) { throw new IncompleteArchiveException("Unexpected end of stream."); } offset += num; length -= num; } } public static async ValueTask<long> TransferToAsync(this Stream source, Stream destination, long maxLength, int? bufferSize = null, CancellationToken cancellationToken = default(CancellationToken)) { using ReadOnlySubStream limitedStream = new ReadOnlySubStream(source, maxLength); await limitedStream.CopyToAsync(destination, bufferSize ?? SharpCompress.Common.Constants.BufferSize, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); return limitedStream.Position; } public static async ValueTask<bool> ReadFullyAsync(this Stream source, byte[] buffer, CancellationToken cancellationToken = default(CancellationToken)) { int total = 0; int num; while ((num = await source.ReadAsync(buffer.AsMemory(total, buffer.Length - total), cancellationToken).ConfigureAwait(continueOnCapturedContext: false)) > 0) { total += num; if (total >= buffer.Length) { return true; } } return total >= buffer.Length; } public static async ValueTask<bool> ReadFullyAsync(this Stream source, byte[] buffer, int offset, int count, CancellationToken cancellationToken = default(CancellationToken)) { int total = 0; int num; while ((num = await source.ReadAsync(buffer.AsMemory(offset + total, count - total), cancellationToken).ConfigureAwait(continueOnCapturedContext: false)) > 0) { total += num; if (total >= count) { return true; } } return total >= count; } public static Stream OpenAsyncWriteStream(string path, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 4096, FileOptions.Asynchronous); } public static Stream OpenAsyncWriteStream(this FileInfo fileInfo, CancellationToken cancellationToken) { fileInfo.NotNull("fileInfo"); return OpenAsyncWriteStream(fileInfo.FullName, cancellationToken); } public static Stream OpenAsyncReadStream(string path, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.Asynchronous); } public static Stream OpenAsyncReadStream(this FileInfo fileInfo, CancellationToken cancellationToken) { fileInfo.NotNull("fileInfo"); return OpenAsyncReadStream(fileInfo.FullName, cancellationToken); } public static bool UseSyncOverAsyncDispose() { return true; } public static ReadOnlyCollection<T> ToReadOnly<T>(this IList<T> items) { return new ReadOnlyCollection<T>(items); } public static int URShift(int number, int bits) { return number >>> bits; } public static long URShift(long number, int bits) { return number >>> bits; } public static void SetSize(this List<byte> list, int count) { if (count > list.Count) { list.Capacity = count; for (int i = list.Count; i < count; i++) { list.Add(0); } } else { list.RemoveRange(count, list.Count - count); } } public static void ForEach<T>(this IEnumerable<T> items, Action<T> action) { foreach (T item in items) { action(item); } } public static IEnumerable<T> AsEnumerable<T>(this T item) { yield return item; } public static DateTime DosDateToDateTime(ushort iDate, ushort iTime) { int year = iDate / 512 + 1980; int num = iDate % 512 / 32; int num2 = iDate % 512 % 32; int hour = iTime / 2048; int minute = iTime % 2048 / 32; int second = iTime % 2048 % 32 * 2; if (iDate == ushort.MaxValue || num == 0 || num2 == 0) { year = 1980; num = 1; num2 = 1; } if (iTime == ushort.MaxValue) { hour = (minute = (second = 0)); } DateTime result; try { return new DateTime(year, num, num2, hour, minute, second, DateTimeKind.Local); } catch { result = default(DateTime); } return result; } public static uint DateTimeToDosTime(this DateTime? dateTime) { if (!dateTime.HasValue) { return 0u; } DateTime dateTime2 = dateTime.Value.ToLocalTime(); return (uint)((dateTime2.Second / 2) | (dateTime2.Minute << 5) | (dateTime2.Hour << 11) | (dateTime2.Day << 16) | (dateTime2.Month << 21) | (dateTime2.Year - 1980 << 25)); } public static DateTime DosDateToDateTime(uint iTime) { return DosDateToDateTime((ushort)(iTime / 65536), (ushort)(iTime % 65536)); } public static DateTime UnixTimeToDateTime(long unixtime) { return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(unixtime); } public static long TransferTo(this Stream source, Stream destination, long maxLength, int? bufferSize) { using ReadOnlySubStream readOnlySubStream = new ReadOnlySubStream(source, maxLength); readOnlySubStream.CopyTo(destination, bufferSize ?? SharpCompress.Common.Constants.BufferSize); return readOnlySubStream.Position; } public static async ValueTask SkipAsync(this Stream source, long advanceAmount, CancellationToken cancellationToken = default(CancellationToken)) { if (source.CanSeek && !(source is SharpCompressStream)) { source.Position += advanceAmount; return; } byte[] array = ArrayPool<byte>.Shared.Rent(SharpCompress.Common.Constants.BufferSize); try { while (advanceAmount > 0) { int count = (int)Math.Min(array.Length, advanceAmount); int num = await source.ReadAsync(array, 0, count, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (num > 0) { advanceAmount -= num; continue; } break; } } finally { ArrayPool<byte>.Shared.Return(array); } } public static bool ReadFully(this Stream source, byte[] buffer) { int num = 0; int num2; while ((num2 = source.Read(buffer, num, buffer.Length - num)) > 0) { num += num2; if (num >= buffer.Length) { return true; } } return num >= buffer.Length; } public static bool ReadFully(this Stream source, Span<byte> buffer) { int num = 0; int num2; while ((num2 = source.Read(buffer.Slice(num, buffer.Length - num))) > 0) { num += num2; if (num >= buffer.Length) { return true; } } return num >= buffer.Length; } public static void ReadExact(this Stream source, byte[] buffer, int offset, int length) { if (source == null) { throw new ArgumentNullException(); } ThrowHelper.ThrowIfNull(buffer); if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset"); } if (length < 0 || length > buffer.Length - offset) { throw new ArgumentOutOfRangeException("length"); } while (length > 0) { int num = source.Read(buffer, offset, length); if (num <= 0) { throw new IncompleteArchiveException("Unexpected end of stream."); } offset += num; length -= num; } } public static string TrimNulls(this string source) { return source.Replace('\0', ' ').Trim(); } public static uint SwapUINT32(uint number) { return (number >> 24) | ((number << 8) & 0xFF0000) | ((number >> 8) & 0xFF00) | (number << 24); } public static void SetLittleUInt32(ref byte[] buffer, uint number, long offset) { buffer[offset] = (byte)number; buffer[offset + 1] = (byte)(number >> 8); buffer[offset + 2] = (byte)(number >> 16); buffer[offset + 3] = (byte)(number >> 24); } public static void SetBigUInt32(ref byte[] buffer, uint number, long offset) { buffer[offset] = (byte)(number >> 24); buffer[offset + 1] = (byte)(number >> 16); buffer[offset + 2] = (byte)(number >> 8); buffer[offset + 3] = (byte)number; } public static string ReplaceInvalidFileNameChars(string fileName) { StringBuilder stringBuilder = new StringBuilder(fileName.Length); foreach (char c in fileName) { char value = (invalidChars.Contains(c) ? '_' : c); stringBuilder.Append(value); } return stringBuilder.ToString(); } } } namespace SharpCompress.Writers { public abstract class AbstractWriter(ArchiveType type, IWriterOptions writerOptions) : IWriter, IDisposable, IAsyncWriter, IAsyncDisposable { protected bool _isDisposed; protected Stream? OutputStream { get; private set; } public ArchiveType Type { get; } = type; protected IWriterOptions WriterOptions { get; } = writerOptions; public abstract ValueTask WriteAsync(string filename, Stream source, DateTime? modificationTime, CancellationToken cancellationToken = default(CancellationToken)); public abstract ValueTask WriteDirectoryAsync(string directoryName, DateTime? modificationTime, CancellationToken cancellationToken = default(CancellationToken)); public virtual ValueTask DisposeAsync() { if (!_isDisposed) { GC.SuppressFinalize(this); Dispose(isDisposing: true); _isDisposed = true; } return default(ValueTask); } protected void InitializeStream(Stream stream) { OutputStream = stream; } protected Stream WrapWithProgress(Stream source, string entryPath) { if (WriterOptions.Progress == null) { return source; } long? totalBytes = (source.CanSeek ? new long?(source.Length) : ((long?)null)); return new ProgressReportingStream(source, WriterOptions.Progress, entryPath, totalBytes, leaveOpen: true); } public abstract void Write(string filename, Stream source, DateTime? modificationTime); public abstract void WriteDirectory(string directoryName, DateTime? modificationTime); protected virtual void Dispose(bool isDisposing) { if (isDisposing) { OutputStream?.Dispose(); } } public void Dispose() { if (!_isDisposed) { GC.SuppressFinalize(this); Dispose(isDisposing: true); _isDisposed = true; } } ~AbstractWriter() { if (!_isDisposed) { Dispose(isDisposing: false); _isDisposed = true; } } } internal static class CompressionLevelValidation { public static void Validate(SharpCompress.Common.CompressionType compressionType, int compressionLevel) { switch (compressionType) { case SharpCompress.Common.CompressionType.GZip: case SharpCompress.Common.CompressionType.Deflate: case SharpCompress.Common.CompressionType.Deflate64: EnsureRange(compressionLevel, 0, 9, compressionType); return; case SharpCompress.Common.CompressionType.ZStandard: EnsureRange(compressionLevel, 1, 22, compressionType); return; } if (compressionLevel != 0) { throw new ArgumentOutOfRangeException("compressionLevel", compressionLevel, $"Compression type {compressionType} does not support configurable compression levels. Use 0."); } } private static void EnsureRange(int compressionLevel, int minInclusive, int maxInclusive, SharpCompress.Common.CompressionType compressionType) { if (compressionLevel < minInclusive || compressionLevel > maxInclusive) { throw new ArgumentOutOfRangeException("compressionLevel", compressionLevel, $"Compression level for {compressionType} must be between {minInclusive} and {maxInclusive}."); } } } public interface IAsyncWriter : IAsyncDisposable { ArchiveType Type { get; } ValueTask WriteAsync(string filename, Stream source, DateTime? modificationTime, CancellationToken cancellationToken = default(CancellationToken)); ValueTask WriteDirectoryAsync(string directoryName, DateTime? modificationTime, CancellationToken cancellationToken = default(CancellationToken)); } public interface IWriter : IDisposable { ArchiveType Type { get; } void Write(string filename, Stream source, DateTime? modificationTime); void WriteDirectory(string directoryName, DateTime? modificationTime); } public static class IWriterExtensions { [SpecialName] public sealed class <G>$5EFE49A34F420D66F1BF4D8946D37190 { [SpecialName] public static class <M>$42FD762F9167B06784109DA947EB9DF0 { } [ExtensionMarker("<M>$42FD762F9167B06784109DA947EB9DF0")] public void Write(string entryPath, Stream source) { throw new NotSupportedException(); } [ExtensionMarker("<M>$42FD762F9167B06784109DA947EB9DF0")] public void Write(string entryPath, FileInfo source) { throw new NotSupportedException(); } [ExtensionMarker("<M>$42FD762F9167B06784109DA947EB9DF0")] public void Write(string entryPath, string source) { throw new NotSupportedException(); } [ExtensionMarker("<M>$42FD762F9167B06784109DA947EB9DF0")] public void WriteAll(string directory, string searchPattern = "*", SearchOption option = SearchOption.TopDirectoryOnly) { throw new NotSupportedException(); } [ExtensionMarker("<M>$42FD762F9167B06784109DA947EB9DF0")] public void WriteAll(string directory, string searchPattern = "*", Func<string, bool>? fileSearchFunc = null, SearchOption option = SearchOption.TopDirectoryOnly) { throw new NotSupportedException(); } [ExtensionMarker("<M>$42FD762F9167B06784109DA947EB9DF0")] public void WriteDirectory(string directoryName) { throw new NotSupportedException(); } } [SpecialName] public sealed class <G>$A50FB326E01A2D268CE4DAD0E49CA0BE { [SpecialName] public static class <M>$98BBF6FE16A51A6EF1A3EDDA36655CAE { } [ExtensionMarker("<M>$98BBF6FE16A51A6EF1A3EDDA36655CAE")] public ValueTask WriteAsync(string entryPath, Stream source, CancellationToken cancellationToken = default(CancellationToken)) { throw new NotSupportedException(); } [ExtensionMarker("<M>$98BBF6FE16A51A6EF1A3EDDA36655CAE")] public ValueTask WriteAsync(string entryPath, FileInfo source, CancellationToken cancellationToken = default(CancellationToken)) { throw new NotSupportedException(); } [ExtensionMarker("<M>$98BBF6FE16A51A6EF1A3EDDA36655CAE")] public ValueTask WriteAsync(string entryPath, string source, CancellationToken cancellationToken = default(CancellationToken)) { throw new NotSupportedException(); } [ExtensionMarker("<M>$98BBF6FE16A51A6EF1A3EDDA36655CAE")] public ValueTask WriteAllAsync(string directory, string searchPattern = "*", SearchOption option = SearchOption.TopDirectoryOnly, CancellationToken cancellationToken = default(CancellationToken)) { throw new NotSupportedException(); } [ExtensionMarker("<M>$98BBF6FE16A51A6EF1A3EDDA36655CAE")] public ValueTask WriteAllAsync(string directory, string searchPattern = "*", Func<string, bool>? fileSearchFunc = null, SearchOption option = SearchOption.TopDirectoryOnly, CancellationToken cancellationToken = default(CancellationToken)) { throw new NotSupportedException(); } [ExtensionMarker("<M>$98BBF6FE16A51A6EF1A3EDDA36655CAE")] public ValueTask WriteDirectoryAsync(string directoryName, CancellationToken cancellationToken = default(CancellationToken)) { throw new NotSupportedException(); } } public static void Write(this IWriter writer, string entryPath, Stream source) { writer.Write(entryPath, source, null); } public static void Write(this IWriter writer, string entryPath, FileInfo source) { if (!source.Exists) { throw new ArgumentException("Source does not exist: " + source.FullName); } using FileStream source2 = source.OpenRead(); writer.Write(entryPath, source2, source.LastWriteTime); } public static void Write(this IWriter writer, string entryPath, string source) { writer.Write(entryPath, new FileInfo(source)); } public static void WriteAll(this IWriter writer, string directory, string searchPattern = "*", SearchOption option = SearchOption.TopDirectoryOnly) { writer.WriteAll(directory, searchPattern, null, option); } public static void WriteAll(this IWriter writer, string directory, string searchPattern = "*", Func<string, bool>? fileSearchFunc = null, SearchOption option = SearchOption.TopDirectoryOnly) { if (!Directory.Exists(directory)) { throw new ArgumentException("Directory does not exist: " + directory); } if (fileSearchFunc == null) { fileSearchFunc = (string n) => true; } foreach (string item in Directory.EnumerateFiles(directory, searchPattern, option).Where(fileSearchFunc)) { writer.Write(item.Substring(directory.Length), item); } } public static void WriteDirectory(this IWriter writer, string directoryName) { writer.WriteDirectory(directoryName, null); } public static ValueTask WriteAsync(this IAsyncWriter writer, string entryPath, Stream source, CancellationToken cancellationToken = default(CancellationToken)) { return writer.WriteAsync(entryPath, source, null, cancellationToken); } public static async ValueTask WriteAsync(this IAsyncWriter writer, string entryPath, FileInfo source, CancellationToken cancellationToken = default(CancellationToken)) { if (!source.Exists) { throw new ArgumentException("Source does not exist: " + source.FullName); } using FileStream stream = source.OpenRead(); await writer.WriteAsync(entryPath, stream, source.LastWriteTime, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static ValueTask WriteAsync(this IAsyncWriter writer, string entryPath, string source, CancellationToken cancellationToken = default(CancellationToken)) { return writer.WriteAsync(entryPath, new FileInfo(source), cancellationToken); } public static ValueTask WriteAllAsync(this IAsyncWriter writer, string directory, string searchPattern = "*", SearchOption option = SearchOption.TopDirectoryOnly, CancellationToken cancellationToken = default(CancellationToken)) { return writer.WriteAllAsync(directory, searchPattern, null, option, cancellationToken); } public static async ValueTask WriteAllAsync(this IAsyncWriter writer, string directory, string searchPattern = "*", Func<string, bool>? fileSearchFunc = null, SearchOption option = SearchOption.TopDirectoryOnly, CancellationToken cancellationToken = default(CancellationToken)) { if (!Directory.Exists(directory)) { throw new ArgumentException("Directory does not exist: " + directory); } if (fileSearchFunc == null) { fileSearchFunc = (string n) => true; } foreach (string item in Directory.EnumerateFiles(directory, searchPattern, option).Where(fileSearchFunc)) { await writer.WriteAsync(item.Substring(directory.Length), item, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } } public static ValueTask WriteDirectoryAsync(this IAsyncWriter writer, string directoryName, CancellationToken cancellationToken = default(CancellationToken)) { return writer.WriteDirectoryAsync(directoryName, null, cancellationToken); } } public interface IWriterFactory : IFactory { IWriter OpenWriter(Stream stream, IWriterOptions writerOptions); ValueTask<IAsyncWriter> OpenAsyncWriter(Stream stream, IWriterOptions writerOptions, CancellationToken cancellationToken = default(CancellationToken)); } public static class WriterFactory { public static IWriter OpenWriter(string filePath, ArchiveType archiveType, IWriterOptions writerOptions) { filePath.NotNullOrEmpty("filePath"); return OpenWriter(new FileInfo(filePath), archiveType, writerOptions); } public static IWriter OpenWriter(FileInfo fileInfo, ArchiveType archiveType, IWriterOptions writerOptions) { fileInfo.NotNull("fileInfo"); return OpenWriter(fileInfo.OpenWrite(), archiveType, writerOptions.WithLeaveStreamOpen(leaveStreamOpen: false)); } public static async ValueTask<IAsyncWriter> OpenAsyncWriter(string filePath, ArchiveType archiveType, IWriterOptions writerOptions, CancellationToken cancellationToken = default(CancellationToken)) { filePath.NotNullOrEmpty("filePath"); return await OpenAsyncWriter(new FileInfo(filePath), archiveType, writerOptions, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static async ValueTask<IAsyncWriter> OpenAsyncWriter(FileInfo fileInfo, ArchiveType archiveType, IWriterOptions writerOptions, CancellationToken cancellationToken = default(CancellationToken)) { fileInfo.NotNull("fileInfo"); return await OpenAsyncWriter(fileInfo.OpenAsyncWriteStream(cancellationToken), archiveType, writerOptions.WithLeaveStreamOpen(leaveStreamOpen: false), cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static IWriter OpenWriter(Stream stream, ArchiveType archiveType, IWriterOptions writerOptions) { stream.RequireWritable(); IWriterFactory writerFactory = Factory.Factories.OfType<IWriterFactory>().FirstOrDefault((IWriterFactory item) => item.KnownArchiveType == archiveType); if (writerFactory != null) { return writerFactory.OpenWriter(stream, writerOptions); } throw new NotSupportedException("Archive Type does not have a Writer: " + archiveType); } public static async ValueTask<IAsyncWriter> OpenAsyncWriter(Stream stream, ArchiveType archiveType, IWriterOptions writerOptions, CancellationToken cancellationToken = default(CancellationToken)) { stream.RequireWritable(); IWriterFactory writerFactory = Factory.Factories.OfType<IWriterFactory>().FirstOrDefault((IWriterFactory item) => item.KnownArchiveType == archiveType); if (writerFactory != null) { return await writerFactory.OpenAsyncWriter(stream, writerOptions, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } throw new NotSupportedException("Archive Type does not have a Writer: " + archiveType); } } public sealed record WriterOptions : IWriterOptions, IStreamOptions, IEncodingOptions, IProgressOptions { public SharpCompress.Common.CompressionType CompressionType { get; set; } public int CompressionLevel { [CompilerGenerated] get { return <CompressionLevel>k__BackingField; } set { CompressionLevelValidation.Validate(CompressionType, value); <CompressionLevel>k__BackingField = value; } } public bool LeaveStreamOpen { get; set; } = true; public IArchiveEncoding ArchiveEncoding { get; set; } = new ArchiveEncoding(); public IProgress<ProgressReport>? Progress { get; set; } public int BufferSize { get; set; } = SharpCompress.Common.Constants.BufferSize; public CompressionProviderRegistry Providers { get; set; } = CompressionProviderRegistry.Default; [CompilerGenerated] private int <CompressionLevel>k__BackingField; public WriterOptions(SharpCompress.Common.CompressionType compressionType) { CompressionType = compressionType; CompressionLevel = compressionType switch { SharpCompress.Common.CompressionType.ZStandard => 3, SharpCompress.Common.CompressionType.Deflate => 6, SharpCompress.Common.CompressionType.Deflate64 => 6, SharpCompress.Common.CompressionType.GZip => 6, _ => 0, }; } public WriterOptions(SharpCompress.Common.CompressionType compressionType, int compressionLevel) { CompressionType = compressionType; CompressionLevel = compressionLevel; } public static implicit operator WriterOptions(SharpCompress.Common.CompressionType compressionType) { return new WriterOptions(compressionType); } public static WriterOptions ForZip(SharpCompress.Common.CompressionType compressionType = SharpCompress.Common.CompressionType.Deflate) { return new WriterOptions(compressionType); } public static WriterOptions ForTar(SharpCompress.Common.CompressionType compressionType = SharpCompress.Common.CompressionType.None) { return new WriterOptions(compressionType); } public static WriterOptions ForGZip() { return new WriterOptions(SharpCompress.Common.CompressionType.GZip); } [CompilerGenerated] private bool PrintMembers(StringBuilder builder) { RuntimeHelpers.EnsureSufficientExecutionStack(); builder.Append("CompressionType = "); builder.Append(CompressionType.ToString()); builder.Append(", CompressionLevel = "); builder.Append(CompressionLevel.ToString()); builder.Append(", LeaveStreamOpen = "); builder.Append(LeaveStreamOpen.ToString()); builder.Append(", ArchiveEncoding = "); builder.Append(ArchiveEncoding); builder.Append(", Progress = "); builder.Append(Progress); builder.Append(", BufferSize = "); builder.Append(BufferSize.ToString()); builder.Append(", Providers = "); builder.Append(Providers); return true; } [CompilerGenerated] public override int GetHashCode() { return ((((((EqualityComparer<Type>.Default.GetHashCode(EqualityContract) * -1521134295 + EqualityComparer<SharpCompress.Common.CompressionType>.Default.GetHashCode(CompressionType)) * -1521134295 + EqualityComparer<int>.Default.GetHashCode(<CompressionLevel>k__BackingField)) * -1521134295 + EqualityComparer<bool>.Default.GetHashCode(LeaveStreamOpen)) * -1521134295 + EqualityComparer<IArchiveEncoding>.Default.GetHashCode(ArchiveEncoding)) * -1521134295 + EqualityComparer<IProgress<ProgressReport>>.Default.GetHashCode(Progress)) * -1521134295 + EqualityComparer<int>.Default.GetHashCode(BufferSize)) * -1521134295 + EqualityComparer<CompressionProviderRegistry>.Default.GetHashCode(Providers); } [CompilerGenerated] public bool Equals(WriterOptions? other) { if ((object)this != other) { if ((object)other != null && EqualityContract == other.EqualityContract && EqualityComparer<SharpCompress.Common.CompressionType>.Default.Equals(CompressionType, other.CompressionType) && EqualityComparer<int>.Default.Equals(<CompressionLevel>k__BackingField, other.<CompressionLevel>k__BackingField) && EqualityComparer<bool>.Default.Equals(LeaveStreamOpen, other.LeaveStreamOpen) && EqualityComparer<IArchiveEncoding>.Default.Equals(ArchiveEncoding, other.ArchiveEncoding) && EqualityComparer<IProgress<ProgressReport>>.Default.Equals(Progress, other.Progress) && EqualityComparer<int>.Default.Equals(BufferSize, other.BufferSize)) { return EqualityComparer<CompressionProviderRegistry>.Default.Equals(Providers, other.Providers); } return false; } return true; } [CompilerGenerated] private WriterOptions(WriterOptions original) { CompressionType = original.CompressionType; <CompressionLevel>k__BackingField = original.<CompressionLevel>k__BackingField; LeaveStreamOpen = original.LeaveStreamOpen; ArchiveEncoding = original.ArchiveEncoding; Progress = original.Progress; BufferSize = original.BufferSize; Providers = original.Providers; } } public static class WriterOptionsExtensions { public static WriterOptions WithLeaveStreamOpen(this WriterOptions options, bool leaveStreamOpen) { return options with { LeaveStreamOpen = leaveStreamOpen }; } public static IWriterOptions WithLeaveStreamOpen(this IWriterOptions options, bool leaveStreamOpen) { if (!(options is WriterOptions writerOptions)) { if (!(options is ZipWriterOptions zipWriterOptions)) { if (!(options is TarWriterOptions tarWriterOptions)) { if (!(options is GZipWriterOptions gZipWriterOptions)) { if (options is SevenZipWriterOptions sevenZipWriterOptions) { return sevenZipWriterOptions with { LeaveStreamOpen = leaveStreamOpen }; } throw new NotSupportedException("Cannot set LeaveStreamOpen on options of type " + options.GetType().Name + ". Options must be a record type implementing IWriterOptions."); } return gZipWriterOptions with { LeaveStreamOpen = leaveStreamOpen }; } return tarWriterOptions with { LeaveStreamOpen = leaveStreamOpen }; } return zipWriterOptions with { LeaveStreamOpen = leaveStreamOpen }; } return writerOptions with { LeaveStreamOpen = leaveStreamOpen }; } public static WriterOptions WithBufferSize(this WriterOptions options, int bufferSize) { return options with { BufferSize = bufferSize }; } public static WriterOptions WithCompressionLevel(this WriterOptions options, int compressionLevel) { return options with { CompressionLevel = compressionLevel }; } public static WriterOptions WithArchiveEncoding(this WriterOptions options, IArchiveEncoding archiveEncoding) { return options with { ArchiveEncoding = archiveEncoding }; } public static WriterOptions WithProgress(this WriterOptions options, IProgress<ProgressReport> progress) { return options with { Progress = progress }; } public static WriterOptions WithProviders(this WriterOptions options, CompressionProviderRegistry providers) { if (providers == null) { throw new ArgumentNullException("providers"); } return options with { Providers = providers }; } } } namespace SharpCompress.Writers.Zip { internal class ZipCentralDirectoryEntry { private readonly ZipCompressionMethod compression; private readonly string fileName; private readonly IArchiveEncoding archiveEncoding; internal DateTime? ModificationTime { get; set; } internal string? Comment { get; set; } internal uint Crc { get; set; } internal ulong Compressed { get; set; } internal ulong Decompressed { get; set; } internal ushort Zip64HeaderOffset { get; set; } internal ulong HeaderOffset { get; } internal bool UsesDataDescriptor { get; set; } public ZipCentralDirectoryEntry(ZipCompressionMethod compression, string fileName, ulong headerOffset, IArchiveEncoding archiveEncoding) { this.compression = compression; this.fileName = fileName; HeaderOffset = headerOffset; this.archiveEncoding = archiveEncoding; } internal uint Write(Stream outputStream) { byte[] array = archiveEncoding.Encode(fileName); byte[] array2 = archiveEncoding.Encode(Comment ?? string.Empty); bool flag = Compressed >= uint.MaxValue || Decompressed >= uint.MaxValue; bool flag2 = flag || HeaderOffset >= uint.MaxValue; ZipCompressionMethod zipCompressionMethod = compression; uint value = (uint)(flag2 ? uint.MaxValue : Compressed); uint value2 = (uint)(flag2 ? uint.MaxValue : Decompressed); uint value3 = (uint)(flag2 ? uint.MaxValue : HeaderOffset); int num = (flag2 ? 32 : 0); byte b = (byte)((compression != ZipCompressionMethod.LZMA && compression != ZipCompressionMethod.PPMd && compression != ZipCompressionMethod.BZip2 && compression != ZipCompressionMethod.ZStandard) ? ((!flag2 && Zip64HeaderOffset == 0) ? 20 : 45) : 63); SharpCompress.Common.Zip.Headers.HeaderFlags headerFlags = (object.Equals(archiveEncoding.GetEncoding(), Encoding.UTF8) ? SharpCompress.Common.Zip.Headers.HeaderFlags.Efs : SharpCompress.Common.Zip.Headers.HeaderFlags.None); if (UsesDataDescriptor) { if (!flag) { headerFlags |= SharpCompress.Common.Zip.Headers.HeaderFlags.UsePostDataDescriptor; } if (zipCompressionMethod == ZipCompressionMethod.LZMA) { headerFlags |= SharpCompress.Common.Zip.Headers.HeaderFlags.Bit1; } } if (Decompressed == 0L && Compressed == 0L) { zipCompressionMethod = ZipCompressionMethod.None; } Span<byte> span = stackalloc byte[8] { 80, 75, 1, 2, b, 0, b, 0 }; outputStream.Write(span); BinaryPrimitives.WriteUInt16LittleEndian(span, (ushort)headerFlags); outputStream.Write(span.Slice(0, 2)); BinaryPrimitives.WriteUInt16LittleEndian(span, (ushort)zipCompressionMethod); outputStream.Write(span.Slice(0, 2)); BinaryPrimitives.WriteUInt32LittleEndian(span, ModificationTime.DateTimeToDosTime()); outputStream.Write(span.Slice(0, 4)); BinaryPrimitives.WriteUInt32LittleEndian(span, Crc); outputStream.Write(span.Slice(0, 4)); BinaryPrimitives.WriteUInt32LittleEndian(span, value); outputStream.Write(span.Slice(0, 4)); BinaryPrimitives.WriteUInt32LittleEndian(span, value2); outputStream.Write(span.Slice(0, 4)); BinaryPrimitives.WriteUInt16LittleEndian(span, (ushort)array.Length); outputStream.Write(span.Slice(0, 2)); BinaryPrimitives.WriteUInt16LittleEndian(span, (ushort)num); outputStream.Write(span.Slice(0, 2)); BinaryPrimitives.WriteUInt16LittleEndian(span, (ushort)array2.Length); outputStream.Write(span.Slice(0, 2)); BinaryPrimitives.WriteUInt16LittleEndian(span, 0); outputStream.Write(span.Slice(0, 2)); BinaryPrimitives.WriteUInt16LittleEndian(span, 0); outputStream.Write(span.Slice(0, 2)); BinaryPrimitives.WriteUInt16LittleEndian(span, 0); outputStream.Write(span.Slice(0, 2)); BinaryPrimitives.WriteUInt16LittleEndian(span, 33024); outputStream.Write(span.Slice(0, 2)); BinaryPrimitives.WriteUInt32LittleEndian(span, value3); outputStream.Write(span.Slice(0, 4)); outputStream.Write(array, 0, array.Length); if (flag2) { BinaryPrimitives.WriteUInt16LittleEndian(span, 1); outputStream.Write(span.Slice(0, 2)); BinaryPrimitives.WriteUInt16LittleEndian(span, (ushort)(num - 4)); outputStream.Write(span.Slice(0, 2)); BinaryPrimitives.WriteUInt64LittleEndian(span, Decompressed); outputStream.Write(span); BinaryPrimitives.WriteUInt64LittleEndian(span, Compressed); outputStream.Write(span); BinaryPrimitives.WriteUInt64LittleEndian(span, HeaderOffset); outputStream.Write(span); BinaryPrimitives.WriteUInt32LittleEndian(span, 0u); outputStream.Write(span.Slice(0, 4)); } outputStream.Write(array2, 0, array2.Length); return (uint)(46 + array.Length + num + array2.Length); } } public class ZipWriter : AbstractWriter { internal class ZipWritingStream : Stream { private readonly CRC32 crc = new CRC32(); private readonly ZipCentralDirectoryEntry entry; private readonly Stream originalStream; private Stream writeStream; private readonly ZipWriter writer; private readonly ZipCompressionMethod zipCompressionMethod; private readonly int compressionLevel; private ICompressionProviderHooks? compressionProviderHooks; private CompressionContext? compressionContext; private CountingStream? counting; private ulong decompressed; private bool limitsExceeded; private bool isDisposed; public override bool CanRead => false; public override bool CanSeek => false; public override bool CanWrite => true; public override long Length { get { throw new NotSupportedException(); } } public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } internal ZipWritingStream(ZipWriter writer, Stream originalStream, ZipCentralDirectoryEntry entry, ZipCompressionMethod zipCompressionMethod, int compressionLevel, Stream? compressionStream = null) : this(writer, originalStream, entry, zipCompressionMethod, compressionLevel) { writeStream = GetWriteStream(compressionStream ?? originalStream); } private ZipWritingStream(ZipWriter writer, Stream originalStream, ZipCentralDirectoryEntry entry, ZipCompressionMethod zipCompressionMethod, int compressionLevel) { this.writer = writer; this.originalStream = originalStream; this.entry = entry; this.zipCompressionMethod = zipCompressionMethod; this.compressionLevel = compressionLevel; writeStream = Stream.Null; } internal static async ValueTask<ZipWritingStream> CreateAsync(ZipWriter writer, Stream originalStream, ZipCentralDirectoryEntry entry, ZipCompressionMethod zipCompressionMethod, int compressionLevel, CancellationToken cancellationToken) { ZipWritingStream stream = new ZipWritingStream(writer, originalStream, entry, zipCompressionMethod, compressionLevel); ZipWritingStream zipWritingStream = stream; zipWritingStream.writeStream = await stream.GetWriteStreamAsync(originalStream, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); return stream; } private Stream GetWriteStream(Stream writeStream) { counting = new CountingStream(SharpCompressStream.CreateNonDisposing(writeStream)); Stream result = counting; CompressionProviderRegistry providers = writer.WriterOptions.Providers; switch (zipCompressionMethod) { case ZipCompressionMethod.None: return result; case ZipCompressionMethod.Deflate: return providers.CreateCompressStream(SharpCompress.Common.CompressionType.Deflate, counting, compressionLevel); case ZipCompressionMethod.BZip2: return providers.CreateCompressStream(SharpCompress.Common.CompressionType.BZip2, counting, compressionLevel); case ZipCompressionMethod.LZMA: { ICompressionProviderHooks compressingProvider2 = providers.GetCompressingProvider(SharpCompress.Common.CompressionType.LZMA); if (compressingProvider2 == null) { throw new ArchiveOperationException("LZMA compression provider not found."); } CompressionContext context2 = new CompressionContext { CanSeek = originalStream.CanSeek }; compressionProviderHooks = compressingProvider2; compressionContext = context2; byte[] preCompressionData2 = compressingProvider2.GetPreCompressionData(context2); if (preCompressionData2 != null) { counting.Write(preCompressionData2, 0, preCompressionData2.Length); } Stream stream = compressingProvider2.CreateCompressStream(counting, compressionLevel, context2); byte[] compressionProperties = compressingProvider2.GetCompressionProperties(stream, context2); if (compressionProperties != null) { counting.Write(compressionProperties, 0, compressionProperties.Length); } return stream; } case ZipCompressionMethod.PPMd: { ICompressionProviderHooks compressingProvider = providers.GetCompressingProvider(SharpCompress.Common.CompressionType.PPMd); if (compressingProvider == null) { throw new ArchiveOperationException("PPMd compression provider not found."); } CompressionContext context = new CompressionContext { CanSeek = originalStream.CanSeek, FormatOptions = writer.PpmdProperties }; compressionProviderHooks = compressingProvider; compressionContext = context; byte[] preCompressionData = compressingProvider.GetPreCompressionData(context); if (preCompressionData != null) { counting.Write(preCompressionData, 0, preCompressionData.Length); } return compressingProvider.CreateCompressStream(counting, compressionLevel, context); } case ZipCompressionMethod.ZStandard: return providers.CreateCompressStream(SharpCompress.Common.CompressionType.ZStandard, counting, compressionLevel); default: throw new NotSupportedException("CompressionMethod: " + zipCompressionMethod); } } private async ValueTask<Stream> GetWriteStreamAsync(Stream writeStream, CancellationToken cancellationToken) { counting = new CountingStream(SharpCompressStream.CreateNonDisposing(writeStream)); Stream result = counting; CompressionProviderRegistry providers = writer.WriterOptions.Providers; switch (zipCompressionMethod) { case ZipCompressionMethod.None: return result; case ZipCompressionMethod.Deflate: return await providers.CreateCompressStreamAsync(SharpCompress.Common.CompressionType.Deflate, counting, compressionLevel, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); case ZipCompressionMethod.BZip2: return await providers.CreateCompressStreamAsync(SharpCompress.Common.CompressionType.BZip2, counting, compressionLevel, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); case ZipCompressionMethod.LZMA: { ICompressionProviderHooks compressingProvider = providers.GetCompressingProvider(SharpCompress.Common.CompressionType.LZMA); if (compressingProvider == null) { throw new ArchiveOperationException("LZMA compression provider not found."); } CompressionContext context = new CompressionContext { CanSeek = originalStream.CanSeek }; compressionProviderHooks = compressingProvider; compressionContext = context; byte[] preCompressionData2 = compressingProvider.GetPreCompressionData(context); if (preCompressionData2 != null) { await counting.WriteAsync(preCompressionData2, 0, preCompressionData2.Length, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } Stream lzmaStream = await compressingProvider.CreateCompressStreamAsync(counting, compressionLevel, context, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); byte[] compressionProperties = compressingProvider.GetCompressionProperties(lzmaStream, context); if (compressionProperties != null) { await counting.WriteAsync(compressionProperties, 0, compressionProperties.Length, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } return lzmaStream; } case ZipCompressionMethod.PPMd: { ICompressionProviderHooks compressingProvider = providers.GetCompressingProvider(SharpCompress.Common.CompressionType.PPMd); if (compressingProvider == null) { throw new ArchiveOperationException("PPMd compression provider not found."); } CompressionContext context = new CompressionContext { CanSeek = originalStream.CanSeek, FormatOptions = writer.PpmdProperties }; compressionProviderHooks = compressingProvider; compressionContext = context; byte[] preCompressionData = compressingProvider.GetPreCompressionData(context); if (preCompressionData != null) { await counting.WriteAsync(preCompressionData, 0, preCompressionData.Length, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } return await compressingProvider.CreateCompressStreamAsync(counting, compressionLevel, context, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } case ZipCompressionMethod.ZStandard: return await providers.CreateCompressStreamAsync(SharpCompress.Common.CompressionType.ZStandard, counting, compressionLevel, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); default: throw new NotSupportedException("CompressionMethod: " + zipCompressionMethod); } } protected override void Dispose(bool disposing) { if (isDisposed) { return; } isDisposed = true; base.Dispose(disposing); if (!disposing) { return; } writeStream.Dispose(); if (limitsExceeded) { originalStream.Dispose(); return; } WritePostCompressionData(); long num = counting?.BytesWritten ?? 0; entry.Crc = (uint)crc.Crc32Result; entry.Compressed = (ulong)num; entry.Decompressed = decompressed; bool flag = entry.Compressed >= uint.MaxValue || entry.Decompressed >= uint.MaxValue; uint compressed = (uint)(flag ? uint.MaxValue : num); uint uncompressed = (uint)(flag ? uint.MaxValue : entry.Decompressed); if (!entry.UsesDataDescriptor) { originalStream.Position = (long)(entry.HeaderOffset + 6); originalStream.WriteByte(0); if (num == 0L && entry.Decompressed == 0L) { originalStream.Position = (long)(entry.HeaderOffset + 8); originalStream.WriteByte(0); originalStream.WriteByte(0); } originalStream.Position = (long)(entry.HeaderOffset + 14); writer.WriteFooter(entry.Crc, compressed, uncompressed); if (flag && entry.Zip64HeaderOffset == 0) { throw new NotSupportedException("Attempted to write a stream that is larger than 4GiB without setting the zip64 option"); } if (entry.Zip64HeaderOffset != 0) { originalStream.Position = (long)(entry.HeaderOffset + entry.Zip64HeaderOffset); Span<byte> span = stackalloc byte[8]; BinaryPrimitives.WriteUInt16LittleEndian(span, 1); originalStream.Write(span.Slice(0, 2)); BinaryPrimitives.WriteUInt16LittleEndian(span, 16); originalStream.Write(span.Slice(0, 2)); BinaryPrimitives.WriteUInt64LittleEndian(span, entry.Decompressed); originalStream.Write(span); BinaryPrimitives.WriteUInt64LittleEndian(span, entry.Compressed); originalStream.Write(span); } originalStream.Position = writer.streamPosition + (long)entry.Compressed; writer.streamPosition += (long)entry.Compressed; } else { if (flag) { throw new NotSupportedException("Streams larger than 4GiB are not supported for non-seekable streams"); } Span<byte> span2 = stackalloc byte[4]; BinaryPrimitives.WriteUInt32LittleEndian(span2, 134695760u); originalStream.Write(span2); writer.WriteFooter(entry.Crc, compressed, uncompressed); writer.streamPosition += (long)(entry.Compressed + 16); } writer.entries.Add(entry); } public override void Flush() { writeStream.Flush(); } public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { CheckWriteLimits(count); decompressed += (uint)count; crc.SlurpBlock(buffer, offset, count); writeStream.Write(buffer, offset, count); CheckPostWriteLimits(); } public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); CheckWriteLimits(count); decompressed += (uint)count; crc.SlurpBlock(buffer, offset, count); await writeStream.WriteAsync(buffer, offset, count, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); CheckPostWriteLimits(); } private void CheckWriteLimits(int count) { if (entry.Zip64HeaderOffset == 0) { long num = counting?.BytesWritten ?? 0; if (limitsExceeded || decompressed + (uint)count > uint.MaxValue || num + (uint)count > uint.MaxValue) { throw new NotSupportedException("Attempted to write a stream that is larger than 4GiB without setting the zip64 option"); } } } private void CheckPostWriteLimits() { if (entry.Zip64HeaderOffset == 0) { long num = counting?.BytesWritten ?? 0; if (decompressed > uint.MaxValue || num > uint.MaxValue) { limitsExceeded = true; throw new NotSupportedException("Attempted to write a stream that is larger than 4GiB without setting the zip64 option"); } } } private void WritePostCompressionData() { if (compressionProviderHooks != null && (object)compressionContext != null && counting != null && zipCompressionMethod != ZipCompressionMethod.None) { byte[] postCompressionData = compressionProviderHooks.GetPostCompressionData(writeStream, compressionContext); if (postCompressionData != null && postCompressionData.Length != 0) { counting.Write(postCompressionData, 0, postCompressionData.Length); } } } private async ValueTask WritePostCompressionDataAsync(CancellationToken cancellationToken) { if (compressionProviderHooks != null && (object)compressionContext != null && counting != null && zipCompressionMethod != ZipCompressionMethod.None) { byte[] postCompressionData = compressionProviderHooks.GetPostCompressionData(writeStream, compressionContext); if (postCompressionData != null && postCompressionData.Length != 0) { await counting.WriteAsync(postCompressionData, 0, postCompressionData.Length, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } } } public override async ValueTask DisposeAsync() { if (isDisposed) { return; } isDisposed = true; IAsyncDisposable asyncDisposable = writeStream; if (asyncDisposable != null) { await asyncDisposable.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false); } else { writeStream.Dispose(); } if (limitsExceeded) { IAsyncDisposable asyncDisposable2 = originalStream; if (asyncDisposable2 != null) { await asyncDisposable2.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false); } else { originalStream.Dispose(); } return; } await WritePostCompressionDataAsync(CancellationToken.None).ConfigureAwait(continueOnCapturedContext: false); long countingCount = counting?.BytesWritten ?? 0; entry.Crc = (uint)crc.Crc32Result; entry.Compressed = (ulong)countingCount; entry.Decompressed = decompressed; bool zip64 = entry.Compressed >= uint.MaxValue || entry.Decompressed >= uint.MaxValue; uint compressedvalue = (uint)(zip64 ? uint.MaxValue : countingCount); uint decompressedvalue = (uint)(zip64 ? uint.MaxValue : entry.Decompressed); if (!entry.UsesDataDescriptor) { originalStream.Position = (long)(entry.HeaderOffset + 6); await originalStream.WriteAsync(new byte[1], 0, 1).ConfigureAwait(continueOnCapturedContext: false); if (countingCount == 0L && entry.Decompressed == 0L) { originalStream.Position = (long)(entry.HeaderOffset + 8); await originalStream.WriteAsync(new byte[2], 0, 2).ConfigureAwait(continueOnCapturedContext: false); } originalStream.Position = (long)(entry.HeaderOffset + 14); await WriteFooterAsync(originalStream, entry.Crc, compressedvalue, decompressedvalue).ConfigureAwait(continueOnCapturedContext: false); if (zip64 && entry.Zip64HeaderOffset == 0) { throw new NotSupportedException("Attempted to write a stream that is larger than 4GiB without setting the zip64 option"); } if (entry.Zip64HeaderOffset != 0) { originalStream.Position = (long)(entry.HeaderOffset + entry.Zip64HeaderOffset); byte[] intBuf = new byte[8]; BinaryPrimitives.WriteUInt16LittleEndian(intBuf, 1); await originalStream.WriteAsync(intBuf, 0, 2).ConfigureAwait(continueOnCapturedContext: false); BinaryPrimitives.WriteUInt16LittleEndian(intBuf, 16); await originalStream.WriteAsync(intBuf, 0, 2).ConfigureAwait(continueOnCapturedContext: false); BinaryPrimitives.WriteUInt64LittleEndian(intBuf, entry.Decompressed); await originalStream.WriteAsync(intBuf, 0, 8).ConfigureAwait(continueOnCapturedContext: false); BinaryPrimitives.WriteUInt64LittleEndian(intBuf, entry.Compressed); await originalStream.WriteAsync(intBuf, 0, 8).ConfigureAwait(continueOnCapturedContext: false); } originalStream.Position = writer.streamPosition + (long)entry.Compressed; writer.streamPosition += (long)entry.Compressed; } else { if (zip64) { throw new NotSupportedException("Streams larger than 4GiB are not supported for non-seekable streams"); } byte[] array = new byte[4]; BinaryPrimitives.WriteUInt32LittleEndian(array, 134695760u); await originalStream.WriteAsync(array, 0, 4).ConfigureAwait(continueOnCapturedContext: false); await WriteFooterAsync(originalStream, entry.Crc, compressedvalue, decompressedvalue).ConfigureAwait(continueOnCapturedContext: false); writer.streamPosition += (long)(entry.Compressed + 16); } writer.entries.Add(entry); await base.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false); } private static async ValueTask WriteFooterAsync(Stream stream, uint crc, uint compressed, uint uncompressed) { byte[] array = new byte[12]; BinaryPrimitives.WriteUInt32LittleEndian(array.AsSpan(0), crc); BinaryPrimitives.WriteUInt32LittleEndian(array.AsSpan(4), compressed); BinaryPrimitives.WriteUInt32LittleEndian(array.AsSpan(8), uncompressed); await stream.WriteAsync(array, 0, array.Length).ConfigureAwait(continueOnCapturedContext: false); } } private readonly SharpCompress.Common.CompressionType compressionType; private readonly int compressionLevel; private readonly List<ZipCentralDirectoryEntry> entries = new List<ZipCentralDirectoryEntry>(); private readonly string zipComment; private long streamPosition; private PpmdProperties? ppmdProps; private readonly bool isZip64; private PpmdProperties PpmdProperties => ppmdProps ?? (ppmdProps = new PpmdProperties()); public override async ValueTask DisposeAsync() { if (_isDisposed) { return; } GC.SuppressFinalize(this); _isDisposed = true; using PooledMemoryStream ms = new PooledMemoryStream(); ulong num = 0uL; foreach (ZipCentralDirectoryEntry entry in entries) { num += entry.Write(ms); } WriteEndRecord(ms, num); ms.Position = 0L; await ms.CopyToAsync(base.OutputStream.NotNull()).ConfigureAwait(continueOnCapturedContext: false); IAsyncDisposable outputStream = base.OutputStream; if (outputStream != null) { await outputStream.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false); } else { base.OutputStream?.Dispose(); } await base.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false); } public override async ValueTask WriteAsync(string filename, Stream source, DateTime? modificationTime, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); await WriteAsync(filename, source, new ZipWriterEntryOptions { ModificationDateTime = modificationTime }, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public async ValueTask WriteAsync(string entryPath, Stream source, ZipWriterEntryOptions zipWriterEntryOptions, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); await using ZipWritingStream output = await WriteToStreamAsync(entryPath, zipWriterEntryOptions, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); await WrapWithProgress(source, entryPath).CopyToAsync(output, 81920, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } private async ValueTask<ZipWritingStream> WriteToStreamAsync(string entryPath, ZipWriterEntryOpti
System.Text.Encoding.CodePages.dll
Decompiled 2 days ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers.Binary; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Threading; using FxResources.System.Text.Encoding.CodePages; using Microsoft.CodeAnalysis; using Microsoft.Win32.SafeHandles; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("System.Text.Encoding.CodePages")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Provides support for code-page based encodings, including Windows-1252, Shift-JIS, and GB2312.\r\n\r\nCommonly Used Types:\r\nSystem.Text.CodePagesEncodingProvider")] [assembly: AssemblyFileVersion("8.0.23.53103")] [assembly: AssemblyInformationalVersion("8.0.0+5535e31a712343a63f5d7d796cd874e563e5ac14")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("System.Text.Encoding.CodePages")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("8.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [module: System.Runtime.CompilerServices.NullablePublicOnly(false)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.System.Text.Encoding.CodePages { internal static class SR { } } namespace System { internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string ArgumentOutOfRange_NeedNonNegNum => GetResourceString("ArgumentOutOfRange_NeedNonNegNum"); internal static string ArgumentOutOfRange_IndexCount => GetResourceString("ArgumentOutOfRange_IndexCount"); internal static string ArgumentOutOfRange_IndexCountBuffer => GetResourceString("ArgumentOutOfRange_IndexCountBuffer"); internal static string NotSupported_NoCodepageData => GetResourceString("NotSupported_NoCodepageData"); internal static string Argument_EncodingConversionOverflowBytes => GetResourceString("Argument_EncodingConversionOverflowBytes"); internal static string Argument_InvalidCharSequenceNoIndex => GetResourceString("Argument_InvalidCharSequenceNoIndex"); internal static string ArgumentOutOfRange_GetByteCountOverflow => GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"); internal static string Argument_EncodingConversionOverflowChars => GetResourceString("Argument_EncodingConversionOverflowChars"); internal static string ArgumentOutOfRange_GetCharCountOverflow => GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"); internal static string Argument_EncoderFallbackNotEmpty => GetResourceString("Argument_EncoderFallbackNotEmpty"); internal static string Argument_RecursiveFallback => GetResourceString("Argument_RecursiveFallback"); internal static string Argument_RecursiveFallbackBytes => GetResourceString("Argument_RecursiveFallbackBytes"); internal static string ArgumentOutOfRange_Range => GetResourceString("ArgumentOutOfRange_Range"); internal static string Argument_CodepageNotSupported => GetResourceString("Argument_CodepageNotSupported"); internal static string ArgumentOutOfRange_IndexMustBeLess => GetResourceString("ArgumentOutOfRange_IndexMustBeLess"); internal static string ArgumentOutOfRange_IndexMustBeLessOrEqual => GetResourceString("ArgumentOutOfRange_IndexMustBeLessOrEqual"); internal static string MissingEncodingNameResource => GetResourceString("MissingEncodingNameResource"); internal static string Globalization_cp_37 => GetResourceString("Globalization_cp_37"); internal static string Globalization_cp_437 => GetResourceString("Globalization_cp_437"); internal static string Globalization_cp_500 => GetResourceString("Globalization_cp_500"); internal static string Globalization_cp_708 => GetResourceString("Globalization_cp_708"); internal static string Globalization_cp_720 => GetResourceString("Globalization_cp_720"); internal static string Globalization_cp_737 => GetResourceString("Globalization_cp_737"); internal static string Globalization_cp_775 => GetResourceString("Globalization_cp_775"); internal static string Globalization_cp_850 => GetResourceString("Globalization_cp_850"); internal static string Globalization_cp_852 => GetResourceString("Globalization_cp_852"); internal static string Globalization_cp_855 => GetResourceString("Globalization_cp_855"); internal static string Globalization_cp_857 => GetResourceString("Globalization_cp_857"); internal static string Globalization_cp_858 => GetResourceString("Globalization_cp_858"); internal static string Globalization_cp_860 => GetResourceString("Globalization_cp_860"); internal static string Globalization_cp_861 => GetResourceString("Globalization_cp_861"); internal static string Globalization_cp_862 => GetResourceString("Globalization_cp_862"); internal static string Globalization_cp_863 => GetResourceString("Globalization_cp_863"); internal static string Globalization_cp_864 => GetResourceString("Globalization_cp_864"); internal static string Globalization_cp_865 => GetResourceString("Globalization_cp_865"); internal static string Globalization_cp_866 => GetResourceString("Globalization_cp_866"); internal static string Globalization_cp_869 => GetResourceString("Globalization_cp_869"); internal static string Globalization_cp_870 => GetResourceString("Globalization_cp_870"); internal static string Globalization_cp_874 => GetResourceString("Globalization_cp_874"); internal static string Globalization_cp_875 => GetResourceString("Globalization_cp_875"); internal static string Globalization_cp_932 => GetResourceString("Globalization_cp_932"); internal static string Globalization_cp_936 => GetResourceString("Globalization_cp_936"); internal static string Globalization_cp_949 => GetResourceString("Globalization_cp_949"); internal static string Globalization_cp_950 => GetResourceString("Globalization_cp_950"); internal static string Globalization_cp_1026 => GetResourceString("Globalization_cp_1026"); internal static string Globalization_cp_1047 => GetResourceString("Globalization_cp_1047"); internal static string Globalization_cp_1140 => GetResourceString("Globalization_cp_1140"); internal static string Globalization_cp_1141 => GetResourceString("Globalization_cp_1141"); internal static string Globalization_cp_1142 => GetResourceString("Globalization_cp_1142"); internal static string Globalization_cp_1143 => GetResourceString("Globalization_cp_1143"); internal static string Globalization_cp_1144 => GetResourceString("Globalization_cp_1144"); internal static string Globalization_cp_1145 => GetResourceString("Globalization_cp_1145"); internal static string Globalization_cp_1146 => GetResourceString("Globalization_cp_1146"); internal static string Globalization_cp_1147 => GetResourceString("Globalization_cp_1147"); internal static string Globalization_cp_1148 => GetResourceString("Globalization_cp_1148"); internal static string Globalization_cp_1149 => GetResourceString("Globalization_cp_1149"); internal static string Globalization_cp_1250 => GetResourceString("Globalization_cp_1250"); internal static string Globalization_cp_1251 => GetResourceString("Globalization_cp_1251"); internal static string Globalization_cp_1252 => GetResourceString("Globalization_cp_1252"); internal static string Globalization_cp_1253 => GetResourceString("Globalization_cp_1253"); internal static string Globalization_cp_1254 => GetResourceString("Globalization_cp_1254"); internal static string Globalization_cp_1255 => GetResourceString("Globalization_cp_1255"); internal static string Globalization_cp_1256 => GetResourceString("Globalization_cp_1256"); internal static string Globalization_cp_1257 => GetResourceString("Globalization_cp_1257"); internal static string Globalization_cp_1258 => GetResourceString("Globalization_cp_1258"); internal static string Globalization_cp_1361 => GetResourceString("Globalization_cp_1361"); internal static string Globalization_cp_10000 => GetResourceString("Globalization_cp_10000"); internal static string Globalization_cp_10001 => GetResourceString("Globalization_cp_10001"); internal static string Globalization_cp_10002 => GetResourceString("Globalization_cp_10002"); internal static string Globalization_cp_10003 => GetResourceString("Globalization_cp_10003"); internal static string Globalization_cp_10004 => GetResourceString("Globalization_cp_10004"); internal static string Globalization_cp_10005 => GetResourceString("Globalization_cp_10005"); internal static string Globalization_cp_10006 => GetResourceString("Globalization_cp_10006"); internal static string Globalization_cp_10007 => GetResourceString("Globalization_cp_10007"); internal static string Globalization_cp_10008 => GetResourceString("Globalization_cp_10008"); internal static string Globalization_cp_10010 => GetResourceString("Globalization_cp_10010"); internal static string Globalization_cp_10017 => GetResourceString("Globalization_cp_10017"); internal static string Globalization_cp_10021 => GetResourceString("Globalization_cp_10021"); internal static string Globalization_cp_10029 => GetResourceString("Globalization_cp_10029"); internal static string Globalization_cp_10079 => GetResourceString("Globalization_cp_10079"); internal static string Globalization_cp_10081 => GetResourceString("Globalization_cp_10081"); internal static string Globalization_cp_10082 => GetResourceString("Globalization_cp_10082"); internal static string Globalization_cp_20000 => GetResourceString("Globalization_cp_20000"); internal static string Globalization_cp_20001 => GetResourceString("Globalization_cp_20001"); internal static string Globalization_cp_20002 => GetResourceString("Globalization_cp_20002"); internal static string Globalization_cp_20003 => GetResourceString("Globalization_cp_20003"); internal static string Globalization_cp_20004 => GetResourceString("Globalization_cp_20004"); internal static string Globalization_cp_20005 => GetResourceString("Globalization_cp_20005"); internal static string Globalization_cp_20105 => GetResourceString("Globalization_cp_20105"); internal static string Globalization_cp_20106 => GetResourceString("Globalization_cp_20106"); internal static string Globalization_cp_20107 => GetResourceString("Globalization_cp_20107"); internal static string Globalization_cp_20108 => GetResourceString("Globalization_cp_20108"); internal static string Globalization_cp_20261 => GetResourceString("Globalization_cp_20261"); internal static string Globalization_cp_20269 => GetResourceString("Globalization_cp_20269"); internal static string Globalization_cp_20273 => GetResourceString("Globalization_cp_20273"); internal static string Globalization_cp_20277 => GetResourceString("Globalization_cp_20277"); internal static string Globalization_cp_20278 => GetResourceString("Globalization_cp_20278"); internal static string Globalization_cp_20280 => GetResourceString("Globalization_cp_20280"); internal static string Globalization_cp_20284 => GetResourceString("Globalization_cp_20284"); internal static string Globalization_cp_20285 => GetResourceString("Globalization_cp_20285"); internal static string Globalization_cp_20290 => GetResourceString("Globalization_cp_20290"); internal static string Globalization_cp_20297 => GetResourceString("Globalization_cp_20297"); internal static string Globalization_cp_20420 => GetResourceString("Globalization_cp_20420"); internal static string Globalization_cp_20423 => GetResourceString("Globalization_cp_20423"); internal static string Globalization_cp_20424 => GetResourceString("Globalization_cp_20424"); internal static string Globalization_cp_20833 => GetResourceString("Globalization_cp_20833"); internal static string Globalization_cp_20838 => GetResourceString("Globalization_cp_20838"); internal static string Globalization_cp_20866 => GetResourceString("Globalization_cp_20866"); internal static string Globalization_cp_20871 => GetResourceString("Globalization_cp_20871"); internal static string Globalization_cp_20880 => GetResourceString("Globalization_cp_20880"); internal static string Globalization_cp_20905 => GetResourceString("Globalization_cp_20905"); internal static string Globalization_cp_20924 => GetResourceString("Globalization_cp_20924"); internal static string Globalization_cp_20932 => GetResourceString("Globalization_cp_20932"); internal static string Globalization_cp_20936 => GetResourceString("Globalization_cp_20936"); internal static string Globalization_cp_20949 => GetResourceString("Globalization_cp_20949"); internal static string Globalization_cp_21025 => GetResourceString("Globalization_cp_21025"); internal static string Globalization_cp_21027 => GetResourceString("Globalization_cp_21027"); internal static string Globalization_cp_21866 => GetResourceString("Globalization_cp_21866"); internal static string Globalization_cp_28592 => GetResourceString("Globalization_cp_28592"); internal static string Globalization_cp_28593 => GetResourceString("Globalization_cp_28593"); internal static string Globalization_cp_28594 => GetResourceString("Globalization_cp_28594"); internal static string Globalization_cp_28595 => GetResourceString("Globalization_cp_28595"); internal static string Globalization_cp_28596 => GetResourceString("Globalization_cp_28596"); internal static string Globalization_cp_28597 => GetResourceString("Globalization_cp_28597"); internal static string Globalization_cp_28598 => GetResourceString("Globalization_cp_28598"); internal static string Globalization_cp_28599 => GetResourceString("Globalization_cp_28599"); internal static string Globalization_cp_28603 => GetResourceString("Globalization_cp_28603"); internal static string Globalization_cp_28605 => GetResourceString("Globalization_cp_28605"); internal static string Globalization_cp_29001 => GetResourceString("Globalization_cp_29001"); internal static string Globalization_cp_38598 => GetResourceString("Globalization_cp_38598"); internal static string Globalization_cp_50000 => GetResourceString("Globalization_cp_50000"); internal static string Globalization_cp_50220 => GetResourceString("Globalization_cp_50220"); internal static string Globalization_cp_50221 => GetResourceString("Globalization_cp_50221"); internal static string Globalization_cp_50222 => GetResourceString("Globalization_cp_50222"); internal static string Globalization_cp_50225 => GetResourceString("Globalization_cp_50225"); internal static string Globalization_cp_50227 => GetResourceString("Globalization_cp_50227"); internal static string Globalization_cp_50229 => GetResourceString("Globalization_cp_50229"); internal static string Globalization_cp_50930 => GetResourceString("Globalization_cp_50930"); internal static string Globalization_cp_50931 => GetResourceString("Globalization_cp_50931"); internal static string Globalization_cp_50933 => GetResourceString("Globalization_cp_50933"); internal static string Globalization_cp_50935 => GetResourceString("Globalization_cp_50935"); internal static string Globalization_cp_50937 => GetResourceString("Globalization_cp_50937"); internal static string Globalization_cp_50939 => GetResourceString("Globalization_cp_50939"); internal static string Globalization_cp_51932 => GetResourceString("Globalization_cp_51932"); internal static string Globalization_cp_51936 => GetResourceString("Globalization_cp_51936"); internal static string Globalization_cp_51949 => GetResourceString("Globalization_cp_51949"); internal static string Globalization_cp_52936 => GetResourceString("Globalization_cp_52936"); internal static string Globalization_cp_54936 => GetResourceString("Globalization_cp_54936"); internal static string Globalization_cp_57002 => GetResourceString("Globalization_cp_57002"); internal static string Globalization_cp_57003 => GetResourceString("Globalization_cp_57003"); internal static string Globalization_cp_57004 => GetResourceString("Globalization_cp_57004"); internal static string Globalization_cp_57005 => GetResourceString("Globalization_cp_57005"); internal static string Globalization_cp_57006 => GetResourceString("Globalization_cp_57006"); internal static string Globalization_cp_57007 => GetResourceString("Globalization_cp_57007"); internal static string Globalization_cp_57008 => GetResourceString("Globalization_cp_57008"); internal static string Globalization_cp_57009 => GetResourceString("Globalization_cp_57009"); internal static string Globalization_cp_57010 => GetResourceString("Globalization_cp_57010"); internal static string Globalization_cp_57011 => GetResourceString("Globalization_cp_57011"); internal static bool UsingResourceKeys() { return s_usingResourceKeys; } private static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } private static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider provider, string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] internal sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] internal sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } } namespace System.Runtime.Versioning { internal abstract class OSPlatformAttribute : Attribute { public string PlatformName { get; } private protected OSPlatformAttribute(string platformName) { PlatformName = platformName; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] internal sealed class TargetPlatformAttribute : OSPlatformAttribute { public TargetPlatformAttribute(string platformName) : base(platformName) { } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] internal sealed class SupportedOSPlatformAttribute : OSPlatformAttribute { public SupportedOSPlatformAttribute(string platformName) : base(platformName) { } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] internal sealed class UnsupportedOSPlatformAttribute : OSPlatformAttribute { public string Message { get; } public UnsupportedOSPlatformAttribute(string platformName) : base(platformName) { } public UnsupportedOSPlatformAttribute(string platformName, string message) : base(platformName) { Message = message; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] internal sealed class ObsoletedOSPlatformAttribute : OSPlatformAttribute { public string Message { get; } public string Url { get; set; } public ObsoletedOSPlatformAttribute(string platformName) : base(platformName) { } public ObsoletedOSPlatformAttribute(string platformName, string message) : base(platformName) { Message = message; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] internal sealed class SupportedOSPlatformGuardAttribute : OSPlatformAttribute { public SupportedOSPlatformGuardAttribute(string platformName) : base(platformName) { } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] internal sealed class UnsupportedOSPlatformGuardAttribute : OSPlatformAttribute { public UnsupportedOSPlatformGuardAttribute(string platformName) : base(platformName) { } } } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class LibraryImportAttribute : Attribute { public string LibraryName { get; } public string EntryPoint { get; set; } public StringMarshalling StringMarshalling { get; set; } public Type StringMarshallingCustomType { get; set; } public bool SetLastError { get; set; } public LibraryImportAttribute(string libraryName) { LibraryName = libraryName; } } internal enum StringMarshalling { Custom, Utf8, Utf16 } } namespace System.Text { internal abstract class BaseCodePageEncoding : EncodingNLS, ISerializable { [StructLayout(LayoutKind.Explicit)] internal struct CodePageDataFileHeader { [FieldOffset(0)] internal char TableName; [FieldOffset(32)] internal ushort Version; [FieldOffset(40)] internal short CodePageCount; [FieldOffset(42)] internal short unused1; } [StructLayout(LayoutKind.Explicit, Pack = 2)] internal struct CodePageIndex { [FieldOffset(0)] internal char CodePageName; [FieldOffset(32)] internal short CodePage; [FieldOffset(34)] internal short ByteCount; [FieldOffset(36)] internal int Offset; } [StructLayout(LayoutKind.Explicit)] internal struct CodePageHeader { [FieldOffset(0)] internal char CodePageName; [FieldOffset(32)] internal ushort VersionMajor; [FieldOffset(34)] internal ushort VersionMinor; [FieldOffset(36)] internal ushort VersionRevision; [FieldOffset(38)] internal ushort VersionBuild; [FieldOffset(40)] internal short CodePage; [FieldOffset(42)] internal short ByteCount; [FieldOffset(44)] internal char UnicodeReplace; [FieldOffset(46)] internal ushort ByteReplace; } internal const string CODE_PAGE_DATA_FILE_NAME = "codepages.nlp"; protected int dataTableCodePage; protected int iExtraBytes; protected char[] arrayUnicodeBestFit; protected char[] arrayBytesBestFit; private const int CODEPAGE_DATA_FILE_HEADER_SIZE = 44; private const int CODEPAGE_HEADER_SIZE = 48; private static readonly byte[] s_codePagesDataHeader = new byte[44]; protected static Stream s_codePagesEncodingDataStream = GetEncodingDataStream("codepages.nlp"); protected static readonly object s_streamLock = new object(); protected byte[] m_codePageHeader = new byte[48]; protected int m_firstDataWordOffset; protected int m_dataSize; protected SafeAllocHHandle safeNativeMemoryHandle; internal BaseCodePageEncoding(int codepage) : this(codepage, codepage) { } internal BaseCodePageEncoding(int codepage, int dataCodePage) : base(codepage, new InternalEncoderBestFitFallback(null), new InternalDecoderBestFitFallback(null)) { ((InternalEncoderBestFitFallback)base.EncoderFallback).encoding = this; ((InternalDecoderBestFitFallback)base.DecoderFallback).encoding = this; dataTableCodePage = dataCodePage; LoadCodePageTables(); } internal BaseCodePageEncoding(int codepage, int dataCodePage, EncoderFallback enc, DecoderFallback dec) : base(codepage, enc, dec) { dataTableCodePage = dataCodePage; LoadCodePageTables(); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } private unsafe static void ReadCodePageDataFileHeader(Stream stream, byte[] codePageDataFileHeader) { int num = stream.Read(codePageDataFileHeader, 0, codePageDataFileHeader.Length); if (BitConverter.IsLittleEndian) { return; } fixed (byte* ptr = &codePageDataFileHeader[0]) { CodePageDataFileHeader* ptr2 = (CodePageDataFileHeader*)ptr; char* ptr3 = &ptr2->TableName; for (int i = 0; i < 16; i++) { ptr3[i] = (char)BinaryPrimitives.ReverseEndianness(ptr3[i]); } ushort* ptr4 = &ptr2->Version; for (int j = 0; j < 4; j++) { ptr4[j] = BinaryPrimitives.ReverseEndianness(ptr4[j]); } ptr2->CodePageCount = BinaryPrimitives.ReverseEndianness(ptr2->CodePageCount); } } private unsafe static void ReadCodePageIndex(Stream stream, byte[] codePageIndex) { int num = stream.Read(codePageIndex, 0, codePageIndex.Length); if (BitConverter.IsLittleEndian) { return; } fixed (byte* ptr = &codePageIndex[0]) { CodePageIndex* ptr2 = (CodePageIndex*)ptr; char* ptr3 = &ptr2->CodePageName; for (int i = 0; i < 16; i++) { ptr3[i] = (char)BinaryPrimitives.ReverseEndianness(ptr3[i]); } ptr2->CodePage = BinaryPrimitives.ReverseEndianness(ptr2->CodePage); ptr2->ByteCount = BinaryPrimitives.ReverseEndianness(ptr2->ByteCount); ptr2->Offset = BinaryPrimitives.ReverseEndianness(ptr2->Offset); } } private unsafe static void ReadCodePageHeader(Stream stream, byte[] codePageHeader) { int num = stream.Read(codePageHeader, 0, codePageHeader.Length); if (BitConverter.IsLittleEndian) { return; } fixed (byte* ptr = &codePageHeader[0]) { CodePageHeader* ptr2 = (CodePageHeader*)ptr; char* ptr3 = &ptr2->CodePageName; for (int i = 0; i < 16; i++) { ptr3[i] = (char)BinaryPrimitives.ReverseEndianness(ptr3[i]); } ptr2->VersionMajor = BinaryPrimitives.ReverseEndianness(ptr2->VersionMajor); ptr2->VersionMinor = BinaryPrimitives.ReverseEndianness(ptr2->VersionMinor); ptr2->VersionRevision = BinaryPrimitives.ReverseEndianness(ptr2->VersionRevision); ptr2->VersionBuild = BinaryPrimitives.ReverseEndianness(ptr2->VersionBuild); ptr2->CodePage = BinaryPrimitives.ReverseEndianness(ptr2->CodePage); ptr2->ByteCount = BinaryPrimitives.ReverseEndianness(ptr2->ByteCount); ptr2->UnicodeReplace = (char)BinaryPrimitives.ReverseEndianness(ptr2->UnicodeReplace); ptr2->ByteReplace = BinaryPrimitives.ReverseEndianness(ptr2->ByteReplace); } } internal static Stream GetEncodingDataStream(string tableName) { Stream manifestResourceStream = typeof(CodePagesEncodingProvider).Assembly.GetManifestResourceStream(tableName); if (manifestResourceStream == null) { throw new InvalidOperationException(); } ReadCodePageDataFileHeader(manifestResourceStream, s_codePagesDataHeader); return manifestResourceStream; } private void LoadCodePageTables() { if (!FindCodePage(dataTableCodePage)) { throw new NotSupportedException(System.SR.Format(System.SR.NotSupported_NoCodepageData, CodePage)); } LoadManagedCodePage(); } private unsafe bool FindCodePage(int codePage) { byte[] array = new byte[sizeof(CodePageIndex)]; lock (s_streamLock) { s_codePagesEncodingDataStream.Seek(44L, SeekOrigin.Begin); int codePageCount; fixed (byte* ptr = &s_codePagesDataHeader[0]) { CodePageDataFileHeader* ptr2 = (CodePageDataFileHeader*)ptr; codePageCount = ptr2->CodePageCount; } fixed (byte* ptr3 = &array[0]) { CodePageIndex* ptr4 = (CodePageIndex*)ptr3; for (int i = 0; i < codePageCount; i++) { ReadCodePageIndex(s_codePagesEncodingDataStream, array); if (ptr4->CodePage == codePage) { long position = s_codePagesEncodingDataStream.Position; s_codePagesEncodingDataStream.Seek(ptr4->Offset, SeekOrigin.Begin); ReadCodePageHeader(s_codePagesEncodingDataStream, m_codePageHeader); m_firstDataWordOffset = (int)s_codePagesEncodingDataStream.Position; if (i == codePageCount - 1) { m_dataSize = (int)(s_codePagesEncodingDataStream.Length - ptr4->Offset - m_codePageHeader.Length); } else { s_codePagesEncodingDataStream.Seek(position, SeekOrigin.Begin); int offset = ptr4->Offset; ReadCodePageIndex(s_codePagesEncodingDataStream, array); m_dataSize = ptr4->Offset - offset - m_codePageHeader.Length; } return true; } } } } return false; } internal unsafe static int GetCodePageByteSize(int codePage) { byte[] array = new byte[sizeof(CodePageIndex)]; lock (s_streamLock) { s_codePagesEncodingDataStream.Seek(44L, SeekOrigin.Begin); int codePageCount; fixed (byte* ptr = &s_codePagesDataHeader[0]) { CodePageDataFileHeader* ptr2 = (CodePageDataFileHeader*)ptr; codePageCount = ptr2->CodePageCount; } fixed (byte* ptr3 = &array[0]) { CodePageIndex* ptr4 = (CodePageIndex*)ptr3; for (int i = 0; i < codePageCount; i++) { ReadCodePageIndex(s_codePagesEncodingDataStream, array); if (ptr4->CodePage == codePage) { return ptr4->ByteCount; } } } } return 0; } protected abstract void LoadManagedCodePage(); protected unsafe byte* GetNativeMemory(int iSize) { if (safeNativeMemoryHandle == null) { byte* ptr = (byte*)(void*)Marshal.AllocHGlobal(iSize); safeNativeMemoryHandle = new SafeAllocHHandle((IntPtr)ptr); } return (byte*)(void*)safeNativeMemoryHandle.DangerousGetHandle(); } protected abstract void ReadBestFitTable(); internal char[] GetBestFitUnicodeToBytesData() { if (arrayUnicodeBestFit == null) { ReadBestFitTable(); } return arrayUnicodeBestFit; } internal char[] GetBestFitBytesToUnicodeData() { if (arrayBytesBestFit == null) { ReadBestFitTable(); } return arrayBytesBestFit; } internal void CheckMemorySection() { if (safeNativeMemoryHandle != null && safeNativeMemoryHandle.DangerousGetHandle() == IntPtr.Zero) { LoadManagedCodePage(); } } } public sealed class CodePagesEncodingProvider : EncodingProvider { private static readonly EncodingProvider s_singleton = new CodePagesEncodingProvider(); private readonly Dictionary<int, Encoding> _encodings = new Dictionary<int, Encoding>(); private readonly ReaderWriterLockSlim _cacheLock = new ReaderWriterLockSlim(); private const int ISCIIAssemese = 57006; private const int ISCIIBengali = 57003; private const int ISCIIDevanagari = 57002; private const int ISCIIGujarathi = 57010; private const int ISCIIKannada = 57008; private const int ISCIIMalayalam = 57009; private const int ISCIIOriya = 57007; private const int ISCIIPanjabi = 57011; private const int ISCIITamil = 57004; private const int ISCIITelugu = 57005; private const int ISOKorean = 50225; private const int ChineseHZ = 52936; private const int ISO2022JP = 50220; private const int ISO2022JPESC = 50221; private const int ISO2022JPSISO = 50222; private const int ISOSimplifiedCN = 50227; private const int EUCJP = 51932; private const int CodePageMacGB2312 = 10008; private const int CodePageMacKorean = 10003; private const int CodePageGB2312 = 20936; private const int CodePageDLLKorean = 20949; private const int GB18030 = 54936; private const int DuplicateEUCCN = 51936; private const int EUCKR = 51949; private const int EUCCN = 936; private const int ISO_8859_8I = 38598; private const int ISO_8859_8_Visual = 28598; public static EncodingProvider Instance => s_singleton; private static int SystemDefaultCodePage => 0; internal CodePagesEncodingProvider() { } public override Encoding? GetEncoding(int codepage) { if (codepage < 0 || codepage > 65535) { return null; } if (codepage == 0) { int systemDefaultCodePage = SystemDefaultCodePage; if (systemDefaultCodePage == 0) { return null; } return GetEncoding(systemDefaultCodePage); } Encoding value = null; _cacheLock.EnterUpgradeableReadLock(); try { if (_encodings.TryGetValue(codepage, out value)) { return value; } switch (BaseCodePageEncoding.GetCodePageByteSize(codepage)) { case 1: value = new SBCSCodePageEncoding(codepage); break; case 2: value = new DBCSCodePageEncoding(codepage); break; default: value = GetEncodingRare(codepage); if (value == null) { return null; } break; } _cacheLock.EnterWriteLock(); try { if (_encodings.TryGetValue(codepage, out var value2)) { return value2; } _encodings.Add(codepage, value); return value; } finally { _cacheLock.ExitWriteLock(); } } finally { _cacheLock.ExitUpgradeableReadLock(); } } public override Encoding? GetEncoding(string name) { int codePageFromName = System.Text.EncodingTable.GetCodePageFromName(name); if (codePageFromName == 0) { return null; } return GetEncoding(codePageFromName); } private static Encoding GetEncodingRare(int codepage) { Encoding result = null; switch (codepage) { case 57002: case 57003: case 57004: case 57005: case 57006: case 57007: case 57008: case 57009: case 57010: case 57011: result = new ISCIIEncoding(codepage); break; case 10008: result = new DBCSCodePageEncoding(10008, 20936); break; case 10003: result = new DBCSCodePageEncoding(10003, 20949); break; case 54936: result = new GB18030Encoding(); break; case 50220: case 50221: case 50222: case 50225: case 52936: result = new ISO2022Encoding(codepage); break; case 50227: case 51936: result = new DBCSCodePageEncoding(codepage, 936); break; case 51932: result = new EUCJPEncoding(); break; case 51949: result = new DBCSCodePageEncoding(codepage, 20949); break; case 38598: result = new SBCSCodePageEncoding(codepage, 28598); break; } return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal unsafe static ref T GetNonNullPinnableReference<T>(T[] array) where T : struct { if (array.Length == 0) { return ref Unsafe.AsRef<T>((void*)1); } return ref array[0]; } } internal class DBCSCodePageEncoding : BaseCodePageEncoding { internal sealed class DBCSDecoder : System.Text.DecoderNLS { internal byte bLeftOver; internal override bool HasState => bLeftOver != 0; public DBCSDecoder(DBCSCodePageEncoding encoding) : base(encoding) { } public override void Reset() { bLeftOver = 0; m_fallbackBuffer?.Reset(); } } protected unsafe char* mapBytesToUnicode = null; protected unsafe ushort* mapUnicodeToBytes = null; protected const char UNKNOWN_CHAR_FLAG = '\0'; protected const char UNICODE_REPLACEMENT_CHAR = '\ufffd'; protected const char LEAD_BYTE_CHAR = '\ufffe'; private ushort _bytesUnknown; private int _byteCountUnknown; protected char charUnknown; private static object s_InternalSyncObject; private static object InternalSyncObject { get { if (s_InternalSyncObject == null) { object value = new object(); Interlocked.CompareExchange<object>(ref s_InternalSyncObject, value, (object)null); } return s_InternalSyncObject; } } public DBCSCodePageEncoding(int codePage) : this(codePage, codePage) { } internal unsafe DBCSCodePageEncoding(int codePage, int dataCodePage) : base(codePage, dataCodePage) { } internal unsafe DBCSCodePageEncoding(int codePage, int dataCodePage, EncoderFallback enc, DecoderFallback dec) : base(codePage, dataCodePage, enc, dec) { } internal unsafe static char ReadChar(char* pChar) { if (BitConverter.IsLittleEndian) { return *pChar; } return (char)BinaryPrimitives.ReverseEndianness(*pChar); } protected unsafe override void LoadManagedCodePage() { fixed (byte* ptr = &m_codePageHeader[0]) { CodePageHeader* ptr2 = (CodePageHeader*)ptr; if (ptr2->ByteCount != 2) { throw new NotSupportedException(System.SR.Format(System.SR.NotSupported_NoCodepageData, CodePage)); } _bytesUnknown = ptr2->ByteReplace; charUnknown = ptr2->UnicodeReplace; if (base.DecoderFallback is InternalDecoderBestFitFallback) { ((InternalDecoderBestFitFallback)base.DecoderFallback).cReplacement = charUnknown; } _byteCountUnknown = 1; if (_bytesUnknown > 255) { _byteCountUnknown++; } int num = 262148 + iExtraBytes; byte* nativeMemory = GetNativeMemory(num); Unsafe.InitBlockUnaligned(nativeMemory, 0, (uint)num); mapBytesToUnicode = (char*)nativeMemory; mapUnicodeToBytes = (ushort*)(nativeMemory + 131072); byte[] array = new byte[m_dataSize]; lock (BaseCodePageEncoding.s_streamLock) { BaseCodePageEncoding.s_codePagesEncodingDataStream.Seek(m_firstDataWordOffset, SeekOrigin.Begin); int num2 = BaseCodePageEncoding.s_codePagesEncodingDataStream.Read(array, 0, m_dataSize); } fixed (byte* ptr3 = array) { char* ptr4 = (char*)ptr3; int num3 = 0; int num4 = 0; while (num3 < 65536) { char c = ReadChar(ptr4); ptr4++; switch (c) { case '\u0001': num3 = ReadChar(ptr4); ptr4++; continue; case '\u0002': case '\u0003': case '\u0004': case '\u0005': case '\u0006': case '\a': case '\b': case '\t': case '\n': case '\v': case '\f': case '\r': case '\u000e': case '\u000f': case '\u0010': case '\u0011': case '\u0012': case '\u0013': case '\u0014': case '\u0015': case '\u0016': case '\u0017': case '\u0018': case '\u0019': case '\u001a': case '\u001b': case '\u001c': case '\u001d': case '\u001e': case '\u001f': num3 += c; continue; } switch (c) { case '\uffff': num4 = num3; c = (char)num3; break; case '\ufffe': num4 = num3; break; case '\ufffd': num3++; continue; default: num4 = num3; break; } if (CleanUpBytes(ref num4)) { if (c != '\ufffe') { mapUnicodeToBytes[(int)c] = (ushort)num4; } mapBytesToUnicode[num4] = c; } num3++; } } CleanUpEndBytes(mapBytesToUnicode); } } protected virtual bool CleanUpBytes(ref int bytes) { return true; } protected unsafe virtual void CleanUpEndBytes(char* chars) { } protected unsafe override void ReadBestFitTable() { lock (InternalSyncObject) { if (arrayUnicodeBestFit != null) { return; } byte[] array = new byte[m_dataSize]; lock (BaseCodePageEncoding.s_streamLock) { BaseCodePageEncoding.s_codePagesEncodingDataStream.Seek(m_firstDataWordOffset, SeekOrigin.Begin); int num = BaseCodePageEncoding.s_codePagesEncodingDataStream.Read(array, 0, m_dataSize); } fixed (byte* ptr = array) { char* ptr2 = (char*)ptr; int num2 = 0; while (num2 < 65536) { char c = ReadChar(ptr2); ptr2++; switch (c) { case '\u0001': num2 = ReadChar(ptr2); ptr2++; break; case '\u0002': case '\u0003': case '\u0004': case '\u0005': case '\u0006': case '\a': case '\b': case '\t': case '\n': case '\v': case '\f': case '\r': case '\u000e': case '\u000f': case '\u0010': case '\u0011': case '\u0012': case '\u0013': case '\u0014': case '\u0015': case '\u0016': case '\u0017': case '\u0018': case '\u0019': case '\u001a': case '\u001b': case '\u001c': case '\u001d': case '\u001e': case '\u001f': num2 += c; break; default: num2++; break; } } char* ptr3 = ptr2; int num3 = 0; num2 = ReadChar(ptr2); ptr2++; while (num2 < 65536) { char c2 = ReadChar(ptr2); ptr2++; switch (c2) { case '\u0001': num2 = ReadChar(ptr2); ptr2++; continue; case '\u0002': case '\u0003': case '\u0004': case '\u0005': case '\u0006': case '\a': case '\b': case '\t': case '\n': case '\v': case '\f': case '\r': case '\u000e': case '\u000f': case '\u0010': case '\u0011': case '\u0012': case '\u0013': case '\u0014': case '\u0015': case '\u0016': case '\u0017': case '\u0018': case '\u0019': case '\u001a': case '\u001b': case '\u001c': case '\u001d': case '\u001e': case '\u001f': num2 += c2; continue; } if (c2 != '\ufffd') { int bytes = num2; if (CleanUpBytes(ref bytes) && mapBytesToUnicode[bytes] != c2) { num3++; } } num2++; } char[] array2 = new char[num3 * 2]; num3 = 0; ptr2 = ptr3; num2 = ReadChar(ptr2); ptr2++; bool flag = false; while (num2 < 65536) { char c3 = ReadChar(ptr2); ptr2++; switch (c3) { case '\u0001': num2 = ReadChar(ptr2); ptr2++; continue; case '\u0002': case '\u0003': case '\u0004': case '\u0005': case '\u0006': case '\a': case '\b': case '\t': case '\n': case '\v': case '\f': case '\r': case '\u000e': case '\u000f': case '\u0010': case '\u0011': case '\u0012': case '\u0013': case '\u0014': case '\u0015': case '\u0016': case '\u0017': case '\u0018': case '\u0019': case '\u001a': case '\u001b': case '\u001c': case '\u001d': case '\u001e': case '\u001f': num2 += c3; continue; } if (c3 != '\ufffd') { int bytes2 = num2; if (CleanUpBytes(ref bytes2) && mapBytesToUnicode[bytes2] != c3) { if (bytes2 != num2) { flag = true; } array2[num3++] = (char)bytes2; array2[num3++] = c3; } } num2++; } if (flag) { for (int i = 0; i < array2.Length - 2; i += 2) { int num4 = i; char c4 = array2[i]; for (int j = i + 2; j < array2.Length; j += 2) { if (c4 > array2[j]) { c4 = array2[j]; num4 = j; } } if (num4 != i) { char c5 = array2[num4]; array2[num4] = array2[i]; array2[i] = c5; c5 = array2[num4 + 1]; array2[num4 + 1] = array2[i + 1]; array2[i + 1] = c5; } } } arrayBytesBestFit = array2; char* ptr4 = ptr2; int num5 = ReadChar(ptr2++); num3 = 0; while (num5 < 65536) { char c6 = ReadChar(ptr2); ptr2++; switch (c6) { case '\u0001': num5 = ReadChar(ptr2); ptr2++; continue; case '\u0002': case '\u0003': case '\u0004': case '\u0005': case '\u0006': case '\a': case '\b': case '\t': case '\n': case '\v': case '\f': case '\r': case '\u000e': case '\u000f': case '\u0010': case '\u0011': case '\u0012': case '\u0013': case '\u0014': case '\u0015': case '\u0016': case '\u0017': case '\u0018': case '\u0019': case '\u001a': case '\u001b': case '\u001c': case '\u001d': case '\u001e': case '\u001f': num5 += c6; continue; } if (c6 > '\0') { num3++; } num5++; } array2 = new char[num3 * 2]; ptr2 = ptr4; num5 = ReadChar(ptr2++); num3 = 0; while (num5 < 65536) { char c7 = ReadChar(ptr2); ptr2++; switch (c7) { case '\u0001': num5 = ReadChar(ptr2); ptr2++; continue; case '\u0002': case '\u0003': case '\u0004': case '\u0005': case '\u0006': case '\a': case '\b': case '\t': case '\n': case '\v': case '\f': case '\r': case '\u000e': case '\u000f': case '\u0010': case '\u0011': case '\u0012': case '\u0013': case '\u0014': case '\u0015': case '\u0016': case '\u0017': case '\u0018': case '\u0019': case '\u001a': case '\u001b': case '\u001c': case '\u001d': case '\u001e': case '\u001f': num5 += c7; continue; } if (c7 > '\0') { int bytes3 = c7; if (CleanUpBytes(ref bytes3)) { array2[num3++] = (char)num5; array2[num3++] = mapBytesToUnicode[bytes3]; } } num5++; } arrayUnicodeBestFit = array2; } } } public unsafe override int GetByteCount(char* chars, int count, System.Text.EncoderNLS encoder) { CheckMemorySection(); char c = '\0'; if (encoder != null) { c = encoder.charLeftOver; if (encoder.InternalHasFallbackBuffer && encoder.FallbackBuffer.Remaining > 0) { throw new ArgumentException(System.SR.Format(System.SR.Argument_EncoderFallbackNotEmpty, EncodingName, encoder.Fallback.GetType())); } } int num = 0; char* ptr = chars + count; EncoderFallbackBuffer encoderFallbackBuffer = null; EncoderFallbackBufferHelper encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer); if (c > '\0') { encoderFallbackBuffer = encoder.FallbackBuffer; encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer); encoderFallbackBufferHelper.InternalInitialize(chars, ptr, encoder, _setEncoder: false); encoderFallbackBufferHelper.InternalFallback(c, ref chars); } char c2; while ((c2 = ((encoderFallbackBuffer != null) ? encoderFallbackBufferHelper.InternalGetNextChar() : '\0')) != 0 || chars < ptr) { if (c2 == '\0') { c2 = *chars; chars++; } ushort num2 = mapUnicodeToBytes[(int)c2]; if (num2 == 0 && c2 != 0) { if (encoderFallbackBuffer == null) { encoderFallbackBuffer = ((encoder != null) ? encoder.FallbackBuffer : base.EncoderFallback.CreateFallbackBuffer()); encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer); encoderFallbackBufferHelper.InternalInitialize(ptr - count, ptr, encoder, _setEncoder: false); } encoderFallbackBufferHelper.InternalFallback(c2, ref chars); } else { num++; if (num2 >= 256) { num++; } } } return num; } public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, System.Text.EncoderNLS encoder) { CheckMemorySection(); EncoderFallbackBuffer encoderFallbackBuffer = null; char* ptr = chars + charCount; char* ptr2 = chars; byte* ptr3 = bytes; byte* ptr4 = bytes + byteCount; EncoderFallbackBufferHelper encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer); char c = '\0'; if (encoder != null) { c = encoder.charLeftOver; encoderFallbackBuffer = encoder.FallbackBuffer; encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer); encoderFallbackBufferHelper.InternalInitialize(chars, ptr, encoder, _setEncoder: true); if (encoder.m_throwOnOverflow && encoderFallbackBuffer.Remaining > 0) { throw new ArgumentException(System.SR.Format(System.SR.Argument_EncoderFallbackNotEmpty, EncodingName, encoder.Fallback.GetType())); } if (c > '\0') { encoderFallbackBufferHelper.InternalFallback(c, ref chars); } } char c2; while ((c2 = ((encoderFallbackBuffer != null) ? encoderFallbackBufferHelper.InternalGetNextChar() : '\0')) != 0 || chars < ptr) { if (c2 == '\0') { c2 = *chars; chars++; } ushort num = mapUnicodeToBytes[(int)c2]; if (num == 0 && c2 != 0) { if (encoderFallbackBuffer == null) { encoderFallbackBuffer = base.EncoderFallback.CreateFallbackBuffer(); encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer); encoderFallbackBufferHelper.InternalInitialize(ptr - charCount, ptr, encoder, _setEncoder: true); } encoderFallbackBufferHelper.InternalFallback(c2, ref chars); continue; } if (num >= 256) { if (bytes + 1 >= ptr4) { if (encoderFallbackBuffer == null || !encoderFallbackBufferHelper.bFallingBack) { chars--; } else { encoderFallbackBuffer.MovePrevious(); } ThrowBytesOverflow(encoder, chars == ptr2); break; } *bytes = (byte)(num >> 8); bytes++; } else if (bytes >= ptr4) { if (encoderFallbackBuffer == null || !encoderFallbackBufferHelper.bFallingBack) { chars--; } else { encoderFallbackBuffer.MovePrevious(); } ThrowBytesOverflow(encoder, chars == ptr2); break; } *bytes = (byte)(num & 0xFFu); bytes++; } if (encoder != null) { if (encoderFallbackBuffer != null && !encoderFallbackBufferHelper.bUsedEncoder) { encoder.charLeftOver = '\0'; } encoder.m_charsUsed = (int)(chars - ptr2); } return (int)(bytes - ptr3); } public unsafe override int GetCharCount(byte* bytes, int count, System.Text.DecoderNLS baseDecoder) { CheckMemorySection(); DBCSDecoder dBCSDecoder = (DBCSDecoder)baseDecoder; DecoderFallbackBuffer decoderFallbackBuffer = null; byte* ptr = bytes + count; int num = count; DecoderFallbackBufferHelper decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); if (dBCSDecoder != null && dBCSDecoder.bLeftOver > 0) { if (count == 0) { if (!dBCSDecoder.MustFlush) { return 0; } decoderFallbackBuffer = dBCSDecoder.FallbackBuffer; decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); decoderFallbackBufferHelper.InternalInitialize(bytes, null); byte[] bytes2 = new byte[1] { dBCSDecoder.bLeftOver }; return decoderFallbackBufferHelper.InternalFallback(bytes2, bytes); } int num2 = dBCSDecoder.bLeftOver << 8; num2 |= *bytes; bytes++; if (mapBytesToUnicode[num2] == '\0' && num2 != 0) { num--; decoderFallbackBuffer = dBCSDecoder.FallbackBuffer; decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); decoderFallbackBufferHelper.InternalInitialize(ptr - count, null); byte[] bytes3 = new byte[2] { (byte)(num2 >> 8), (byte)num2 }; num += decoderFallbackBufferHelper.InternalFallback(bytes3, bytes); } } while (bytes < ptr) { int num3 = *bytes; bytes++; char c = mapBytesToUnicode[num3]; if (c == '\ufffe') { num--; if (bytes < ptr) { num3 <<= 8; num3 |= *bytes; bytes++; c = mapBytesToUnicode[num3]; } else { if (dBCSDecoder != null && !dBCSDecoder.MustFlush) { break; } num++; c = '\0'; } } if (c == '\0' && num3 != 0) { if (decoderFallbackBuffer == null) { decoderFallbackBuffer = ((dBCSDecoder != null) ? dBCSDecoder.FallbackBuffer : base.DecoderFallback.CreateFallbackBuffer()); decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); decoderFallbackBufferHelper.InternalInitialize(ptr - count, null); } num--; byte[] bytes4 = ((num3 >= 256) ? new byte[2] { (byte)(num3 >> 8), (byte)num3 } : new byte[1] { (byte)num3 }); num += decoderFallbackBufferHelper.InternalFallback(bytes4, bytes); } } return num; } public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount, System.Text.DecoderNLS baseDecoder) { CheckMemorySection(); DBCSDecoder dBCSDecoder = (DBCSDecoder)baseDecoder; byte* ptr = bytes; byte* ptr2 = bytes + byteCount; char* ptr3 = chars; char* ptr4 = chars + charCount; bool flag = false; DecoderFallbackBuffer decoderFallbackBuffer = null; DecoderFallbackBufferHelper decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); if (dBCSDecoder != null && dBCSDecoder.bLeftOver > 0) { if (byteCount == 0) { if (!dBCSDecoder.MustFlush) { return 0; } decoderFallbackBuffer = dBCSDecoder.FallbackBuffer; decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); decoderFallbackBufferHelper.InternalInitialize(bytes, ptr4); byte[] bytes2 = new byte[1] { dBCSDecoder.bLeftOver }; if (!decoderFallbackBufferHelper.InternalFallback(bytes2, bytes, ref chars)) { ThrowCharsOverflow(dBCSDecoder, nothingDecoded: true); } dBCSDecoder.bLeftOver = 0; return (int)(chars - ptr3); } int num = dBCSDecoder.bLeftOver << 8; num |= *bytes; bytes++; char c = mapBytesToUnicode[num]; if (c == '\0' && num != 0) { decoderFallbackBuffer = dBCSDecoder.FallbackBuffer; decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); decoderFallbackBufferHelper.InternalInitialize(ptr2 - byteCount, ptr4); byte[] bytes3 = new byte[2] { (byte)(num >> 8), (byte)num }; if (!decoderFallbackBufferHelper.InternalFallback(bytes3, bytes, ref chars)) { ThrowCharsOverflow(dBCSDecoder, nothingDecoded: true); } } else { if (chars >= ptr4) { ThrowCharsOverflow(dBCSDecoder, nothingDecoded: true); } *(chars++) = c; } } while (bytes < ptr2) { int num2 = *bytes; bytes++; char c2 = mapBytesToUnicode[num2]; if (c2 == '\ufffe') { if (bytes < ptr2) { num2 <<= 8; num2 |= *bytes; bytes++; c2 = mapBytesToUnicode[num2]; } else { if (dBCSDecoder != null && !dBCSDecoder.MustFlush) { flag = true; dBCSDecoder.bLeftOver = (byte)num2; break; } c2 = '\0'; } } if (c2 == '\0' && num2 != 0) { if (decoderFallbackBuffer == null) { decoderFallbackBuffer = ((dBCSDecoder != null) ? dBCSDecoder.FallbackBuffer : base.DecoderFallback.CreateFallbackBuffer()); decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); decoderFallbackBufferHelper.InternalInitialize(ptr2 - byteCount, ptr4); } byte[] array = ((num2 >= 256) ? new byte[2] { (byte)(num2 >> 8), (byte)num2 } : new byte[1] { (byte)num2 }); if (!decoderFallbackBufferHelper.InternalFallback(array, bytes, ref chars)) { bytes -= array.Length; decoderFallbackBufferHelper.InternalReset(); ThrowCharsOverflow(dBCSDecoder, bytes == ptr); break; } continue; } if (chars >= ptr4) { bytes--; if (num2 >= 256) { bytes--; } ThrowCharsOverflow(dBCSDecoder, bytes == ptr); break; } *(chars++) = c2; } if (dBCSDecoder != null) { if (!flag) { dBCSDecoder.bLeftOver = 0; } dBCSDecoder.m_bytesUsed = (int)(bytes - ptr); } return (int)(chars - ptr3); } public override int GetMaxByteCount(int charCount) { if (charCount < 0) { throw new ArgumentOutOfRangeException("charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } long num = (long)charCount + 1L; if (base.EncoderFallback.MaxCharCount > 1) { num *= base.EncoderFallback.MaxCharCount; } num *= 2; if (num > int.MaxValue) { throw new ArgumentOutOfRangeException("charCount", System.SR.ArgumentOutOfRange_GetByteCountOverflow); } return (int)num; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) { throw new ArgumentOutOfRangeException("byteCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } long num = (long)byteCount + 1L; if (base.DecoderFallback.MaxCharCount > 1) { num *= base.DecoderFallback.MaxCharCount; } if (num > int.MaxValue) { throw new ArgumentOutOfRangeException("byteCount", System.SR.ArgumentOutOfRange_GetCharCountOverflow); } return (int)num; } public override Decoder GetDecoder() { return new DBCSDecoder(this); } } internal sealed class InternalDecoderBestFitFallback : DecoderFallback { internal BaseCodePageEncoding encoding; internal char[] arrayBestFit; internal char cReplacement = '?'; public override int MaxCharCount => 1; internal InternalDecoderBestFitFallback(BaseCodePageEncoding _encoding) { encoding = _encoding; } public override DecoderFallbackBuffer CreateFallbackBuffer() { return new InternalDecoderBestFitFallbackBuffer(this); } public override bool Equals([NotNullWhen(true)] object value) { if (value is InternalDecoderBestFitFallback internalDecoderBestFitFallback) { return encoding.CodePage == internalDecoderBestFitFallback.encoding.CodePage; } return false; } public override int GetHashCode() { return encoding.CodePage; } } internal sealed class InternalDecoderBestFitFallbackBuffer : DecoderFallbackBuffer { internal char cBestFit; internal int iCount = -1; internal int iSize; private readonly InternalDecoderBestFitFallback _oFallback; private static object s_InternalSyncObject; private static object InternalSyncObject { get { if (s_InternalSyncObject == null) { object value = new object(); Interlocked.CompareExchange<object>(ref s_InternalSyncObject, value, (object)null); } return s_InternalSyncObject; } } public override int Remaining { get { if (iCount <= 0) { return 0; } return iCount; } } public InternalDecoderBestFitFallbackBuffer(InternalDecoderBestFitFallback fallback) { _oFallback = fallback; if (_oFallback.arrayBestFit != null) { return; } lock (InternalSyncObject) { InternalDecoderBestFitFallback oFallback = _oFallback; if (oFallback.arrayBestFit == null) { oFallback.arrayBestFit = fallback.encoding.GetBestFitBytesToUnicodeData(); } } } public override bool Fallback(byte[] bytesUnknown, int index) { cBestFit = TryBestFit(bytesUnknown); if (cBestFit == '\0') { cBestFit = _oFallback.cReplacement; } iCount = (iSize = 1); return true; } public override char GetNextChar() { iCount--; if (iCount < 0) { return '\0'; } if (iCount == int.MaxValue) { iCount = -1; return '\0'; } return cBestFit; } public override bool MovePrevious() { if (iCount >= 0) { iCount++; } if (iCount >= 0) { return iCount <= iSize; } return false; } public override void Reset() { iCount = -1; } private char TryBestFit(byte[] bytesCheck) { int num = 0; int num2 = _oFallback.arrayBestFit.Length; if (num2 == 0) { return '\0'; } if (bytesCheck.Length == 0 || bytesCheck.Length > 2) { return '\0'; } char c = ((bytesCheck.Length != 1) ? ((char)((bytesCheck[0] << 8) + bytesCheck[1])) : ((char)bytesCheck[0])); if (c < _oFallback.arrayBestFit[0] || c > _oFallback.arrayBestFit[num2 - 2]) { return '\0'; } int num3; while ((num3 = num2 - num) > 6) { int num4 = (num3 / 2 + num) & 0xFFFE; char c2 = _oFallback.arrayBestFit[num4]; if (c2 == c) { return _oFallback.arrayBestFit[num4 + 1]; } if (c2 < c) { num = num4; } else { num2 = num4; } } for (int num4 = num; num4 < num2; num4 += 2) { if (_oFallback.arrayBestFit[num4] == c) { return _oFallback.arrayBestFit[num4 + 1]; } } return '\0'; } } internal struct DecoderFallbackBufferHelper { internal unsafe byte* byteStart; internal unsafe char* charEnd; private readonly DecoderFallbackBuffer _fallbackBuffer; public unsafe DecoderFallbackBufferHelper(DecoderFallbackBuffer fallbackBuffer) { _fallbackBuffer = fallbackBuffer; byteStart = null; charEnd = null; } internal unsafe void InternalReset() { byteStart = null; _fallbackBuffer.Reset(); } internal unsafe void InternalInitialize(byte* _byteStart, char* _charEnd) { byteStart = _byteStart; charEnd = _charEnd; } internal unsafe bool InternalFallback(byte[] bytes, byte* pBytes, ref char* chars) { if (_fallbackBuffer.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length))) { char* ptr = chars; bool flag = false; char nextChar; while ((nextChar = _fallbackBuffer.GetNextChar()) != 0) { if (char.IsSurrogate(nextChar)) { if (char.IsHighSurrogate(nextChar)) { if (flag) { throw new ArgumentException(System.SR.Argument_InvalidCharSequenceNoIndex); } flag = true; } else { if (!flag) { throw new ArgumentException(System.SR.Argument_InvalidCharSequenceNoIndex); } flag = false; } } if (ptr >= charEnd) { return false; } *(ptr++) = nextChar; } if (flag) { throw new ArgumentException(System.SR.Argument_InvalidCharSequenceNoIndex); } chars = ptr; } return true; } internal unsafe int InternalFallback(byte[] bytes, byte* pBytes) { if (_fallbackBuffer.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length))) { int num = 0; bool flag = false; char nextChar; while ((nextChar = _fallbackBuffer.GetNextChar()) != 0) { if (char.IsSurrogate(nextChar)) { if (char.IsHighSurrogate(nextChar)) { if (flag) { throw new ArgumentException(System.SR.Argument_InvalidCharSequenceNoIndex); } flag = true; } else { if (!flag) { throw new ArgumentException(System.SR.Argument_InvalidCharSequenceNoIndex); } flag = false; } } num++; } if (flag) { throw new ArgumentException(System.SR.Argument_InvalidCharSequenceNoIndex); } return num; } return 0; } } internal class DecoderNLS : Decoder, ISerializable { protected EncodingNLS m_encoding; protected bool m_mustFlush; internal bool m_throwOnOverflow; internal int m_bytesUsed; internal DecoderFallback m_fallback; internal DecoderFallbackBuffer m_fallbackBuffer; internal new DecoderFallback Fallback => m_fallback; internal bool InternalHasFallbackBuffer => m_fallbackBuffer != null; public new DecoderFallbackBuffer FallbackBuffer { get { if (m_fallbackBuffer == null) { m_fallbackBuffer = ((m_fallback != null) ? m_fallback.CreateFallbackBuffer() : DecoderFallback.ReplacementFallback.CreateFallbackBuffer()); } return m_fallbackBuffer; } } public bool MustFlush => m_mustFlush; internal virtual bool HasState => false; internal DecoderNLS(EncodingNLS encoding) { m_encoding = encoding; m_fallback = m_encoding.DecoderFallback; Reset(); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } public override void Reset() { m_fallbackBuffer?.Reset(); } public override int GetCharCount(byte[] bytes, int index, int count) { return GetCharCount(bytes, index, count, flush: false); } public unsafe override int GetCharCount(byte[] bytes, int index, int count, bool flush) { if (bytes == null) { throw new ArgumentNullException("bytes"); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - index < count) { throw new ArgumentOutOfRangeException("bytes", System.SR.ArgumentOutOfRange_IndexCountBuffer); } fixed (byte* ptr = &CodePagesEncodingProvider.GetNonNullPinnableReference(bytes)) { return GetCharCount(ptr + index, count, flush); } } public unsafe override int GetCharCount(byte* bytes, int count, bool flush) { if (bytes == null) { throw new ArgumentNullException("bytes"); } if (count < 0) { throw new ArgumentOutOfRangeException("count", System.SR.ArgumentOutOfRange_NeedNonNegNum); } m_mustFlush = flush; m_throwOnOverflow = true; return m_encoding.GetCharCount(bytes, count, this); } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { return GetChars(bytes, byteIndex, byteCount, chars, charIndex, flush: false); } public unsafe override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush) { if (bytes == null) { throw new ArgumentNullException("bytes"); } if (chars == null) { throw new ArgumentNullException("chars"); } if (byteIndex < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException((byteIndex < 0) ? "byteIndex" : "byteCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - byteIndex < byteCount) { throw new ArgumentOutOfRangeException("bytes", System.SR.ArgumentOutOfRange_IndexCountBuffer); } if (charIndex < 0 || charIndex > chars.Length) { throw new ArgumentOutOfRangeException("charIndex", System.SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); } int charCount = chars.Length - charIndex; fixed (byte* ptr = &CodePagesEncodingProvider.GetNonNullPinnableReference(bytes)) { fixed (char* ptr2 = &CodePagesEncodingProvider.GetNonNullPinnableReference(chars)) { return GetChars(ptr + byteIndex, byteCount, ptr2 + charIndex, charCount, flush); } } } public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush) { if (bytes == null) { throw new ArgumentNullException("bytes"); } if (chars == null) { throw new ArgumentNullException("chars"); } if (byteCount < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((byteCount < 0) ? "byteCount" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } m_mustFlush = flush; m_throwOnOverflow = true; return m_encoding.GetChars(bytes, byteCount, chars, charCount, this); } public unsafe override void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { if (bytes == null) { throw new ArgumentNullException("bytes"); } if (chars == null) { throw new ArgumentNullException("chars"); } if (byteIndex < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException((byteIndex < 0) ? "byteIndex" : "byteCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (charIndex < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - byteIndex < byteCount) { throw new ArgumentOutOfRangeException("bytes", System.SR.ArgumentOutOfRange_IndexCountBuffer); } if (chars.Length - charIndex < charCount) { throw new ArgumentOutOfRangeException("chars", System.SR.ArgumentOutOfRange_IndexCountBuffer); } fixed (byte* ptr = &CodePagesEncodingProvider.GetNonNullPinnableReference(bytes)) { fixed (char* ptr2 = &CodePagesEncodingProvider.GetNonNullPinnableReference(chars)) { Convert(ptr + byteIndex, byteCount, ptr2 + charIndex, charCount, flush, out bytesUsed, out charsUsed, out completed); } } } public unsafe override void Convert(byte* bytes, int byteCount, char* chars, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { if (bytes == null) { throw new ArgumentNullException("bytes"); } if (chars == null) { throw new ArgumentNullException("chars"); } if (byteCount < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((byteCount < 0) ? "byteCount" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } m_mustFlush = flush; m_throwOnOverflow = false; m_bytesUsed = 0; charsUsed = m_encoding.GetChars(bytes, byteCount, chars, charCount, this); bytesUsed = m_bytesUsed; completed = bytesUsed == byteCount && (!flush || !HasState) && (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0); } internal void ClearMustFlush() { m_mustFlush = false; } } internal sealed class InternalEncoderBestFitFallback : EncoderFallback { internal BaseCodePageEncoding encoding; internal char[] arrayBestFit; public override int MaxCharCount => 1; internal InternalEncoderBestFitFallback(BaseCodePageEncoding _encoding) { encoding = _encoding; } public override EncoderFallbackBuffer CreateFallbackBuffer() { return new InternalEncoderBestFitFallbackBuffer(this); } public override bool Equals([NotNullWhen(true)] object value) { if (value is InternalEncoderBestFitFallback internalEncoderBestFitFallback) { return encoding.CodePage == internalEncoderBestFitFallback.encoding.CodePage; } return false; } public override int GetHashCode() { return encoding.CodePage; } } internal sealed class InternalEncoderBestFitFallbackBuffer : EncoderFallbackBuffer { private char _cBestFit; private readonly InternalEncoderBestFitFallback _oFallback; private int _iCount = -1; private int _iSize; private static object s_InternalSyncObject; private static object InternalSyncObject { get { if (s_InternalSyncObject == null) { object value = new object(); Interlocked.CompareExchange<object>(ref s_InternalSyncObject, value, (object)null); } return s_InternalSyncObject; } } public override int Remaining { get { if (_iCount <= 0) { return 0; } return _iCount; } } public InternalEncoderBestFitFallbackBuffer(InternalEncoderBestFitFallback fallback) { _oFallback = fallback; if (_oFallback.arrayBestFit != null) { return; } lock (InternalSyncObject) { InternalEncoderBestFitFallback oFallback = _oFallback; if (oFallback.arrayBestFit == null) { oFallback.arrayBestFit = fallback.encoding.GetBestFitUnicodeToBytesData(); } } } public override bool Fallback(char charUnknown, int index) { _iCount = (_iSize = 1); _cBestFit = TryBestFit(charUnknown); if (_cBestFit == '\0') { _cBestFit = '?'; } return true; } public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index) { if (!char.IsHighSurrogate(charUnknownHigh)) { throw new ArgumentOutOfRangeException("charUnknownHigh", System.SR.Format(System.SR.ArgumentOutOfRange_Range, 55296, 56319)); } if (!char.IsLowSurrogate(charUnknownLow)) { throw new ArgumentOutOfRangeException("charUnknownLow", System.SR.Format(System.SR.ArgumentOutOfRange_Range, 56320, 57343)); } _cBestFit = '?'; _iCount = (_iSize = 2); return true; } public override char GetNextChar() { _iCount--; if (_iCount < 0) { return '\0'; } if (_iCount == int.MaxValue) { _iCount = -1; return '\0'; } return _cBestFit; } public override bool MovePrevious() { if (_iCount >= 0) { _iCount++; } if (_iCount >= 0) { return _iCount <= _iSize; } return false; } public override void Reset() { _iCount = -1; } private char TryBestFit(char cUnknown) { int num = 0; int num2 = _oFallback.arrayBestFit.Length; int num3; while ((num3 = num2 - num) > 6) { int num4 = (num3 / 2 + num) & 0xFFFE; char c = _oFallback.arrayBestFit[num4]; if (c == cUnknown) { return _oFallback.arrayBestFit[num4 + 1]; } if (c < cUnknown) { num = num4; } else { num2 = num4; } } for (int num4 = num; num4 < num2; num4 += 2) { if (_oFallback.arrayBestFit[num4] == cUnknown) { return _oFallback.arrayBestFit[num4 + 1]; } } return '\0'; } } internal struct EncoderFallbackBufferHelper { internal unsafe char* charStart; internal unsafe char* charEnd; internal System.Text.EncoderNLS encoder; internal bool setEncoder; internal bool bUsedEncoder; internal bool bFallingBack; internal int iRecursionCount; private const int iMaxRecursion = 250; private readonly EncoderFallbackBuffer _fallbackBuffer; public unsafe EncoderFallbackBufferHelper(EncoderFallbackBuffer fallbackBuffer) { _fallbackBuffer = fallbackBuffer; bFallingBack = (bUsedEncoder = (setEncoder = false)); iRecursionCount = 0; charEnd = (charStart = null); encoder = null; } internal unsafe void InternalReset() { charStart = null; bFallingBack = false; iRecursionCount = 0; _fallbackBuffer.Reset(); } internal unsafe void InternalInitialize(char* _charStart, char* _charEnd, System.Text.EncoderNLS _encoder, bool _setEncoder) { charStart = _charStart; charEnd = _charEnd; encoder = _encoder; setEncoder = _setEncoder; bUsedEncoder = false; bFallingBack = false; iRecursionCount = 0; } internal char InternalGetNextChar() { char nextChar = _fallbackBuffer.GetNextChar(); bFallingBack = nextChar != '\0'; if (nextChar == '\0') { iRecursionCount = 0; } return nextChar; } internal unsafe bool InternalFallback(char ch, ref char* chars) { int index = (int)(chars - charStart) - 1; if (char.IsHighSurrogate(ch)) { if (chars >= charEnd) { if (encoder != null && !encoder.MustFlush) { if (setEncoder) { bUsedEncoder = true; encoder.charLeftOver = ch; } bFallingBack = false; return false; } } else { char c = *chars; if (char.IsLowSurrogate(c)) { if (bFallingBack && iRecursionCount++ > 250) { ThrowLastCharRecursive(char.ConvertToUtf32(ch, c)); } chars++; bFallingBack = _fallbackBuffer.Fallback(ch, c, index); return bFallingBack; } } } if (bFallingBack && iRecursionCount++ > 250) { ThrowLastCharRecursive(ch); } bFallingBack = _fallbackBuffer.Fallback(ch, index); return bFallingBack; } internal static void ThrowLastCharRecursive(int charRecursive) { throw new ArgumentException(System.SR.Format(System.SR.Argument_RecursiveFallback, charRecursive), "chars"); } } internal class EncoderNLS : Encoder, ISerializable { internal char charLeftOver; protected EncodingNLS m_encoding; protected bool m_mustFlush; internal bool m_throwOnOverflow; internal int m_charsUsed; internal EncoderFallback m_fallback; internal EncoderFallbackBuffer m_fallbackBuffer; internal new EncoderFallback Fallback => m_fallback; internal bool InternalHasFallbackBuffer => m_fallbackBuffer != null; public new EncoderFallbackBuffer FallbackBuffer { get { if (m_fallbackBuffer == null) { m_fallbackBuffer = ((m_fallback != null) ? m_fallback.CreateFallbackBuffer() : EncoderFallback.ReplacementFallback.CreateFallbackBuffer()); } return m_fallbackBuffer; } } public Encoding Encoding => m_encoding; public bool MustFlush => m_mustFlush; internal virtual bool HasState => charLeftOver != '\0'; internal EncoderNLS(EncodingNLS encoding) { m_encoding = encoding; m_fallback = m_encoding.EncoderFallback; Reset(); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } public override void Reset() { charLeftOver = '\0'; m_fallbackBuffer?.Reset(); } public unsafe override int GetByteCount(char[] chars, int index, int count, bool flush) { if (chars == null) { throw new ArgumentNullException("chars"); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (chars.Length - index < count) { throw new ArgumentOutOfRangeException("chars", System.SR.ArgumentOutOfRange_IndexCountBuffer); } fixed (char* ptr = &CodePagesEncodingProvider.GetNonNullPinnableReference(chars)) { return GetByteCount(ptr + index, count, flush); } } public unsafe override int GetByteCount(char* chars, int count, bool flush) { if (chars == null) { throw new ArgumentNullException("chars"); } if (count < 0) { throw new ArgumentOutOfRangeException("count", System.SR.ArgumentOutOfRange_NeedNonNegNum); } m_mustFlush = flush; m_throwOnOverflow = true; return m_encoding.GetByteCount(chars, count, this); } public unsafe override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush) { if (chars == null) { throw new ArgumentNullException("chars"); } if (bytes == null) { throw new ArgumentNullException("bytes"); } if (charIndex < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (chars.Length - charIndex < charCount) { throw new ArgumentOutOfRangeException("chars", System.SR.ArgumentOutOfRange_IndexCountBuffer); } if (byteIndex < 0 || byteIndex > bytes.Length) { throw new ArgumentOutOfRangeException("byteIndex", System.SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); } int byteCount = bytes.Length - byteIndex; fixed (char* ptr = &CodePagesEncodingProvider.GetNonNullPinnableReference(chars)) { fixed (byte* ptr2 = &CodePagesEncodingProvider.GetNonNullPinnableReference(bytes)) { return GetBytes(ptr + charIndex, charCount, ptr2 + byteIndex, byteCount, flush); } } } public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush) { if (chars == null) { throw new ArgumentNullException("chars"); } if (bytes == null) { throw new ArgumentNullException("bytes"); } if (byteCount < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((byteCount < 0) ? "byteCount" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } m_mustFlush = flush; m_throwOnOverflow = true; return m_encoding.GetBytes(chars, charCount, bytes, byteCount, this); } public unsafe override void Convert(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { if (chars == null) { throw new ArgumentNullException("chars"); } if (bytes == null) { throw new ArgumentNullException("bytes"); } if (charIndex < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (byteIndex < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException((byteIndex < 0) ? "byteIndex" : "byteCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (chars.Length - charIndex < charCount) { throw new ArgumentOutOfRangeException("chars", System.SR.ArgumentOutOfRange_IndexCountBuffer); } if (bytes.Length - byteIndex < byteCount) { throw new ArgumentOutOfRangeException("bytes", System.SR.ArgumentOutOfRange_IndexCountBuffer); } fixed (char* ptr = &CodePagesEncodingProvider.GetNonNullPinnableReference(chars)) { fixed (byte* ptr2 = &CodePagesEncodingProvider.GetNonNullPinnableReference(bytes)) { Convert(ptr + charIndex, charCount, ptr2 + byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out completed); } } } public unsafe override void Convert(char* chars, int charCount, byte* bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { if (chars == null) { throw new ArgumentNullException("chars"); } if (bytes == null) { throw new ArgumentNullException("bytes"); } if (charCount < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException((charCount < 0) ? "charCount" : "byteCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } m_mustFlush = flush; m_throwOnOverflow = false; m_charsUsed = 0; bytesUsed = m_encoding.GetBytes(chars, charCount, bytes, byteCount, this); charsUsed = m_charsUsed; completed = charsUsed == charCount && (!flush || !HasState) && (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0); } internal void ClearMustFlush() { m_mustFlush = false; } } internal sealed class EncodingByteBuffer { private unsafe byte* _bytes; private unsafe readonly byte* _byteStart; private unsafe readonly byte* _byteEnd; private unsafe char* _chars; private unsafe readonly char* _charStart; private unsafe readonly char* _charEnd; private int _byteCountResult; private readonly EncodingNLS _enc; private readonly System.Text.EncoderNLS _encoder; internal EncoderFallbackBuffer fallbackBuffer; internal EncoderFallbackBufferHelper fallbackBufferHelper; internal unsafe bool MoreData { get { if (fallbackBuffer.Remaining <= 0) { return _chars < _charEnd; } return true; } } internal unsafe int CharsUsed => (int)(_chars - _charStart); internal int Count => _byteCountResult; internal unsafe EncodingByteBuffer(EncodingNLS inEncoding, System.Text.EncoderNLS inEncoder, byte* inByteStart, int inByteCount, char* inCharStart, int inCharCount) { _enc = inEncoding; _encoder = inEncoder; _charStart = inCharStart; _chars = inCharStart; _charEnd = inCharStart + inCharCount; _bytes = inByteStart; _byteStart = inByteStart; _byteEnd = inByteStart + inByteCount; if (_encoder == null) { fallbackBuffer = _enc.EncoderFallback.CreateFallbackBuffer(); } else { fallbackBuffer = _encoder.FallbackBuffer; if (_encoder.m_throwOnOverflow && _encoder.InternalHasFallbackBuffer && fallbackBuffer.Remaining > 0) { throw new ArgumentException(System.SR.Format(System.SR.Argument_EncoderFallbackNotEmpty, _encoder.Encoding.EncodingName, _encoder.Fallback.GetType())); } } fallbackBufferHelper = new EncoderFallbackBufferHelper(fallbackBuffer); fallbackBufferHelper.InternalInitialize(_chars, _charEnd, _encoder, _bytes != null); } internal unsafe bool AddByte(byte b, int moreBytesExpected) { if (_bytes != null) { if (_bytes >= _byteEnd - moreBytesExpected) { MovePrevious(bThrow: true); return false; } *(_bytes++) = b; } _byteCountResult++; return true; } internal bool AddByte(byte b1) { return AddByte(b1, 0); } internal bool AddByte(byte b1, byte b2) { return AddByte(b1, b2, 0); } internal bool AddByte(byte b1, byte b2, int moreBytesExpected) { if (AddByte(b1, 1 + moreBytesExpected)) { return AddByte(b2, moreBytesExpected); } return false; } internal bool AddByte(byte b1, byte b2, byte b3) { return AddByte(b1, b2, b3, 0); } internal bool AddByte(byte b1, byte b2, byte b3, int moreBytesExpected) { if (AddByte(b1, 2 + moreBytesExpected) && AddByte(b2, 1 + moreBytesExpected)) { return AddByte(b3, moreBytesExpected); } return false; } internal bool AddByte(byte b1, byte b2, byte b3, byte b4) { if (AddByte(b1, 3) && AddByte(b2, 2) && AddByte(b3, 1)) { return AddByte(b4, 0); } return false; } internal unsafe void MovePrevious(bool bThrow) { if (fallbackBufferHelper.bFallingBack) { fallbackBuffer.MovePrevious(); } else if (_chars > _charStart) { _chars--; } if (bThrow) { _enc.ThrowBytesOverflow(_encoder, _bytes == _byteStart); } } internal unsafe bool Fallback(char charFallback) { return fallbackBufferHelper.InternalFallback(charFallback, ref _chars); } internal unsafe char GetNextChar() { char c = fallbackBufferHelper.InternalGetNextChar(); if (c == '\0' && _chars < _charEnd) { c = *(_chars++); } return c; } } internal sealed class EncodingCharBuffer { private unsafe char* _chars; private unsafe readonly char* _charStart; private unsafe readonly char* _charEnd; private int _charCountResult; private readonly EncodingNLS _enc; private readonly System.Text.DecoderNLS _decoder; private unsafe readonly byte* _byteStart; private unsafe readonly byte* _byteEnd; private unsafe byte* _bytes; private readonly DecoderFallbackBuffer _fallbackBuffer; private DecoderFallbackBufferHelper _fallbackBufferHelper; internal unsafe bool MoreData => _bytes < _byteEnd; internal unsafe int BytesUsed => (int)(_bytes - _byteStart); internal int Count => _charCountResult; internal unsafe EncodingCharBuffer(EncodingNLS enc, System.Text.DecoderNLS decoder, char* charStart, int charCount, byte* byteStart, int byteCount) { _enc = enc; _decoder = decoder; _chars = charStart; _charStart = charStart; _charEnd = charStart + charCount; _byteStart = byteStart; _bytes = byteStart; _byteEnd = byteStart + byteCount; if (_decoder == null) { _fallbackBuffer = enc.DecoderFallback.CreateFallbackBuffer(); } else { _fallbackBuffer = _decoder.FallbackBuffer; } _fallbackBufferHelper = new DecoderFallbackBufferHelper(_fallbackBuffer); _fallbackBufferHelper.InternalInitialize(_bytes, _charEnd); } internal unsafe bool AddChar(char ch, int numBytes) { if (_chars != null) { if (_chars >= _charEnd) { _bytes -= numBytes; _enc.ThrowCharsOverflow(_decoder, _bytes <= _byteStart); return false; } *(_chars++) = ch; } _charCountResult++; return true; } internal bool AddChar(char ch) { return AddChar(ch, 1); } internal unsafe bool AddChar(char ch1, char ch2, int numBytes) { if (_chars >= _charEnd - 1) { _bytes -= numBytes; _enc.ThrowCharsOverflow(_decoder, _bytes <= _byteStart); return false; } if (AddChar(ch1, numBytes)) { return AddChar(ch2, numBytes); } return false; } internal unsafe void AdjustBytes(int count) { _bytes += count; } internal unsafe bool EvenMoreData(int count) { return _bytes <= _byteEnd - count; } internal unsafe byte GetNextByte() { if (_bytes >= _byteEnd) { return 0; } return *(_bytes++); } internal bool Fallback(byte fallbackByte) { byte[] byteBuffer = new byte[1] { fallbackByte }; return Fallback(byteBuffer); } internal bool Fallback(byte byte1, byte byte2) { byte[] byteBuffer = new byte[2] { byte1, byte2 }; return Fallback(byteBuffer); } internal bool Fallback(byte byte1, byte byte2, byte byte3, byte byte4) { byte[] byteBuffer = new byte[4] { byte1, byte2, byte3, byte4 }; return Fallback(byteBuffer); } internal unsafe bool Fallback(byte[] byteBuffer) { if (_chars != null) { char* chars = _chars; if (!_fallbackBufferHelper.InternalFallback(byteBuffer, _bytes, ref _chars)) { _bytes -= byteBuffer.Length; _fallbackBufferHelper.InternalReset(); _enc.ThrowCharsOverflow(_decoder, _chars == _charStart); return false; } _charCountResult += (int)(_chars - chars); } else { _charCountResult += _fallbackBufferHelper.InternalFallback(byteBuffer, _bytes); } return true; } } internal abstract class EncodingNLS : Encoding { private string _encodingName; private string _webName; public override string EncodingName { get { if (_encodingName == null) { _encodingName = GetLocalizedEncodingNameResource(CodePage); if (_encodingName == null) { throw new NotSupportedException(System.SR.Format(System.SR.MissingEncodingNameResource, WebName, CodePage)); } if (_encodingName.StartsWith("Globalization_cp_", StringComparison.OrdinalIgnoreCase)) { _encodingName = System.Text.EncodingTable.GetEnglishNameFromCodePage(CodePage); if (_encodingName == null) { throw new NotSupportedException(System.SR.Format(System.SR.MissingEncodingNameResource, WebName, CodePage)); } } } return _encodingName; } } public override string WebName { get { if (_webName == null) { _webName = System.Text.EncodingTable.GetWebNameFromCodePage(CodePage); if (_webName == null) { throw new NotSupportedException(System.SR.Format(System.SR.NotSupported_NoCodepageData, CodePage)); } } return _webName; } } public override string HeaderName => CodePage switch { 932 => "iso-2022-jp", 50221 => "iso-2022-jp", 50225 => "euc-kr", _ => WebName, }; public override string BodyName => CodePage switch { 932 => "iso-2022-jp", 1250 => "iso-8859-2", 1251 => "koi8-r", 1252 => "iso-8859-1", 1253 => "iso-8859-7", 1254 => "iso-8859-9", 50221 => "iso-2022-jp", 50225 => "iso-2022-kr", _ => WebName, }; protected EncodingNLS(int codePage) : base(codePage) { } protected EncodingNLS(int codePage, EncoderFallback enc, DecoderFallback dec) : base(codePage, enc, dec) { } public unsafe abstract int GetByteCount(char* chars, int count, System.Text.EncoderNLS encoder); public unsafe abstract int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, System.Text.EncoderNLS encoder); public unsafe abstract int GetCharCount(byte* bytes, int count, System.Text.DecoderNLS decoder); public unsafe abstract int GetChars(byte* bytes, int byteCount, char* chars, int charCount, System.Text.DecoderNLS decoder); public unsafe override int GetByteCount(char[] chars, int index, int count) { if (chars == null) { throw new ArgumentNullException("chars"); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (chars.Length - index < count) { throw new ArgumentOutOfRangeException("chars", System.SR.ArgumentOutOfRange_IndexCountBuffer); } if (chars.Length == 0) { return 0; } fixed (char* ptr = &chars[0]) { return GetByteCount(ptr + index, count, null); } } public unsafe override int GetByteCount(string s) { if (s == null) { throw new ArgumentNullException("s"); } fixed (char* chars = s) { return GetByteCount(chars, s.Length, null); } } public unsafe override int GetByteCount(char* chars, int count) { if (chars == null) { throw new ArgumentNullException("chars"); } if (count < 0) { throw new ArgumentOutOfRangeException("count", System.SR.ArgumentOutOfRange_NeedNonNegNum); } return GetByteCount(chars, count, null); } public unsafe override int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (s == null) { throw new ArgumentNullException("s"); } if (bytes == null) { throw new ArgumentNullException("bytes"); } if (charIndex < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (s.Length - charIndex < charCount) { throw new ArgumentOutOfRangeException("s", System.SR.ArgumentOutOfRange_IndexCount); } if (byteIndex < 0 || byteIndex > bytes.Length) { throw new ArgumentOutOfRangeException("byteIndex", System.SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); } int byteCount = bytes.Length - byteIndex; fixed (char* ptr = s) { fixed (byte* ptr2 = &CodePagesEncodingProvider.GetNonNullPinnableReference(bytes)) { return GetBytes(ptr + charIndex, charCount, ptr2 + byteIndex, byteCount, null); } } } public unsafe override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (chars == null) { throw new ArgumentNullException("chars"); } if (bytes == null) { throw new ArgumentNullException("bytes"); } if (charIndex < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (chars.Length - charIndex < charCount) { throw new ArgumentOutOfRangeException("chars", System.SR.ArgumentOutOfRange_IndexCountBuffer); } if (byteIndex < 0 || byteIndex > bytes.Length) { throw new ArgumentOutOfRangeException("byteIndex", System.SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); } if (chars.Length == 0) { return 0; } int byteCount = bytes.Length - byteIndex; fixed (char* ptr = &chars[0]) { fixed (byte* ptr2 = &CodePagesEncodingProvider.GetNonNullPinnableReference(bytes)) { return GetBytes(