Decompiled source of Enhanced Prefab Loader v2.0.0
BepInEx/patchers/EnhancedPrefabLoaderPrepatch.dll
Decompiled 3 months agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using EnhancedPrefabLoaderPrepatch.Extensions; using EnhancedPrefabLoaderPrepatch.Models; using Microsoft.CodeAnalysis; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Cecil.Rocks; using MonoMod.Cil; using Newtonsoft.Json; using Scripts; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")] [assembly: AssemblyCompany("EnhancedPrefabLoaderPrepatch")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("2.0.0.0")] [assembly: AssemblyInformationalVersion("2.0.0+40cdc7df25d66bcd28939d889a9240738f060bdd")] [assembly: AssemblyProduct("Enhanced Prefab Loader Prepatch")] [assembly: AssemblyTitle("EnhancedPrefabLoaderPrepatch")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("2.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace EnhancedPrefabLoaderPrepatch { public class BidirectionalDictionary<k, v> { private Dictionary<v, k> m_InverseDictionary = new Dictionary<v, k>(); public v this[k key] { get { return Dictionary[key]; } set { Dictionary[key] = value; m_InverseDictionary[value] = key; } } public Dictionary<k, v> Dictionary { get; } = new Dictionary<k, v>(); public bool TryGetValue(k key, out v value) { return Dictionary.TryGetValue(key, out value); } public bool TryGetKey(v value, out k key) { return m_InverseDictionary.TryGetValue(value, out key); } public void Clear() { Dictionary.Clear(); m_InverseDictionary.Clear(); } public void AddAll(IEnumerable<KeyValuePair<k, v>> items) { foreach (KeyValuePair<k, v> item in items) { this[item.Key] = item.Value; } } } public static class EnumPatcher { public static BidirectionalDictionary<string, int> PatchEnum(AssemblyDefinition assembly, string enumName, List<string> names, int startingValue, BidirectionalDictionary<string, int> savedValues = null) { //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Expected O, but got Unknown //IL_0135: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Expected O, but got Unknown BidirectionalDictionary<string, int> bidirectionalDictionary = new BidirectionalDictionary<string, int>(); TypeDefinition val = ((IEnumerable<TypeDefinition>)assembly.MainModule.Types).FirstOrDefault((Func<TypeDefinition, bool>)((TypeDefinition t) => ((MemberReference)t).Name == enumName)); if (val != null) { FieldDefinition val2 = ((IEnumerable<FieldDefinition>)val.Fields).FirstOrDefault((Func<FieldDefinition, bool>)((FieldDefinition f) => f.HasConstant && f.IsStatic && f.IsLiteral)); if (val2 != null) { SortedDictionary<int, FieldDefinition> sortedDictionary = new SortedDictionary<int, FieldDefinition>(); if (savedValues != null) { foreach (KeyValuePair<string, int> item in savedValues.Dictionary) { if (names.Contains(item.Key)) { sortedDictionary[item.Value] = new FieldDefinition(item.Key, val2.Attributes, (TypeReference)(object)val) { Constant = item.Value }; bidirectionalDictionary[item.Key] = item.Value; names.Remove(item.Key); } } } foreach (string name in names) { while (sortedDictionary.ContainsKey(startingValue)) { startingValue++; } sortedDictionary[startingValue] = new FieldDefinition(name, val2.Attributes, (TypeReference)(object)val) { Constant = startingValue }; bidirectionalDictionary[name] = startingValue; startingValue++; } { foreach (KeyValuePair<int, FieldDefinition> item2 in sortedDictionary) { val.Fields.Add(item2.Value); } return bidirectionalDictionary; } } } return bidirectionalDictionary; } } public enum CallType { Get, Set, Count, None } public class ListPatcher { private static ListPatcher m_Instance; public static ListPatcher Instance => m_Instance ?? (m_Instance = new ListPatcher()); private ListPatcher() { } public void PatchListAccessors(ModuleDefinition module) { foreach (TypeDefinition allType in ModuleDefinitionRocks.GetAllTypes(module)) { foreach (MethodDefinition item in ((IEnumerable<MethodDefinition>)allType.Methods).Where((MethodDefinition m) => m.HasBody)) { Logger.Debug("Processing method: " + ((MemberReference)item).FullName); ProcessMethod(item); } } } private void ProcessMethod(MethodDefinition method) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected O, but got Unknown MethodBodyRocks.SimplifyMacros(method.Body); ILContext val = new ILContext(method); try { ILCursor val2 = new ILCursor(val); MethodVariablePool methodVariablePool = new MethodVariablePool(method); MethodReference accessorCall = null; while (val2.TryGotoNext((MoveType)0, new Func<Instruction, bool>[2] { (Instruction instr) => ILPatternMatchingExt.MatchCallOrCallvirt(instr, ref accessorCall), (Instruction _) => accessorCall?.IsListAccessor() ?? false })) { Logger.Debug($"Found list indexer call at {val2.Next}"); MethodReference obj = accessorCall; TypeReference obj2 = ((obj != null) ? ((MemberReference)obj).DeclaringType : null); GenericInstanceType val3 = (GenericInstanceType)(object)((obj2 is GenericInstanceType) ? obj2 : null); if (val3 == null) { Logger.Debug($"Skipping indexer call at {val2.Next}. Declaring type is non-generic."); continue; } TypeReference val4 = val3.GenericArguments[0]; CallType callType = GetCallType(accessorCall); if (DiscoverDeclaredListName(val2, val4, out var listName)) { PatchListAccess(val2, accessorCall, val4, callType, listName, methodVariablePool); } } Logger.Debug("Method " + ((MemberReference)val2.Method).FullName + " completed"); MethodBodyRocks.OptimizeMacros(method.Body); } finally { ((IDisposable)val)?.Dispose(); } } private void PatchListAccess(ILCursor cursor, MethodReference accessorCall, TypeReference itemType, CallType callType, string listName, MethodVariablePool methodVariablePool) { //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Unknown result type (might be due to invalid IL or missing references) //IL_0139: Unknown result type (might be due to invalid IL or missing references) //IL_0159: Unknown result type (might be due to invalid IL or missing references) //IL_017d: Unknown result type (might be due to invalid IL or missing references) //IL_01a0: Unknown result type (might be due to invalid IL or missing references) //IL_01d6: Unknown result type (might be due to invalid IL or missing references) //IL_01ee: Unknown result type (might be due to invalid IL or missing references) //IL_01bd: Unknown result type (might be due to invalid IL or missing references) GenericInstanceType val = TypeReferenceRocks.MakeGenericInstanceType(cursor.Module.ImportReference(typeof(ListInterceptor<>)), (TypeReference[])(object)new TypeReference[1] { itemType }); string interceptorMethodName = GetInterceptorMethodName(callType); MethodDefinition val2 = ((IEnumerable<MethodDefinition>)((TypeReference)val).Resolve().Methods).First((MethodDefinition m) => ((MemberReference)m).Name == interceptorMethodName); MethodReference val3 = cursor.Module.ImportReference((MethodReference)(object)val2); ((MemberReference)val3).DeclaringType = (TypeReference)(object)val; IEnumerable<Instruction> enumerable = ((IEnumerable<Instruction>)cursor.Method.Body.Instructions).Where((Instruction instr) => instr.Operand == cursor.Next); Instruction operand = null; switch (callType) { case CallType.Get: operand = cursor.Emit(OpCodes.Stloc, methodVariablePool.GetIndexVariable()).Previous; cursor.Emit(OpCodes.Stloc, methodVariablePool.GetListVariable(((MemberReference)accessorCall).DeclaringType)); break; case CallType.Set: operand = cursor.Emit(OpCodes.Stloc, methodVariablePool.GetItemVariable(itemType)).Previous; cursor.Emit(OpCodes.Stloc, methodVariablePool.GetIndexVariable()); cursor.Emit(OpCodes.Stloc, methodVariablePool.GetListVariable(((MemberReference)accessorCall).DeclaringType)); break; case CallType.Count: operand = cursor.Emit(OpCodes.Stloc, methodVariablePool.GetListVariable(((MemberReference)accessorCall).DeclaringType)).Previous; break; } cursor.Emit(OpCodes.Ldloc, methodVariablePool.GetListVariable(((MemberReference)accessorCall).DeclaringType)); if (callType != CallType.Count) { cursor.Emit(OpCodes.Ldloc, methodVariablePool.GetIndexVariable()); } if (callType == CallType.Set) { cursor.Emit(OpCodes.Ldloc, methodVariablePool.GetItemVariable(itemType)); } cursor.Emit(OpCodes.Ldstr, listName); cursor.Next.OpCode = OpCodes.Call; cursor.Next.Operand = val3; foreach (Instruction item in enumerable) { item.Operand = operand; } Logger.Debug("Patch complete"); } private bool DiscoverDeclaredListName(ILCursor cursor, TypeReference elementType, out string listName) { //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) ILCursor walkBackCursor = cursor.Clone(); TypeReference matchedElementType = null; if (walkBackCursor.TryGotoPrev((MoveType)0, new Func<Instruction, bool>[2] { (Instruction instr) => instr.MatchListLoad(walkBackCursor.Method.Body, out matchedElementType), (Instruction _) => matchedElementType == elementType })) { if (walkBackCursor.Next.OpCode.IsFieldLoad()) { object operand = walkBackCursor.Next.Operand; object obj = ((operand is FieldReference) ? operand : null); listName = ((obj != null) ? ((MemberReference)obj).Name : null); return true; } if (walkBackCursor.Next.OpCode.IsLdloc()) { Instruction instructionToCheck = walkBackCursor.Next; if (walkBackCursor.TryGotoPrev((MoveType)0, new Func<Instruction, bool>[1] { (Instruction instr) => instr.IsComplimentaryStOf(instructionToCheck) })) { if (walkBackCursor.Previous.OpCode.IsFieldLoad()) { object operand2 = walkBackCursor.Previous.Operand; object obj2 = ((operand2 is FieldReference) ? operand2 : null); listName = ((obj2 != null) ? ((MemberReference)obj2).Name : null); return true; } return DiscoverDeclaredListName(walkBackCursor, elementType, out listName); } } } listName = "SkippedName"; return false; } private string GetInterceptorMethodName(CallType callType) { return callType switch { CallType.Count => "InvokeCount", CallType.Get => "InvokeGet", CallType.Set => "InvokeSet", _ => throw new ArgumentOutOfRangeException(), }; } private CallType GetCallType(MethodReference methodRef) { if (methodRef.IsListGetCountCall()) { return CallType.Count; } if (methodRef.IsListGetItemCall()) { return CallType.Get; } if (methodRef.IsListSetItemCall()) { return CallType.Set; } return CallType.None; } } public enum LogLevel { Debug, Info, Warning, Error, None } public static class Logger { private static readonly object _lock = new object(); public static LogLevel MinimumLevel { get; set; } = LogLevel.Info; public static void Debug(string message) { Log(LogLevel.Debug, message); } public static void Info(string message) { Log(LogLevel.Info, message); } public static void Warning(string message) { Log(LogLevel.Warning, message); } public static void Error(string message) { Log(LogLevel.Error, message); } private static void Log(LogLevel level, string message) { if (level < MinimumLevel) { return; } lock (_lock) { ConsoleColor foregroundColor = Console.ForegroundColor; try { Console.ForegroundColor = GetLevelColor(level); Console.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] [{level}] {message}"); } finally { Console.ForegroundColor = foregroundColor; } } } private static ConsoleColor GetLevelColor(LogLevel level) { return level switch { LogLevel.Debug => ConsoleColor.DarkGray, LogLevel.Info => ConsoleColor.White, LogLevel.Warning => ConsoleColor.Yellow, LogLevel.Error => ConsoleColor.Red, _ => ConsoleColor.Gray, }; } } public class MethodVariablePool { private readonly MethodDefinition m_Method; private readonly Dictionary<TypeReference, VariableDefinition> m_Variables = new Dictionary<TypeReference, VariableDefinition>(); public MethodVariablePool(MethodDefinition method) { m_Method = method; } public VariableDefinition GetListVariable(TypeReference type) { return GetVariableDefinition(type); } public VariableDefinition GetIndexVariable() { return GetVariableDefinition(((MemberReference)m_Method).Module.TypeSystem.UInt32); } public VariableDefinition GetItemVariable(TypeReference type) { return GetVariableDefinition(type); } private VariableDefinition GetVariableDefinition(TypeReference type) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Expected O, but got Unknown if (!m_Variables.TryGetValue(type, out var value)) { value = new VariableDefinition(type); m_Method.Body.Variables.Add(value); m_Variables[type] = value; } return value; } } public class Patcher { public static IEnumerable<string> TargetDLLs { get; } = new <>z__ReadOnlySingleElementList<string>("Assembly-CSharp.dll"); public static SaveManager SaveManager { get; set; } = null; private static string BasePatcherDirectory { get; set; } = ""; private static ObjectTypes TypesToLoad { get; set; } = new ObjectTypes(); public static void Initialize() { if (SaveManager == null) { SaveManager = new SaveManager(); } BasePatcherDirectory = (from x in Directory.GetDirectories(Paths.PatcherPluginPath, "*", SearchOption.AllDirectories) where x.ToLower().EndsWith("enhancedprefabloader") select x).FirstOrDefault(); Logger.Info("Loading saved enum values."); SaveManager.Load(BasePatcherDirectory + "/savedTypes"); foreach (string item in from x in Directory.GetDirectories(Paths.PatcherPluginPath, "*", SearchOption.AllDirectories) where x.ToLower().EndsWith("prefabloader") select x) { foreach (string item2 in Directory.EnumerateFiles(item, "*.json", SearchOption.AllDirectories)) { Logger.Info("Enhanced Prefab Loader json detected: " + item2 + "."); ObjectTypes objectTypes = JsonConvert.DeserializeObject<ObjectTypes>(File.ReadAllText(item2)); TypesToLoad.FurnitureTypes.AddRange(objectTypes.FurnitureTypes); TypesToLoad.ItemTypes.AddRange(objectTypes.ItemTypes); } } Logger.Info("Object type enum values found: "); TypesToLoad.FurnitureTypes.ForEach(delegate(string x) { Logger.Info(x); }); Logger.Info("Item type enum values found: "); TypesToLoad.ItemTypes.ForEach(delegate(string x) { Logger.Info(x); }); } public static void Patch(AssemblyDefinition assembly) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) Logger.MinimumLevel = LogLevel.Info; _ = assembly.MainModule; ((BaseAssemblyResolver)assembly.MainModule.AssemblyResolver).AddSearchDirectory((from x in Directory.GetDirectories(Paths.PluginPath, "*", SearchOption.AllDirectories) where x.ToLower().EndsWith("enhancedprefabloader") select x).FirstOrDefault()); Logger.Info("Enhanced Prefab Loader patching started."); Logger.Info("Applying patches to List accessors."); ListPatcher.Instance.PatchListAccessors(assembly.MainModule); if (TypesToLoad?.FurnitureTypes != null && TypesToLoad.FurnitureTypes.Count > 0) { Logger.Info("Loading enum patches for furniture types."); SaveManager.FurnitureTypes = EnumPatcher.PatchEnum(assembly, "EObjectType", TypesToLoad.FurnitureTypes, 1000, SaveManager.FurnitureTypes); } if (TypesToLoad?.ItemTypes != null && TypesToLoad.ItemTypes.Count > 0) { Logger.Info("Loading enum patches for item types"); SaveManager.ItemTypes = EnumPatcher.PatchEnum(assembly, "EItemType", TypesToLoad.ItemTypes, 200000, SaveManager.ItemTypes); } SaveManager.Save(BasePatcherDirectory + "/savedTypes"); Logger.Info("Enhanced Prefab Loader PrePatching complete"); } } public class SaveManager { public BidirectionalDictionary<string, int> FurnitureTypes { get; set; } = new BidirectionalDictionary<string, int>(); public BidirectionalDictionary<string, int> ItemTypes { get; set; } = new BidirectionalDictionary<string, int>(); public BidirectionalDictionary<string, int> ItemCategories { get; set; } = new BidirectionalDictionary<string, int>(); public void Load(string filePath) { if (File.Exists(filePath)) { SaveData saveData = JsonConvert.DeserializeObject<SaveData>(File.ReadAllText(filePath)); FurnitureTypes.Clear(); ItemTypes.Clear(); ItemCategories.Clear(); if (saveData.FurnitureObjectTypes != null) { FurnitureTypes.AddAll(saveData.FurnitureObjectTypes); } if (saveData.ItemTypes != null) { ItemTypes.AddAll(saveData.ItemTypes); } if (saveData.ItemCategories != null) { ItemCategories.AddAll(saveData.ItemCategories); } } } public void Save(string filePath) { SaveData saveData = default(SaveData); saveData.FurnitureObjectTypes = FurnitureTypes.Dictionary; saveData.ItemTypes = ItemTypes.Dictionary; saveData.ItemCategories = ItemCategories.Dictionary; SaveData saveData2 = saveData; File.WriteAllText(filePath, JsonConvert.SerializeObject((object)saveData2)); } } public static class MyPluginInfo { public const string PLUGIN_GUID = "EnhancedPrefabLoaderPrepatch"; public const string PLUGIN_NAME = "Enhanced Prefab Loader Prepatch"; public const string PLUGIN_VERSION = "2.0.0"; } } namespace EnhancedPrefabLoaderPrepatch.Models { public class ObjectTypes { public List<string> FurnitureTypes { get; set; } = new List<string>(); public List<string> ItemTypes { get; set; } = new List<string>(); public List<string> ItemCategoryTypes { get; set; } = new List<string>(); } public struct SaveData { public Dictionary<string, int> FurnitureObjectTypes { get; set; } public Dictionary<string, int> ItemTypes { get; set; } public Dictionary<string, int> ItemCategories { get; set; } } } namespace EnhancedPrefabLoaderPrepatch.Extensions { public static class CicelExtensions { public static bool IsLoadCode(this OpCode opCode) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) if (!opCode.IsLdloc() && !opCode.IsLdarg() && !opCode.IsLdc() && !opCode.IsLdelem() && !opCode.IsFieldLoad() && !opCode.IsLdNullOrStr()) { return opCode.IsLdind(); } return true; } public static bool IsFieldLoad(this OpCode opCode) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Invalid comparison between Unknown and I4 //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Invalid comparison between Unknown and I4 Code code = ((OpCode)(ref opCode)).Code; if ((int)code == 120 || (int)code == 123) { return true; } return false; } public static bool IsLdloc(this OpCode opCode) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Invalid comparison between Unknown and I4 //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Invalid comparison between Unknown and I4 //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Invalid comparison between Unknown and I4 Code code = ((OpCode)(ref opCode)).Code; if (code - 6 <= 3 || (int)code == 17 || (int)code == 202) { return true; } return false; } public static bool IsLdarg(this OpCode opCode) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Invalid comparison between Unknown and I4 //IL_000e: 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_0013: Invalid comparison between Unknown and I4 //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Invalid comparison between Unknown and I4 Code code = ((OpCode)(ref opCode)).Code; if (code - 2 <= 3 || code - 14 <= 1 || code - 199 <= 1) { return true; } return false; } public static bool IsLdc(this OpCode opCode) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Invalid comparison between Unknown and I4 Code code = ((OpCode)(ref opCode)).Code; if (code - 21 <= 14) { return true; } return false; } public static bool IsLdelem(this OpCode opCode) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Invalid comparison between Unknown and I4 //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Invalid comparison between Unknown and I4 //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Invalid comparison between Unknown and I4 Code code = ((OpCode)(ref opCode)).Code; if ((int)code == 145 || (int)code == 151 || (int)code == 160) { return true; } return false; } public static bool IsLdind(this OpCode opCode) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Invalid comparison between Unknown and I4 //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Invalid comparison between Unknown and I4 Code code = ((OpCode)(ref opCode)).Code; if (code - 69 <= 6 || code - 77 <= 2) { return true; } return false; } public static bool IsLdNullOrStr(this OpCode opCode) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Invalid comparison between Unknown and I4 //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Invalid comparison between Unknown and I4 Code code = ((OpCode)(ref opCode)).Code; if ((int)code == 20 || (int)code == 113) { return true; } return false; } public static bool IsStloc(this OpCode opCode) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Invalid comparison between Unknown and I4 //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Invalid comparison between Unknown and I4 //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Invalid comparison between Unknown and I4 Code code = ((OpCode)(ref opCode)).Code; if (code - 10 <= 3 || (int)code == 19 || (int)code == 204) { return true; } return false; } public static bool IsComplimentaryStOf(this Instruction stInstruction, Instruction ldInstruction) { //IL_0001: 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 (stInstruction.OpCode.IsStloc() && ldInstruction.OpCode.IsLdloc()) { return stInstruction.GetLocalCodeIndex() == ldInstruction.GetLocalCodeIndex(); } return false; } public static int? GetLocalCodeIndex(this Instruction instr) { //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_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Expected I4, but got Unknown //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Invalid comparison between Unknown and I4 //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Invalid comparison between Unknown and I4 OpCode opCode = instr.OpCode; Code code = ((OpCode)(ref opCode)).Code; switch (code - 6) { default: if ((int)code != 202 && (int)code != 204) { break; } goto case 11; case 0: case 4: return 0; case 1: case 5: return 1; case 2: case 6: return 2; case 3: case 7: return 3; case 11: case 13: { object operand = instr.Operand; object obj = ((operand is VariableReference) ? operand : null); return (obj != null) ? new int?(((VariableReference)obj).Index) : null; } case 8: case 9: case 10: case 12: break; } return null; } public static bool IsListType(this TypeReference typeRef) { if (((typeRef != null) ? ((MemberReference)typeRef).Name : null) == "List`1" && ((typeRef != null) ? typeRef.Namespace : null) == "System.Collections.Generic") { if (!(typeRef is GenericInstanceType)) { TypeDefinition obj = typeRef.Resolve(); object obj2; if (obj == null) { obj2 = null; } else { TypeReference baseType = obj.BaseType; obj2 = ((baseType != null) ? ((MemberReference)baseType).Name : null); } return (string?)obj2 == "List`1"; } return true; } return false; } public static bool IsListAccessor(this MethodReference methodRef) { if (methodRef != null) { if (!methodRef.IsListGetItemCall() && !methodRef.IsListSetItemCall()) { return methodRef.IsListGetCountCall(); } return true; } return false; } public static bool IsListGetItemCall(this MethodReference methodRef) { if (methodRef != null && ((MemberReference)methodRef).DeclaringType.IsListType()) { return ((MemberReference)methodRef).Name == "get_Item"; } return false; } public static bool IsListSetItemCall(this MethodReference methodRef) { if (methodRef != null && ((MemberReference)methodRef).DeclaringType.IsListType()) { return ((MemberReference)methodRef).Name == "set_Item"; } return false; } public static bool IsListGetCountCall(this MethodReference methodRef) { if (methodRef != null && ((MemberReference)methodRef).DeclaringType.IsListType()) { return ((MemberReference)methodRef).Name == "get_Count"; } return false; } public static bool MatchListLoad(this Instruction instr, MethodBody methodBody, out TypeReference elementType) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0032: 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_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Invalid comparison between Unknown and I4 //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Invalid comparison between Unknown and I4 //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Expected I4, but got Unknown //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Invalid comparison between Unknown and I4 //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Invalid comparison between Unknown and I4 //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Invalid comparison between Unknown and I4 elementType = null; if (instr != null) { _ = instr.OpCode; if (0 == 0 && ((methodBody != null) ? methodBody.Method : null) != null && instr.OpCode.IsLoadCode()) { try { OpCode opCode = instr.OpCode; Code code = ((OpCode)(ref opCode)).Code; if ((int)code <= 120) { switch (code - 2) { case 4: goto IL_00bb; case 5: goto IL_00d2; case 6: goto IL_00e9; case 7: goto IL_0100; case 15: goto IL_0117; case 0: goto IL_0134; case 1: goto IL_0171; case 2: goto IL_019a; case 3: goto IL_01c3; case 12: goto IL_01ec; case 8: case 9: case 10: case 11: case 13: case 14: goto IL_0220; } if ((int)code == 120) { goto IL_0206; } } else { if ((int)code == 123) { goto IL_0206; } if ((int)code == 199) { goto IL_01ec; } if ((int)code == 202) { goto IL_0117; } } goto IL_0220; IL_0220: TypeReference val = null; goto IL_0222; IL_0134: object obj2; if (!((MethodReference)methodBody.Method).HasThis) { ParameterDefinition obj = ((MethodReference)methodBody.Method).Parameters[0]; obj2 = ((obj != null) ? ((ParameterReference)obj).ParameterType : null); } else { obj2 = methodBody.Method.DeclaringType; } val = (TypeReference)obj2; goto IL_0222; IL_0100: val = ((VariableReference)methodBody.Variables[3]).VariableType; goto IL_0222; IL_00e9: val = ((VariableReference)methodBody.Variables[2]).VariableType; goto IL_0222; IL_00d2: val = ((VariableReference)methodBody.Variables[1]).VariableType; goto IL_0222; IL_00bb: val = ((VariableReference)methodBody.Variables[0]).VariableType; goto IL_0222; IL_01c3: val = ((ParameterReference)((MethodReference)methodBody.Method).Parameters[((MethodReference)methodBody.Method).HasThis ? 2 : 3]).ParameterType; goto IL_0222; IL_0117: object operand = instr.Operand; object obj3 = ((operand is VariableReference) ? operand : null); val = ((obj3 != null) ? ((VariableReference)obj3).VariableType : null); goto IL_0222; IL_0206: object operand2 = instr.Operand; object obj4 = ((operand2 is FieldReference) ? operand2 : null); val = ((obj4 != null) ? ((FieldReference)obj4).FieldType : null); goto IL_0222; IL_01ec: object operand3 = instr.Operand; object obj5 = ((operand3 is ParameterReference) ? operand3 : null); val = ((obj5 != null) ? ((ParameterReference)obj5).ParameterType : null); goto IL_0222; IL_019a: val = ((ParameterReference)((MethodReference)methodBody.Method).Parameters[((MethodReference)methodBody.Method).HasThis ? 1 : 2]).ParameterType; goto IL_0222; IL_0222: TypeReference val2 = val; GenericInstanceType val3 = (GenericInstanceType)(object)((val2 is GenericInstanceType) ? val2 : null); if (val3 != null && val2.IsListType() && val3.GenericArguments.Count > 0) { elementType = val3.GenericArguments[0]; return true; } return false; IL_0171: val = ((ParameterReference)((MethodReference)methodBody.Method).Parameters[(!((MethodReference)methodBody.Method).HasThis) ? 1 : 0]).ParameterType; goto IL_0222; } catch (Exception ex) when (((ex is ArgumentOutOfRangeException || ex is NullReferenceException) ? 1 : 0) != 0) { elementType = null; return false; } } } return false; } } } [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(); } }
BepInEx/patchers/MonoMod.Backports.dll
Decompiled 3 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Numerics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Cryptography; using System.Security.Permissions; using System.Threading; using Microsoft.CodeAnalysis; using MonoMod; using MonoMod.Backports.ILHelpers; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: CLSCompliant(true)] [assembly: TargetFramework(".NETFramework,Version=v4.5.2", FrameworkDisplayName = ".NET Framework 4.5.2")] [assembly: AssemblyCompany("0x0ade, DaNike")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright 2024 0x0ade, DaNike")] [assembly: AssemblyDescription("A set of backports of new BCL features to all frameworks which MonoMod supports.")] [assembly: AssemblyFileVersion("1.1.2.0")] [assembly: AssemblyInformationalVersion("1.1.2+a1b82852b")] [assembly: AssemblyProduct("MonoMod.Backports")] [assembly: AssemblyTitle("MonoMod.Backports")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/MonoMod/MonoMod.git")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.1.2.0")] [assembly: TypeForwardedTo(typeof(ConcurrentBag<>))] [assembly: TypeForwardedTo(typeof(ConcurrentDictionary<, >))] [assembly: TypeForwardedTo(typeof(ConcurrentQueue<>))] [assembly: TypeForwardedTo(typeof(ConcurrentStack<>))] [assembly: TypeForwardedTo(typeof(EnumerablePartitionerOptions))] [assembly: TypeForwardedTo(typeof(IProducerConsumerCollection<>))] [assembly: TypeForwardedTo(typeof(OrderablePartitioner<>))] [assembly: TypeForwardedTo(typeof(Partitioner))] [assembly: TypeForwardedTo(typeof(Partitioner<>))] [assembly: TypeForwardedTo(typeof(IReadOnlyCollection<>))] [assembly: TypeForwardedTo(typeof(IReadOnlyList<>))] [assembly: TypeForwardedTo(typeof(IStructuralComparable))] [assembly: TypeForwardedTo(typeof(IStructuralEquatable))] [assembly: TypeForwardedTo(typeof(IntrospectionExtensions))] [assembly: TypeForwardedTo(typeof(IReflectableType))] [assembly: TypeForwardedTo(typeof(TypeDelegator))] [assembly: TypeForwardedTo(typeof(TypeInfo))] [assembly: TypeForwardedTo(typeof(CallerFilePathAttribute))] [assembly: TypeForwardedTo(typeof(CallerLineNumberAttribute))] [assembly: TypeForwardedTo(typeof(CallerMemberNameAttribute))] [assembly: TypeForwardedTo(typeof(ConditionalWeakTable<, >))] [assembly: TypeForwardedTo(typeof(TupleElementNamesAttribute))] [assembly: TypeForwardedTo(typeof(DefaultDllImportSearchPathsAttribute))] [assembly: TypeForwardedTo(typeof(DllImportSearchPath))] [assembly: TypeForwardedTo(typeof(SpinLock))] [assembly: TypeForwardedTo(typeof(SpinWait))] [assembly: TypeForwardedTo(typeof(ThreadLocal<>))] [assembly: TypeForwardedTo(typeof(Volatile))] [assembly: TypeForwardedTo(typeof(Tuple))] [assembly: TypeForwardedTo(typeof(Tuple<>))] [assembly: TypeForwardedTo(typeof(Tuple<, >))] [assembly: TypeForwardedTo(typeof(Tuple<, , >))] [assembly: TypeForwardedTo(typeof(Tuple<, , , >))] [assembly: TypeForwardedTo(typeof(Tuple<, , , , >))] [assembly: TypeForwardedTo(typeof(Tuple<, , , , , >))] [assembly: TypeForwardedTo(typeof(Tuple<, , , , , , >))] [assembly: TypeForwardedTo(typeof(Tuple<, , , , , , , >))] [assembly: TypeForwardedTo(typeof(ValueTuple))] [assembly: TypeForwardedTo(typeof(ValueTuple<>))] [assembly: TypeForwardedTo(typeof(ValueTuple<, >))] [assembly: TypeForwardedTo(typeof(ValueTuple<, , >))] [assembly: TypeForwardedTo(typeof(ValueTuple<, , , >))] [assembly: TypeForwardedTo(typeof(ValueTuple<, , , , >))] [assembly: TypeForwardedTo(typeof(ValueTuple<, , , , , >))] [assembly: TypeForwardedTo(typeof(ValueTuple<, , , , , , >))] [assembly: TypeForwardedTo(typeof(ValueTuple<, , , , , , , >))] [assembly: TypeForwardedTo(typeof(WeakReference<>))] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsByRefLikeAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NativeIntegerAttribute : Attribute { public readonly bool[] TransformFlags; public NativeIntegerAttribute() { TransformFlags = new bool[1] { true }; } public NativeIntegerAttribute(bool[] P_0) { TransformFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } internal static class AssemblyInfo { public const string AssemblyName = "MonoMod.Backports"; public const string AssemblyVersion = "1.1.2"; } namespace MonoMod.SourceGen.Attributes { [AttributeUsage(AttributeTargets.Class)] internal sealed class EmitILOverloadsAttribute : Attribute { public EmitILOverloadsAttribute(string filename, string kind) { } } internal static class ILOverloadKind { public const string Cursor = "ILCursor"; public const string Matcher = "ILMatcher"; } } namespace MonoMod.Backports { public static class MethodImplOptionsEx { public const MethodImplOptions Unmanaged = MethodImplOptions.Unmanaged; public const MethodImplOptions NoInlining = MethodImplOptions.NoInlining; public const MethodImplOptions ForwardRef = MethodImplOptions.ForwardRef; public const MethodImplOptions Synchronized = MethodImplOptions.Synchronized; public const MethodImplOptions NoOptimization = MethodImplOptions.NoOptimization; public const MethodImplOptions PreserveSig = MethodImplOptions.PreserveSig; public const MethodImplOptions AggressiveInlining = MethodImplOptions.AggressiveInlining; public const MethodImplOptions AggressiveOptimization = MethodImplOptions.AggressiveOptimization; public const MethodImplOptions InternalCall = MethodImplOptions.InternalCall; } } namespace System { public static class ArrayEx { private static class TypeHolder<T> { public static readonly T[] Empty = new T[0]; } public static int MaxLength => 1879048191; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T[] Empty<T>() { return TypeHolder<T>.Empty; } } public readonly struct SequencePosition : IEquatable<SequencePosition> { private readonly object? _object; private readonly int _integer; public SequencePosition(object? @object, int integer) { _object = @object; _integer = integer; } [EditorBrowsable(EditorBrowsableState.Never)] public object? GetObject() { return _object; } [EditorBrowsable(EditorBrowsableState.Never)] public int GetInteger() { return _integer; } public bool Equals(SequencePosition other) { if (_integer == other._integer) { return object.Equals(_object, other._object); } return false; } [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) { if (obj is SequencePosition other) { return Equals(other); } return false; } [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { return HashCode.Combine(_object, _integer); } } public static class EnvironmentEx { public static int CurrentManagedThreadId => Environment.CurrentManagedThreadId; } public sealed class Gen2GcCallback : CriticalFinalizerObject { private readonly Func<bool>? _callback0; private readonly Func<object, bool>? _callback1; private GCHandle _weakTargetObj; private Gen2GcCallback(Func<bool> callback) { _callback0 = callback; } private Gen2GcCallback(Func<object, bool> callback, object targetObj) { _callback1 = callback; _weakTargetObj = GCHandle.Alloc(targetObj, GCHandleType.Weak); } public static void Register(Func<bool> callback) { new Gen2GcCallback(callback); } public static void Register(Func<object, bool> callback, object targetObj) { new Gen2GcCallback(callback, targetObj); } ~Gen2GcCallback() { if (_weakTargetObj.IsAllocated) { object target = _weakTargetObj.Target; if (target == null) { _weakTargetObj.Free(); return; } try { if (!_callback1(target)) { _weakTargetObj.Free(); return; } } catch { } } else { try { if (!_callback0()) { return; } } catch { } } GC.ReRegisterForFinalize(this); } } public struct HashCode { private static readonly uint s_seed = GenerateGlobalSeed(); private const uint Prime1 = 2654435761u; private const uint Prime2 = 2246822519u; private const uint Prime3 = 3266489917u; private const uint Prime4 = 668265263u; private const uint Prime5 = 374761393u; private uint _v1; private uint _v2; private uint _v3; private uint _v4; private uint _queue1; private uint _queue2; private uint _queue3; private uint _length; private static uint GenerateGlobalSeed() { Span<byte> destination = stackalloc byte[4]; using (RandomNumberGenerator randomNumberGenerator = RandomNumberGenerator.Create()) { byte[] array = new byte[destination.Length]; randomNumberGenerator.GetBytes(array); MemoryExtensions.AsSpan(array).CopyTo(destination); } return Unsafe.ReadUnaligned<uint>(ref destination[0]); } public static int Combine<T1>(T1 value1) { uint queuedValue = (uint)(value1?.GetHashCode() ?? 0); return (int)MixFinal(QueueRound(MixEmptyState() + 4, queuedValue)); } public static int Combine<T1, T2>(T1 value1, T2 value2) { uint queuedValue = (uint)(value1?.GetHashCode() ?? 0); uint queuedValue2 = (uint)(value2?.GetHashCode() ?? 0); return (int)MixFinal(QueueRound(QueueRound(MixEmptyState() + 8, queuedValue), queuedValue2)); } public static int Combine<T1, T2, T3>(T1 value1, T2 value2, T3 value3) { uint queuedValue = (uint)(value1?.GetHashCode() ?? 0); uint queuedValue2 = (uint)(value2?.GetHashCode() ?? 0); uint queuedValue3 = (uint)(value3?.GetHashCode() ?? 0); return (int)MixFinal(QueueRound(QueueRound(QueueRound(MixEmptyState() + 12, queuedValue), queuedValue2), queuedValue3)); } public static int Combine<T1, T2, T3, T4>(T1 value1, T2 value2, T3 value3, T4 value4) { uint input = (uint)(value1?.GetHashCode() ?? 0); uint input2 = (uint)(value2?.GetHashCode() ?? 0); uint input3 = (uint)(value3?.GetHashCode() ?? 0); uint input4 = (uint)(value4?.GetHashCode() ?? 0); Initialize(out var v, out var v2, out var v3, out var v4); v = Round(v, input); v2 = Round(v2, input2); v3 = Round(v3, input3); v4 = Round(v4, input4); return (int)MixFinal(MixState(v, v2, v3, v4) + 16); } public static int Combine<T1, T2, T3, T4, T5>(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5) { uint input = (uint)(value1?.GetHashCode() ?? 0); uint input2 = (uint)(value2?.GetHashCode() ?? 0); uint input3 = (uint)(value3?.GetHashCode() ?? 0); uint input4 = (uint)(value4?.GetHashCode() ?? 0); uint queuedValue = (uint)(value5?.GetHashCode() ?? 0); Initialize(out var v, out var v2, out var v3, out var v4); v = Round(v, input); v2 = Round(v2, input2); v3 = Round(v3, input3); v4 = Round(v4, input4); return (int)MixFinal(QueueRound(MixState(v, v2, v3, v4) + 20, queuedValue)); } public static int Combine<T1, T2, T3, T4, T5, T6>(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6) { uint input = (uint)(value1?.GetHashCode() ?? 0); uint input2 = (uint)(value2?.GetHashCode() ?? 0); uint input3 = (uint)(value3?.GetHashCode() ?? 0); uint input4 = (uint)(value4?.GetHashCode() ?? 0); uint queuedValue = (uint)(value5?.GetHashCode() ?? 0); uint queuedValue2 = (uint)(value6?.GetHashCode() ?? 0); Initialize(out var v, out var v2, out var v3, out var v4); v = Round(v, input); v2 = Round(v2, input2); v3 = Round(v3, input3); v4 = Round(v4, input4); return (int)MixFinal(QueueRound(QueueRound(MixState(v, v2, v3, v4) + 24, queuedValue), queuedValue2)); } public static int Combine<T1, T2, T3, T4, T5, T6, T7>(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6, T7 value7) { uint input = (uint)(value1?.GetHashCode() ?? 0); uint input2 = (uint)(value2?.GetHashCode() ?? 0); uint input3 = (uint)(value3?.GetHashCode() ?? 0); uint input4 = (uint)(value4?.GetHashCode() ?? 0); uint queuedValue = (uint)(value5?.GetHashCode() ?? 0); uint queuedValue2 = (uint)(value6?.GetHashCode() ?? 0); uint queuedValue3 = (uint)(value7?.GetHashCode() ?? 0); Initialize(out var v, out var v2, out var v3, out var v4); v = Round(v, input); v2 = Round(v2, input2); v3 = Round(v3, input3); v4 = Round(v4, input4); return (int)MixFinal(QueueRound(QueueRound(QueueRound(MixState(v, v2, v3, v4) + 28, queuedValue), queuedValue2), queuedValue3)); } public static int Combine<T1, T2, T3, T4, T5, T6, T7, T8>(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6, T7 value7, T8 value8) { uint input = (uint)(value1?.GetHashCode() ?? 0); uint input2 = (uint)(value2?.GetHashCode() ?? 0); uint input3 = (uint)(value3?.GetHashCode() ?? 0); uint input4 = (uint)(value4?.GetHashCode() ?? 0); uint input5 = (uint)(value5?.GetHashCode() ?? 0); uint input6 = (uint)(value6?.GetHashCode() ?? 0); uint input7 = (uint)(value7?.GetHashCode() ?? 0); uint input8 = (uint)(value8?.GetHashCode() ?? 0); Initialize(out var v, out var v2, out var v3, out var v4); v = Round(v, input); v2 = Round(v2, input2); v3 = Round(v3, input3); v4 = Round(v4, input4); v = Round(v, input5); v2 = Round(v2, input6); v3 = Round(v3, input7); v4 = Round(v4, input8); return (int)MixFinal(MixState(v, v2, v3, v4) + 32); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Initialize(out uint v1, out uint v2, out uint v3, out uint v4) { v1 = (uint)((int)s_seed + -1640531535 + -2048144777); v2 = s_seed + 2246822519u; v3 = s_seed; v4 = s_seed - 2654435761u; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static uint Round(uint hash, uint input) { return BitOperations.RotateLeft(hash + (uint)((int)input * -2048144777), 13) * 2654435761u; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static uint QueueRound(uint hash, uint queuedValue) { return BitOperations.RotateLeft(hash + (uint)((int)queuedValue * -1028477379), 17) * 668265263; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static uint MixState(uint v1, uint v2, uint v3, uint v4) { return BitOperations.RotateLeft(v1, 1) + BitOperations.RotateLeft(v2, 7) + BitOperations.RotateLeft(v3, 12) + BitOperations.RotateLeft(v4, 18); } private static uint MixEmptyState() { return s_seed + 374761393; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static uint MixFinal(uint hash) { hash ^= hash >> 15; hash *= 2246822519u; hash ^= hash >> 13; hash *= 3266489917u; hash ^= hash >> 16; return hash; } public void Add<T>(T value) { Add(value?.GetHashCode() ?? 0); } public void Add<T>(T value, IEqualityComparer<T>? comparer) { Add((value != null) ? (comparer?.GetHashCode(value) ?? value.GetHashCode()) : 0); } public void AddBytes(ReadOnlySpan<byte> value) { ref byte reference = ref MemoryMarshal.GetReference(value); ref byte reference2 = ref Unsafe.Add(ref reference, value.Length); while (Unsafe.ByteOffset(ref reference, ref reference2) >= 4) { Add(Unsafe.ReadUnaligned<int>(ref reference)); reference = ref Unsafe.Add(ref reference, 4); } while (Unsafe.IsAddressLessThan(ref reference, ref reference2)) { Add((int)reference); reference = ref Unsafe.Add(ref reference, 1); } } private void Add(int value) { uint num = _length++; switch (num % 4) { case 0u: _queue1 = (uint)value; return; case 1u: _queue2 = (uint)value; return; case 2u: _queue3 = (uint)value; return; } if (num == 3) { Initialize(out _v1, out _v2, out _v3, out _v4); } _v1 = Round(_v1, _queue1); _v2 = Round(_v2, _queue2); _v3 = Round(_v3, _queue3); _v4 = Round(_v4, (uint)value); } public int ToHashCode() { uint length = _length; uint num = length % 4; uint num2 = ((length < 4) ? MixEmptyState() : MixState(_v1, _v2, _v3, _v4)); num2 += length * 4; if (num != 0) { num2 = QueueRound(num2, _queue1); if (num > 1) { num2 = QueueRound(num2, _queue2); if (num > 2) { num2 = QueueRound(num2, _queue3); } } } return (int)MixFinal(num2); } [Obsolete("HashCode is a mutable struct and should not be compared with other HashCodes. Use ToHashCode to retrieve the computed hash code.", true)] [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { throw new NotSupportedException("GetHashCode on HashCode is not supported"); } [Obsolete("HashCode is a mutable struct and should not be compared with other HashCodes.", true)] [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) { throw new NotSupportedException("Equals on HashCode is not supported"); } } public static class MathEx { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static byte Clamp(byte value, byte min, byte max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static decimal Clamp(decimal value, decimal min, decimal max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double Clamp(double value, double min, double max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static short Clamp(short value, short min, short max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int Clamp(int value, int min, int max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static long Clamp(long value, long min, long max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static nint Clamp(nint value, nint min, nint max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static sbyte Clamp(sbyte value, sbyte min, sbyte max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Clamp(float value, float min, float max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ushort Clamp(ushort value, ushort min, ushort max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static uint Clamp(uint value, uint min, uint max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ulong Clamp(ulong value, ulong min, ulong max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static nuint Clamp(nuint value, nuint min, nuint max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [DoesNotReturn] private static void ThrowMinMaxException<T>(T min, T max) { throw new ArgumentException($"Minimum {min} is less than maximum {max}"); } } [DebuggerTypeProxy(typeof(System.MemoryDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] public readonly struct Memory<T> { private readonly object? _object; private readonly int _index; private readonly int _length; private const int RemoveFlagsBitMask = int.MaxValue; public static Memory<T> Empty => default(Memory<T>); public int Length => _length & 0x7FFFFFFF; public bool IsEmpty => (_length & 0x7FFFFFFF) == 0; public Span<T> Span { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Span<T> result; if (_index < 0) { result = ((MemoryManager<T>)_object).GetSpan(); return result.Slice(_index & 0x7FFFFFFF, _length); } if (typeof(T) == typeof(char) && _object is string text) { result = new Span<T>(text, (IntPtr)RuntimeHelpers.OffsetToStringData, text.Length); return result.Slice(_index, _length); } if (_object != null) { return new Span<T>((T[])_object, _index, _length & 0x7FFFFFFF); } result = default(Span<T>); return result; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory(T[]? array) { if (array == null) { this = default(Memory<T>); return; } if (default(T) == null && array.GetType() != typeof(T[])) { System.ThrowHelper.ThrowArrayTypeMismatchException(); } _object = array; _index = 0; _length = array.Length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(T[]? array, int start) { if (array == null) { if (start != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } this = default(Memory<T>); return; } if (default(T) == null && array.GetType() != typeof(T[])) { System.ThrowHelper.ThrowArrayTypeMismatchException(); } if ((uint)start > (uint)array.Length) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } _object = array; _index = start; _length = array.Length - start; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory(T[]? array, int start, int length) { if (array == null) { if (start != 0 || length != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } this = default(Memory<T>); return; } if (default(T) == null && array.GetType() != typeof(T[])) { System.ThrowHelper.ThrowArrayTypeMismatchException(); } if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } _object = array; _index = start; _length = length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(MemoryManager<T> manager, int length) { if (length < 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } _object = manager; _index = int.MinValue; _length = length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(MemoryManager<T> manager, int start, int length) { if (length < 0 || start < 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } _object = manager; _index = start | int.MinValue; _length = length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(object? obj, int start, int length) { _object = obj; _index = start; _length = length; } public static implicit operator Memory<T>(T[]? array) { return new Memory<T>(array); } public static implicit operator Memory<T>(ArraySegment<T> segment) { return new Memory<T>(segment.Array, segment.Offset, segment.Count); } public static implicit operator ReadOnlyMemory<T>(Memory<T> memory) { return Unsafe.As<Memory<T>, ReadOnlyMemory<T>>(ref memory); } public override string ToString() { if (typeof(T) == typeof(char)) { if (!(_object is string text)) { return Span.ToString(); } return text.Substring(_index, _length & 0x7FFFFFFF); } return $"System.Memory<{typeof(T).Name}>[{_length & 0x7FFFFFFF}]"; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory<T> Slice(int start) { int length = _length; int num = length & 0x7FFFFFFF; if ((uint)start > (uint)num) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new Memory<T>(_object, _index + start, length - start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory<T> Slice(int start, int length) { int length2 = _length; int num = length2 & 0x7FFFFFFF; if ((uint)start > (uint)num || (uint)length > (uint)(num - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } return new Memory<T>(_object, _index + start, length | (length2 & int.MinValue)); } public void CopyTo(Memory<T> destination) { Span.CopyTo(destination.Span); } public bool TryCopyTo(Memory<T> destination) { return Span.TryCopyTo(destination.Span); } public unsafe MemoryHandle Pin() { if (_index < 0) { return ((MemoryManager<T>)_object).Pin(_index & 0x7FFFFFFF); } if (typeof(T) == typeof(char) && _object is string value) { GCHandle handle = GCHandle.Alloc(value, GCHandleType.Pinned); return new MemoryHandle(Unsafe.Add<T>((void*)handle.AddrOfPinnedObject(), _index), handle); } if (_object is T[] array) { if (_length < 0) { return new MemoryHandle(Unsafe.Add<T>(Unsafe.AsPointer(ref MemoryMarshal.GetReference<T>(array)), _index)); } GCHandle handle2 = GCHandle.Alloc(array, GCHandleType.Pinned); return new MemoryHandle(Unsafe.Add<T>((void*)handle2.AddrOfPinnedObject(), _index), handle2); } return default(MemoryHandle); } public T[] ToArray() { return Span.ToArray(); } [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) { if (obj is ReadOnlyMemory<T> readOnlyMemory) { return readOnlyMemory.Equals(this); } if (obj is Memory<T> other) { return Equals(other); } return false; } public bool Equals(Memory<T> other) { if (_object == other._object && _index == other._index) { return _length == other._length; } return false; } [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { if (_object == null) { return 0; } return HashCode.Combine(_object, _index, _length); } } internal sealed class MemoryDebugView<T> { private readonly ReadOnlyMemory<T> _memory; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items => _memory.ToArray(); public MemoryDebugView(Memory<T> memory) { _memory = memory; } public MemoryDebugView(ReadOnlyMemory<T> memory) { _memory = memory; } } public static class MemoryExtensions { public static ReadOnlySpan<char> Trim(this ReadOnlySpan<char> span) { return span.TrimStart().TrimEnd(); } public static ReadOnlySpan<char> TrimStart(this ReadOnlySpan<char> span) { int i; for (i = 0; i < span.Length && char.IsWhiteSpace(span[i]); i++) { } return span.Slice(i); } public static ReadOnlySpan<char> TrimEnd(this ReadOnlySpan<char> span) { int num = span.Length - 1; while (num >= 0 && char.IsWhiteSpace(span[num])) { num--; } return span.Slice(0, num + 1); } public static ReadOnlySpan<char> Trim(this ReadOnlySpan<char> span, char trimChar) { return span.TrimStart(trimChar).TrimEnd(trimChar); } public static ReadOnlySpan<char> TrimStart(this ReadOnlySpan<char> span, char trimChar) { int i; for (i = 0; i < span.Length && span[i] == trimChar; i++) { } return span.Slice(i); } public static ReadOnlySpan<char> TrimEnd(this ReadOnlySpan<char> span, char trimChar) { int num = span.Length - 1; while (num >= 0 && span[num] == trimChar) { num--; } return span.Slice(0, num + 1); } public static ReadOnlySpan<char> Trim(this ReadOnlySpan<char> span, ReadOnlySpan<char> trimChars) { return span.TrimStart(trimChars).TrimEnd(trimChars); } public static ReadOnlySpan<char> TrimStart(this ReadOnlySpan<char> span, ReadOnlySpan<char> trimChars) { if (trimChars.IsEmpty) { return span.TrimStart(); } int i; for (i = 0; i < span.Length; i++) { int num = 0; while (num < trimChars.Length) { if (span[i] != trimChars[num]) { num++; continue; } goto IL_003c; } break; IL_003c:; } return span.Slice(i); } public static ReadOnlySpan<char> TrimEnd(this ReadOnlySpan<char> span, ReadOnlySpan<char> trimChars) { if (trimChars.IsEmpty) { return span.TrimEnd(); } int num; for (num = span.Length - 1; num >= 0; num--) { int num2 = 0; while (num2 < trimChars.Length) { if (span[num] != trimChars[num2]) { num2++; continue; } goto IL_0044; } break; IL_0044:; } return span.Slice(0, num + 1); } public static bool IsWhiteSpace(this ReadOnlySpan<char> span) { for (int i = 0; i < span.Length; i++) { if (!char.IsWhiteSpace(span[i])) { return false; } } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf<T>(this Span<T> span, T value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value), span.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.IndexOf(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, char>(ref value), span.Length); } return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf<T>(this Span<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), value.Length); } return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOf<T>(this Span<T> span, T value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value), span.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, char>(ref value), span.Length); } return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOf<T>(this Span<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), value.Length); } return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool SequenceEqual<T>(this Span<T> span, ReadOnlySpan<T> other) where T : IEquatable<T> { int length = span.Length; if (default(T) != null && IsTypeComparableAsBytes<T>(out var size)) { if (length == other.Length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), (nuint)length * size); } return false; } if (length == other.Length) { return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other), length); } return false; } public static int SequenceCompareTo<T>(this Span<T> span, ReadOnlySpan<T> other) where T : IComparable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), other.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(other)), other.Length); } return System.SpanHelpers.SequenceCompareTo(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(other), other.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf<T>(this ReadOnlySpan<T> span, T value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value), span.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.IndexOf(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, char>(ref value), span.Length); } return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), value.Length); } return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOf<T>(this ReadOnlySpan<T> span, T value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value), span.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, char>(ref value), span.Length); } return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOf<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), value.Length); } return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny<T>(this Span<T> span, T value0, T value1) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), span.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny<T>(this Span<T> span, T value0, T value1, T value2) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), Unsafe.As<T, byte>(ref value2), span.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny<T>(this Span<T> span, ReadOnlySpan<T> values) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(values)), values.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny<T>(this ReadOnlySpan<T> span, T value0, T value1) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), span.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny<T>(this ReadOnlySpan<T> span, T value0, T value1, T value2) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), Unsafe.As<T, byte>(ref value2), span.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> values) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(values)), values.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny<T>(this Span<T> span, T value0, T value1) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), span.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny<T>(this Span<T> span, T value0, T value1, T value2) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), Unsafe.As<T, byte>(ref value2), span.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny<T>(this Span<T> span, ReadOnlySpan<T> values) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(values)), values.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny<T>(this ReadOnlySpan<T> span, T value0, T value1) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), span.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny<T>(this ReadOnlySpan<T> span, T value0, T value1, T value2) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), Unsafe.As<T, byte>(ref value2), span.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> values) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(values)), values.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool SequenceEqual<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> other) where T : IEquatable<T> { int length = span.Length; if (default(T) != null && IsTypeComparableAsBytes<T>(out var size)) { if (length == other.Length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), (nuint)length * size); } return false; } if (length == other.Length) { return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other), length); } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int SequenceCompareTo<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> other) where T : IComparable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), other.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(other)), other.Length); } return System.SpanHelpers.SequenceCompareTo(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(other), other.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool StartsWith<T>(this Span<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { int length = value.Length; if (default(T) != null && IsTypeComparableAsBytes<T>(out var size)) { if (length <= span.Length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (nuint)length * size); } return false; } if (length <= span.Length) { return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(value), length); } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool StartsWith<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { int length = value.Length; if (default(T) != null && IsTypeComparableAsBytes<T>(out var size)) { if (length <= span.Length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (nuint)length * size); } return false; } if (length <= span.Length) { return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(value), length); } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool EndsWith<T>(this Span<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { int length = span.Length; int length2 = value.Length; if (default(T) != null && IsTypeComparableAsBytes<T>(out var size)) { if (length2 <= length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), length - length2)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (nuint)length2 * size); } return false; } if (length2 <= length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), length - length2), ref MemoryMarshal.GetReference(value), length2); } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool EndsWith<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { int length = span.Length; int length2 = value.Length; if (default(T) != null && IsTypeComparableAsBytes<T>(out var size)) { if (length2 <= length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), length - length2)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (nuint)length2 * size); } return false; } if (length2 <= length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), length - length2), ref MemoryMarshal.GetReference(value), length2); } return false; } public static void Reverse<T>(this Span<T> span) { if (span.Length > 1) { ref T reference = ref MemoryMarshal.GetReference(span); ref T reference2 = ref Unsafe.Add(ref Unsafe.Add(ref reference, span.Length), -1); do { T val = reference; reference = reference2; reference2 = val; reference = ref Unsafe.Add(ref reference, 1); reference2 = ref Unsafe.Add(ref reference2, -1); } while (Unsafe.IsAddressLessThan(ref reference, ref reference2)); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<T> AsSpan<T>(this T[]? array) { return new Span<T>(array); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<T> AsSpan<T>(this T[]? array, int start, int length) { return new Span<T>(array, start, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<T> AsSpan<T>(this ArraySegment<T> segment) { return new Span<T>(segment.Array, segment.Offset, segment.Count); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<T> AsSpan<T>(this ArraySegment<T> segment, int start) { if ((uint)start > segment.Count) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new Span<T>(segment.Array, segment.Offset + start, segment.Count - start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<T> AsSpan<T>(this ArraySegment<T> segment, int start, int length) { if ((uint)start > segment.Count) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } if ((uint)length > segment.Count - start) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.length); } return new Span<T>(segment.Array, segment.Offset + start, length); } public static Memory<T> AsMemory<T>(this T[]? array) { return new Memory<T>(array); } public static Memory<T> AsMemory<T>(this T[]? array, int start) { return new Memory<T>(array, start); } public static Memory<T> AsMemory<T>(this T[]? array, int start, int length) { return new Memory<T>(array, start, length); } public static Memory<T> AsMemory<T>(this ArraySegment<T> segment) { return new Memory<T>(segment.Array, segment.Offset, segment.Count); } public static Memory<T> AsMemory<T>(this ArraySegment<T> segment, int start) { if ((uint)start > segment.Count) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new Memory<T>(segment.Array, segment.Offset + start, segment.Count - start); } public static Memory<T> AsMemory<T>(this ArraySegment<T> segment, int start, int length) { if ((uint)start > segment.Count) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } if ((uint)length > segment.Count - start) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.length); } return new Memory<T>(segment.Array, segment.Offset + start, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void CopyTo<T>(this T[]? source, Span<T> destination) { new ReadOnlySpan<T>(source).CopyTo(destination); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void CopyTo<T>(this T[]? source, Memory<T> destination) { source.CopyTo(destination.Span); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Overlaps<T>(this Span<T> span, ReadOnlySpan<T> other) { return ((ReadOnlySpan<T>)span).Overlaps(other); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Overlaps<T>(this Span<T> span, ReadOnlySpan<T> other, out int elementOffset) { return ((ReadOnlySpan<T>)span).Overlaps(other, out elementOffset); } public static bool Overlaps<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> other) { if (span.IsEmpty || other.IsEmpty) { return false; } nint num = Unsafe.ByteOffset(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other)); if (Unsafe.SizeOf<IntPtr>() == 4) { if ((uint)(int)(IntPtr)num >= (uint)(span.Length * Unsafe.SizeOf<T>())) { return (uint)(int)(IntPtr)num > (uint)(-(other.Length * Unsafe.SizeOf<T>())); } return true; } if ((ulong)(long)(IntPtr)num >= (ulong)((long)span.Length * (long)Unsafe.SizeOf<T>())) { return (ulong)(long)(IntPtr)num > (ulong)(-((long)other.Length * (long)Unsafe.SizeOf<T>())); } return true; } public static bool Overlaps<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> other, out int elementOffset) { if (span.IsEmpty || other.IsEmpty) { elementOffset = 0; return false; } nint num = Unsafe.ByteOffset(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other)); if (Unsafe.SizeOf<IntPtr>() == 4) { if ((uint)(int)(IntPtr)num < (uint)(span.Length * Unsafe.SizeOf<T>()) || (uint)(int)(IntPtr)num > (uint)(-(other.Length * Unsafe.SizeOf<T>()))) { if ((int)(IntPtr)num % Unsafe.SizeOf<T>() != 0) { System.ThrowHelper.ThrowArgumentException_OverlapAlignmentMismatch(); } elementOffset = (int)(IntPtr)num / Unsafe.SizeOf<T>(); return true; } elementOffset = 0; return false; } if ((ulong)(long)(IntPtr)num < (ulong)((long)span.Length * (long)Unsafe.SizeOf<T>()) || (ulong)(long)(IntPtr)num > (ulong)(-((long)other.Length * (long)Unsafe.SizeOf<T>()))) { if ((long)(IntPtr)num % Unsafe.SizeOf<T>() != 0L) { System.ThrowHelper.ThrowArgumentException_OverlapAlignmentMismatch(); } elementOffset = (int)((long)(IntPtr)num / Unsafe.SizeOf<T>()); return true; } elementOffset = 0; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T>(this Span<T> span, IComparable<T> comparable) { return span.BinarySearch<T, IComparable<T>>(comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T, TComparable>(this Span<T> span, TComparable comparable) where TComparable : IComparable<T> { return BinarySearch((ReadOnlySpan<T>)span, comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T, TComparer>(this Span<T> span, T value, TComparer comparer) where TComparer : IComparer<T> { return ((ReadOnlySpan<T>)span).BinarySearch(value, comparer); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T>(this ReadOnlySpan<T> span, IComparable<T> comparable) { return MemoryExtensions.BinarySearch<T, IComparable<T>>(span, comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T, TComparable>(this ReadOnlySpan<T> span, TComparable comparable) where TComparable : IComparable<T> { return System.SpanHelpers.BinarySearch(span, comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T, TComparer>(this ReadOnlySpan<T> span, T value, TComparer comparer) where TComparer : IComparer<T> { if (comparer == null) { System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.comparer); } System.SpanHelpers.ComparerComparable<T, TComparer> comparable = new System.SpanHelpers.ComparerComparable<T, TComparer>(value, comparer); return BinarySearch(span, comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsTypeComparableAsBytes<T>(out nuint size) { if (typeof(T) == typeof(byte) || typeof(T) == typeof(sbyte)) { size = 1u; return true; } if (typeof(T) == typeof(char) || typeof(T) == typeof(short) || typeof(T) == typeof(ushort)) { size = 2u; return true; } if (typeof(T) == typeof(int) || typeof(T) == typeof(uint)) { size = 4u; return true; } if (typeof(T) == typeof(long) || typeof(T) == typeof(ulong)) { size = 8u; return true; } size = 0u; return false; } public static Span<T> AsSpan<T>(this T[]? array, int start) { return Span<T>.Create(array, start); } public static bool Contains(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType) { return span.IndexOf(value, comparisonType) >= 0; } public static bool Equals(this ReadOnlySpan<char> span, ReadOnlySpan<char> other, StringComparison comparisonType) { switch (comparisonType) { case StringComparison.Ordinal: return span.SequenceEqual(other); case StringComparison.OrdinalIgnoreCase: if (span.Length != other.Length) { return false; } return EqualsOrdinalIgnoreCase(span, other); default: return span.ToString().Equals(other.ToString(), comparisonType); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool EqualsOrdinalIgnoreCase(ReadOnlySpan<char> span, ReadOnlySpan<char> other) { if (other.Length == 0) { return true; } return CompareToOrdinalIgnoreCase(span, other) == 0; } public static int CompareTo(this ReadOnlySpan<char> span, ReadOnlySpan<char> other, StringComparison comparisonType) { return comparisonType switch { StringComparison.Ordinal => span.SequenceCompareTo(other), StringComparison.OrdinalIgnoreCase => CompareToOrdinalIgnoreCase(span, other), _ => string.Compare(span.ToString(), other.ToString(), comparisonType), }; } private unsafe static int CompareToOrdinalIgnoreCase(ReadOnlySpan<char> strA, ReadOnlySpan<char> strB) { int num = Math.Min(strA.Length, strB.Length); int num2 = num; fixed (char* ptr = &MemoryMarshal.GetReference(strA)) { fixed (char* ptr3 = &MemoryMarshal.GetReference(strB)) { char* ptr2 = ptr; char* ptr4 = ptr3; while (num != 0 && *ptr2 <= '\u007f' && *ptr4 <= '\u007f') { int num3 = *ptr2; int num4 = *ptr4; if (num3 == num4) { ptr2++; ptr4++; num--; continue; } if ((uint)(num3 - 97) <= 25u) { num3 -= 32; } if ((uint)(num4 - 97) <= 25u) { num4 -= 32; } if (num3 != num4) { return num3 - num4; } ptr2++; ptr4++; num--; } if (num == 0) { return strA.Length - strB.Length; } num2 -= num; return string.Compare(strA.Slice(num2).ToString(), strB.Slice(num2).ToString(), StringComparison.OrdinalIgnoreCase); } } } public static int IndexOf(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType) { if (comparisonType == StringComparison.Ordinal) { return span.IndexOf(value); } return span.ToString().IndexOf(value.ToString(), comparisonType); } public static int ToLower(this ReadOnlySpan<char> source, Span<char> destination, CultureInfo culture) { System.ThrowHelper.ThrowIfArgumentNull(culture, System.ExceptionArgument.culture); if (destination.Length < source.Length) { return -1; } string str = source.ToString(); AsSpan(culture.TextInfo.ToLower(str)).CopyTo(destination); return source.Length; } public static int ToLowerInvariant(this ReadOnlySpan<char> source, Span<char> destination) { return source.ToLower(destination, CultureInfo.InvariantCulture); } public static int ToUpper(this ReadOnlySpan<char> source, Span<char> destination, CultureInfo culture) { System.ThrowHelper.ThrowIfArgumentNull(culture, System.ExceptionArgument.culture); if (destination.Length < source.Length) { return -1; } string str = source.ToString(); AsSpan(culture.TextInfo.ToUpper(str)).CopyTo(destination); return source.Length; } public static int ToUpperInvariant(this ReadOnlySpan<char> source, Span<char> destination) { return source.ToUpper(destination, CultureInfo.InvariantCulture); } public static bool EndsWith(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType) { switch (comparisonType) { case StringComparison.Ordinal: return span.EndsWith(value); case StringComparison.OrdinalIgnoreCase: if (value.Length <= span.Length) { return EqualsOrdinalIgnoreCase(span.Slice(span.Length - value.Length), value); } return false; default: { string text = span.ToString(); string value2 = value.ToString(); return text.EndsWith(value2, comparisonType); } } } public static bool StartsWith(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType) { switch (comparisonType) { case StringComparison.Ordinal: return span.StartsWith(value); case StringComparison.OrdinalIgnoreCase: if (value.Length <= span.Length) { return EqualsOrdinalIgnoreCase(span.Slice(0, value.Length), value); } return false; default: { string text = span.ToString(); string value2 = value.ToString(); return text.StartsWith(value2, comparisonType); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<char> AsSpan(this string? text) { if (text == null) { return default(ReadOnlySpan<char>); } return new ReadOnlySpan<char>(text, (IntPtr)RuntimeHelpers.OffsetToStringData, text.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<char> AsSpan(this string? text, int start) { if (text == null) { if (start != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return default(ReadOnlySpan<char>); } if ((uint)start > (uint)text.Length) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new ReadOnlySpan<char>(text, (nint)RuntimeHelpers.OffsetToStringData + (nint)(start * 2), text.Length - start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<char> AsSpan(this string? text, int start, int length) { if (text == null) { if (start != 0 || length != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return default(ReadOnlySpan<char>); } if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new ReadOnlySpan<char>(text, (nint)RuntimeHelpers.OffsetToStringData + (nint)(start * 2), length); } public static ReadOnlyMemory<char> AsMemory(this string? text) { if (text == null) { return default(ReadOnlyMemory<char>); } return new ReadOnlyMemory<char>(text, 0, text.Length); } public static ReadOnlyMemory<char> AsMemory(this string? text, int start) { if (text == null) { if (start != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return default(ReadOnlyMemory<char>); } if ((uint)start > (uint)text.Length) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new ReadOnlyMemory<char>(text, start, text.Length - start); } public static ReadOnlyMemory<char> AsMemory(this string? text, int start, int length) { if (text == null) { if (start != 0 || length != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return default(ReadOnlyMemory<char>); } if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new ReadOnlyMemory<char>(text, start, length); } } [DebuggerTypeProxy(typeof(System.MemoryDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] public readonly struct ReadOnlyMemory<T> { private readonly object? _object; private readonly int _index; private readonly int _length; internal const int RemoveFlagsBitMask = int.MaxValue; public static ReadOnlyMemory<T> Empty => default(ReadOnlyMemory<T>); public int Length => _length & 0x7FFFFFFF; public bool IsEmpty => (_length & 0x7FFFFFFF) == 0; public ReadOnlySpan<T> Span { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if (_index < 0) { return ((MemoryManager<T>)_object).GetSpan().Slice(_index & 0x7FFFFFFF, _length); } ReadOnlySpan<T> result; if (typeof(T) == typeof(char) && _object is string text) { result = new ReadOnlySpan<T>(text, (IntPtr)RuntimeHelpers.OffsetToStringData, text.Length); return result.Slice(_index, _length); } if (_object != null) { return new ReadOnlySpan<T>((T[])_object, _index, _length & 0x7FFFFFFF); } result = default(ReadOnlySpan<T>); return result; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory(T[]? array) { if (array == null) { this = default(ReadOnlyMemory<T>); return; } _object = array; _index = 0; _length = array.Length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory(T[]? array, int start, int length) { if (array == null) { if (start != 0 || length != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } this = default(ReadOnlyMemory<T>); return; } if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } _object = array; _index = start; _length = length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ReadOnlyMemory(object? obj, int start, int length) { _object = obj; _index = start; _length = length; } public static implicit operator ReadOnlyMemory<T>(T[]? array) { return new ReadOnlyMemory<T>(array); } public static implicit operator ReadOnlyMemory<T>(ArraySegment<T> segment) { return new ReadOnlyMemory<T>(segment.Array, segment.Offset, segment.Count); } public override string ToString() { if (typeof(T) == typeof(char)) { if (!(_object is string text)) { return Span.ToString(); } return text.Substring(_index, _length & 0x7FFFFFFF); } return $"System.ReadOnlyMemory<{typeof(T).Name}>[{_length & 0x7FFFFFFF}]"; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory<T> Slice(int start) { int length = _length; int num = length & 0x7FFFFFFF; if ((uint)start > (uint)num) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new ReadOnlyMemory<T>(_object, _index + start, length - start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory<T> Slice(int start, int length) { int length2 = _length; int num = _length & 0x7FFFFFFF; if ((uint)start > (uint)num || (uint)length > (uint)(num - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new ReadOnlyMemory<T>(_object, _index + start, length | (length2 & int.MinValue)); } public void CopyTo(Memory<T> destination) { Span.CopyTo(destination.Span); } public bool TryCopyTo(Memory<T> destination) { return Span.TryCopyTo(destination.Span); } public unsafe MemoryHandle Pin() { if (_index < 0) { return ((MemoryManager<T>)_object).Pin(_index & 0x7FFFFFFF); } if (typeof(T) == typeof(char) && _object is string value) { GCHandle handle = GCHandle.Alloc(value, GCHandleType.Pinned); return new MemoryHandle(Unsafe.Add<T>((void*)handle.AddrOfPinnedObject(), _index), handle); } if (_object is T[] array) { if (_length < 0) { return new MemoryHandle(Unsafe.Add<T>(Unsafe.AsPointer(ref MemoryMarshal.GetReference<T>(array)), _index)); } GCHandle handle2 = GCHandle.Alloc(array, GCHandleType.Pinned); return new MemoryHandle(Unsafe.Add<T>((void*)handle2.AddrOfPinnedObject(), _index), handle2); } return default(MemoryHandle); } public T[] ToArray() { return Span.ToArray(); } [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) { if (obj is ReadOnlyMemory<T> other) { return Equals(other); } if (obj is Memory<T> memory) { return Equals(memory); } return false; } public bool Equals(ReadOnlyMemory<T> other) { if (_object == other._object && _index == other._index) { return _length == other._length; } return false; } [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { if (_object == null) { return 0; } return HashCode.Combine(_object, _index, _length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal object? GetObjectStartLength(out int start, out int length) { start = _index; length = _length; return _object; } } [DebuggerTypeProxy(typeof(System.SpanDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] public readonly ref struct ReadOnlySpan<T> { public ref struct Enumerator { private readonly ReadOnlySpan<T> _span; private int _index; public ref readonly T Current { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return ref _span[_index]; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Enumerator(ReadOnlySpan<T> span) { _span = span; _index = -1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool MoveNext() { int num = _index + 1; if (num < _span.Length) { _index = num; return true; } return false; } } private readonly object? _pinnable; private readonly IntPtr _byteOffset; private readonly int _length; public int Length => _length; public bool IsEmpty => _length == 0; public static ReadOnlySpan<T> Empty => default(ReadOnlySpan<T>); public ref readonly T this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if ((uint)index >= (uint)_length) { System.ThrowHelper.ThrowIndexOutOfRangeException(); } return ref Unsafe.Add(ref DangerousGetPinnableReference(), index); } } internal object? Pinnable => _pinnable; internal IntPtr ByteOffset => _byteOffset; public static bool operator !=(ReadOnlySpan<T> left, ReadOnlySpan<T> right) { return !(left == right); } [Obsolete("Equals() on ReadOnlySpan will always throw an exception. Use == instead.")] [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) { throw new NotSupportedException("Cannot call Equals on Span"); } [Obsolete("GetHashCode() on ReadOnlySpan will always throw an exception.")] [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { throw new NotSupportedException("Cannot call GetHashCodee on Span"); } public static implicit operator ReadOnlySpan<T>(T[]? array) { return new ReadOnlySpan<T>(array); } public static implicit operator ReadOnlySpan<T>(ArraySegment<T> segment) { return new ReadOnlySpan<T>(segment.Array ?? throw new ArgumentNullException("segment"), segment.Offset, segment.Count); } public Enumerator GetEnumerator() { return new Enumerator(this); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan(T[]? array) { if (array == null) { this = default(ReadOnlySpan<T>); return; } _length = array.Length; _pinnable = array; _byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan(T[]? array, int start, int length) { if (array == null) { if (start != 0 || length != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } this = default(ReadOnlySpan<T>); return; } if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } _length = length; _pinnable = array; _byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public unsafe ReadOnlySpan(void* pointer, int length) { if (System.SpanHelpers.IsReferenceOrContainsReferences<T>()) { System.ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T)); } if (length < 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } _length = length; _pinnable = null; _byteOffset = new IntPtr(pointer); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ReadOnlySpan(object? pinnable, IntPtr byteOffset, int length) { _length = length; _pinnable = pinnable; _byteOffset = byteOffset; } [EditorBrowsable(EditorBrowsableState.Never)] public unsafe ref readonly T GetPinnableReference() { if (_length != 0) { return ref DangerousGetPinnableReference(); } return ref Unsafe.AsRef<T>(null); } public void CopyTo(Span<T> destination) { if (!TryCopyTo(destination)) { System.ThrowHelper.ThrowArgumentException_DestinationTooShort(); } } public bool TryCopyTo(Span<T> destination) { int length = _length; int length2 = destination.Length; if (length == 0) { return true; } if ((uint)length > (uint)length2) { return false; } ref T src = ref DangerousGetPinnableReference(); System.SpanHelpers.CopyTo(ref destination.DangerousGetPinnableReference(), length2, ref src, length); return true; } public static bool operator ==(ReadOnlySpan<T> left, ReadOnlySpan<T> right) { if (left._length == right._length) { return Unsafe.AreSame(ref left.DangerousGetPinnableReference(), ref right.DangerousGetPinnableReference()); } return false; } public unsafe override string ToString() { if (typeof(T) == typeof(char)) { if (_byteOffset == (IntPtr)RuntimeHelpers.OffsetToStringData && Unsafe.As<object>(_pinnable) is string text && _length == text.Length) { return text; } fixed (char* value = &Unsafe.As<T, char>(ref DangerousGetPinnableReference())) { return new string(value, 0, _length); } } return $"System.ReadOnlySpan<{typeof(T).Name}>[{_length}]"; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan<T> Slice(int start) { if ((uint)start > (uint)_length) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } IntPtr byteOffset = _byteOffset.Add<T>(start); int length = _length - start; return new ReadOnlySpan<T>(_pinnable, byteOffset, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan<T> Slice(int start, int length) { if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } IntPtr byteOffset = _byteOffset.Add<T>(start); return new ReadOnlySpan<T>(_pinnable, byteOffset, length); } public T[] ToArray() { if (_length == 0) { return System.SpanHelpers.PerTypeValues<T>.EmptyArray; } T[] array = new T[_length]; CopyTo(array); return array; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ref T DangerousGetPinnableReference() { return ref Unsafe.AddByteOffset(ref ILHelpers.ObjectAsRef<T>(_pinnable), _byteOffset); } } [DebuggerTypeProxy(typeof(System.SpanDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] public readonly ref struct Span<T> { public ref struct Enumerator { private readonly Span<T> _span; private int _index; public ref T Current { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return ref _span[_index]; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Enumerator(Span<T> span) { _span = span; _index = -1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool MoveNext() { int num = _index + 1; if (num < _span.Length) { _index = num; return true; } return false; } } private readonly object? _pinnable; private readonly IntPtr _byteOffset; private readonly int _length; public int Length => _length; public bool IsEmpty => _length == 0; public static Span<T> Empty => default(Span<T>); public ref T this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if ((uint)index >= (uint)_length) { System.ThrowHelper.ThrowIndexOutOfRangeException(); } return ref Unsafe.Add(ref DangerousGetPinnableReference(), index); } } internal object? Pinnable => _pinnable; internal IntPtr ByteOffset => _byteOffset; public static bool operator !=(Span<T> left, Span<T> right) { return !(left == right); } [Obsolete("Equals() on Span will always throw an exception. Use == instead.")] [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) { throw new NotSupportedException("Cannot call Equals on Span"); } [Obsolete("GetHashCode() on Span will always throw an exception.")] [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { throw new NotSupportedException("Cannot call GetHashCode on Span"); } public static implicit operator Span<T>(T[]? array) { return new Span<T>(array); } public static implicit operator Span<T>(ArraySegment<T> segment) { return new Span<T>(segment.Array, segment.Offset, segment.Count); } public Enumerator GetEnumerator() { return new Enumerator(this); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span(T[]? array) { if (array == null) { this = default(Span<T>); return; } if (default(T) == null && array.GetType() != typeof(T[])) { System.ThrowHelper.ThrowArrayTypeMismatchException(); } _length = array.Length; _pinnable = array; _byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static Span<T> Create(T[]? array, int start) { if (array == null) { if (start != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return default(Span<T>); } if (default(T) == null && array.GetType() != typeof(T[])) { System.ThrowHelper.ThrowArrayTypeMismatchException(); } if ((uint)start > (uint)array.Length) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } IntPtr byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start); int length = array.Length - start; return new Span<T>(array, byteOffset, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span(T[]? array, int start, int length) { if (array == null) { if (start != 0 || length != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } this = default(Span<T>); return; } if (default(T) == null && array.GetType() != typeof(T[])) { System.ThrowHelper.ThrowArrayTypeMismatchException(); } if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } _length = length; _pinnable = array; _byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public unsafe Span(void* pointer, int length) { if (System.SpanHelpers.IsReferenceOrContainsReferences<T>()) { System.ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T)); } if (length < 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } _length = length; _pinnable = null; _byteOffset = new IntPtr(pointer); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Span(object? pinnable, IntPtr byteOffset, int length) { _length = length; _pinnable = pinnable; _byteOffset = byteOffset; } [EditorBrowsable(EditorBrowsableState.Never)] public ref T GetPinnableReference() { if (_length != 0) { return ref DangerousGetPinnableReference(); } return ref Unsafe.NullRef<T>(); } public unsafe void Clear() { int length = _length; if (length == 0) { return; } nuint byteLength = (UIntPtr)(ulong)((uint)length * Unsafe.SizeOf<T>()); if ((Unsafe.SizeOf<T>() & (sizeof(IntPtr) - 1)) != 0) { if (_pinnable == null) { IntPtr byteOffset = _byteOffset; byte* ptr = (byte*)byteOffset.ToPointer(); System.SpanHelpers.ClearLessThanPointerSized(ptr, byteLength); } else { System.SpanHelpers.ClearLessThanPointerSized(ref Unsafe.As<T, byte>(ref DangerousGetPinnableReference()), byteLength); } } else if (System.SpanHelpers.IsReferenceOrContainsReferences<T>()) { nuint pointerSizeLength = (UIntPtr)(ulong)(length * Unsafe.SizeOf<T>() / sizeof(IntPtr)); System.SpanHelpers.ClearPointerSizedWithReferences(ref Unsafe.As<T, IntPtr>(ref DangerousGetPinnableReference()), pointerSizeLength); } else { System.SpanHelpers.ClearPointerSizedWithoutReferences(ref Unsafe.As<T, byte>(ref DangerousGetPinnableReference()), byteLength); } } public void Fill(T value) { int length = _length; if (length == 0) { return; } if (Unsafe.SizeOf<T>() == 1) { byte value2 = Unsafe.As<T, byte>(ref value); Unsafe.InitBlockUnaligned(ref Unsafe.As<T, byte>(ref DangerousGetPinnableReference()), value2, (uint)length); return; } ref T source = ref DangerousGetPinnableReference(); int i; for (i = 0; i < (length & -8); i += 8) { Unsafe.Add(ref source, i) = value; Unsafe.Add(ref source, i + 1) = value; Unsafe.Add(ref source, i + 2) = value; Unsafe.Add(ref source, i + 3) = value; Unsafe.Add(ref source, i + 4) = value; Unsafe.Add(ref source, i + 5) = value; Unsafe.Add(ref source, i + 6) = value; Unsafe.Add(ref source, i + 7) = value; } if (i < (length & -4)) { Unsafe.Add(ref source, i) = value; Unsafe.Add(ref source, i + 1) = value; Unsafe.Add(ref source, i + 2) = value; Unsafe.Add(ref source, i + 3) = value; i += 4; } for (; i < length; i++) { Unsafe.Add(ref source, i) = value; } } public void CopyTo(Span<T> destination) { if (!TryCopyTo(destination)) { System.ThrowHelper.ThrowArgumentException_DestinationTooShort(); } } public bool TryCopyTo(Span<T> destination) { int length = _length; int length2 = destination._length; if (length == 0) { return true; } if ((uint)length > (uint)length2) { return false; } ref T src = ref DangerousGetPinnableReference(); System.SpanHelpers.CopyTo(ref destination.DangerousGetPinnableReference(), length2, ref src, length); return true; } public static bool operator ==(Span<T> left, Span<T> right) { if (left._length == right._length) { return Unsafe.AreSame(ref left.DangerousGetPinnableReference(), ref right.DangerousGetPinnableReference()); } return false; } public static implicit operator ReadOnlySpan<T>(Span<T> span) { return new ReadOnlySpan<T>(span._pinnable, span._byteOffset, span._length); } public unsafe override string ToString() { if (typeof(T) == typeof(char)) { fixed (char* value = &Unsafe.As<T, char>(ref DangerousGetPinnableReference())) { return new string(value, 0, _length); } } return $"System.Span<{typeof(T).Name}>[{_length}]"; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<T> Slice(int start) { if ((uint)start > (uint)_length) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } IntPtr byteOffset = _byteOffset.Add<T>(start); int length = _length - start; return new Span<T>(_pinnable, byteOffset, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<T> Slice(int start, int length) { if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } IntPtr byteOffset = _byteOffset.Add<T>(start); return new Span<T>(_pinnable, byteOffset, length); } public T[] ToArray() { if (_length == 0) { return System.SpanHelpers.PerTypeValues<T>.EmptyArray; } T[] array = new T[_length]; CopyTo(array); return array; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ref T DangerousGetPinnableReference() { return ref Unsafe.AddByteOffset(ref ILHelpers.ObjectAsRef<T>(_pinnable), _byteOffset); } } internal sealed class SpanDebugView<T> { private readonly T[] _array; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items => _array; public SpanDebugView(Span<T> span) { _array = span.ToArray(); } public SpanDebugView(ReadOnlySpan<T> span) { _array = span.ToArray(); } } internal static class SpanHelpers { internal struct ComparerComparable<T, TComparer> : IComparable<T> where TComparer : IComparer<T> { private readonly T _value; private readonly TComparer _comparer; public ComparerComparable(T value, TComparer comparer) { _value = value; _comparer = comparer; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public int CompareTo(T? other) { return _comparer.Compare(_value, other); } } [StructLayout(LayoutKind.Sequential, Size = 64)] private struct Reg64 { } [StructLayout(LayoutKind.Sequential, Size = 32)] private struct Reg32 { } [StructLayout(LayoutKind.Sequential, Size = 16)] private struct Reg16 { } public static class PerTypeValues<T> { public static readonly bool IsReferenceOrContainsReferences = IsReferenceOrContainsReferencesCore(typeof(T)); public static readonly T[] EmptyArray = ArrayEx.Empty<T>(); public static readonly IntPtr ArrayAdjustment = MeasureArrayAdjustment(); private static IntPtr MeasureArrayAdjustment() { T[] array = new T[1]; return Unsafe.ByteOffset(ref ILHelpers.ObjectAsRef<T>((object)array), ref array[0]); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T, TComparable>(this ReadOnlySpan<T> span, TComparable comparable) where TComparable : IComparable<T> { if (comparable == null) { System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.comparable); } return BinarySearch(ref MemoryMarshal.GetReference(span), span.Length, comparable); } public static int BinarySearch<T, TComparable>(ref T spanStart, int length, TComparable comparable) where TComparable : IComparable<T> { int num = 0; int num2 = length - 1; while (num <= num2) { int num3 = num2 + num >>> 1; ref TComparable reference = ref comparable; TComparable val = default(TComparable); if (val == null) { val = reference; reference = ref val; } int num4 = reference.CompareTo(Unsafe.Add(ref spanStart, num3)); if (num4 == 0) { return num3; } if (num4 > 0) { num = num3 + 1; } else { num2 = num3 - 1; } } return ~num; } public static int IndexOf(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength) { if (valueLength == 0) { return 0; } byte value2 = value; ref byte second = ref Unsafe.Add(ref value, 1); int num = valueLength - 1; int num2 = 0; while (true) { int num3 = searchSpaceLength - num2 - num; if (num3 <= 0) { break; } int num4 = IndexOf(ref Unsafe.Add(ref searchSpace, num2), value2, num3); if (num4 == -1) { break; } num2 += num4; if (SequenceEqual(ref Unsafe.Add(ref searchSpace, num2 + 1), ref second, num)) { return num2; } num2++; } return -1; } public static int IndexOfAny(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength) { if (valueLength == 0) { return 0; } int num = -1; for (int i = 0; i < valueLength; i++) { int num2 = IndexOf(ref searchSpace, Unsafe.Add(ref value, i), searchSpaceLength); if ((uint)num2 < (uint)num) { num = num2; searchSpaceLength = num2; if (num == 0) { break; } } } return num; } public static int LastIndexOfAny(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength) { if (valueLength == 0) { return 0; } int num = -1; for (int i = 0; i < valueLength; i++) { int num2 = LastIndexOf(ref searchSpace, Unsafe.Add(ref value, i), searchSpaceLength); if (num2 > num) { num = num2; } } return num; } public static int IndexOf(ref byte searchSpace, byte value, int length) { nint num = 0; nint num2 = length; while (true) { if ((nuint)num2 >= (nuint)8u) { num2 -= 8; if (value != Unsafe.AddByteOffset(ref searchSpace, num)) { if (value == Unsafe.AddByteOffset(ref searchSpace, num + 1)) { goto IL_0109; } if (value == Unsafe.AddByteOffset(ref searchSpace, num + 2)) { goto IL_010f; } if (value != Unsafe.AddByteOffset(ref searchSpace, num + 3)) { if (value != Unsafe.AddByteOffset(ref searchSpace, num + 4)) { if (value != Unsafe.AddByteOffset(ref searchSpace, num + 5)) { if (value != Unsafe.AddByteOffset(ref searchSpace, num + 6)) { if (value == Unsafe.AddByteOffset(ref searchSpace, num + 7)) { break; } num += 8; continue; } return (int)(num + 6); } return (int)(num + 5); } return (int)(num + 4); } goto IL_0115; } } else { if ((nuint)num2 >= (nuint)4u) { num2 -= 4; if (value == Unsafe.AddByteOffset(ref searchSpace, num)) { goto IL_0106; } if (value == Unsafe.AddByteOffset(ref searchSpace, num + 1)) { goto IL_0109; } if (value == Unsafe.AddByteOffset(ref searchSpace, num + 2)) { goto IL_010f; } if (value == Unsafe.AddByteOffset(ref searchSpace, num + 3)) { goto IL_0115; } num += 4; } while (true) { if (num2 != 0) { num2--; if (value == Unsafe.AddByteOffset(ref searchSpace, num)) { break; } num++; continue; } return -1; } } goto IL_0106; IL_010f: return (int)(num + 2); IL_0106: return (int)num; IL_0109: return (int)(num + 1); IL_0115: return (int)(num + 3); } return (int)(num + 7); } public static int LastIndexOf(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength) { if (valueLength == 0) { return 0; } byte value2 = value; ref byte second = ref Unsafe.Add(ref value, 1); int num = valueLength - 1; int num2 = 0; while (true) { int num3 = searchSpaceLength - num2 - num; if (num3 <= 0) { break; } int num4 = LastIndexOf(ref searchSpace, value2, num3); if (num4 == -1) { break; } if (SequenceEqual(ref Unsafe.Add(ref searchSpace, num4 + 1), ref second, num)) { return num4; } num2 += num3 - num4; } return -1; } public static int LastIndexOf(ref byte searchSpace, byte value, int length) { nint num = length; nint num2 = length; while (true) { if ((nuint)num2 >= (nuint)8u) { num2 -= 8; num -= 8; if (value == Unsafe.AddByteOffset(ref searchSpace, num + 7)) { break; } if (value == Unsafe.AddByteOffset(ref searchSpace, num + 6)) { return (int)(num + 6); } if (value == Unsafe.AddByteOffset(ref searchSpace, num + 5)) { return (int)(num + 5); } if (value == Unsafe.AddByteOffset(ref searchSpace, num + 4)) { return (int)(num + 4); } if (value == Unsafe.AddByteOffset(ref searchSpace, num + 3)) { goto IL_010f; } if (value == Unsafe.AddByteOffset(ref searchSpace, num + 2)) { goto IL_0109; } if (value == Unsafe.AddByteOffset(ref searchSpace, num + 1)) { goto IL_0103; } if (value != Unsafe.AddByteOffset(ref searchSpace, num)) { continue; } } else { if ((nuint)num2 >= (nuint)4u) { num2 -= 4; num -= 4; if (value == Unsafe.AddByteOffset(ref searchSpace, num + 3)) { goto IL_010f; } if (value == Unsafe.AddByteOffset(ref searchSpace, num + 2)) { goto IL_0109; } if (value == Unsafe.AddByteOffset(ref searchSpace, num + 1)) { goto IL_0103; } if (value == Unsafe.AddByteOffset(ref searchSpace, num)) { goto IL_0100; } } do { if (num2 != 0) { num2--; num--; continue; } return -1; } while (value != Unsafe.AddByteOffset(ref searchSpace, num)); } goto IL_0100; IL_0109: return (int)(num + 2); IL_010f: return (int)(num + 3); IL_0103: return (int)(num + 1); IL_0100: return (int)num; } return (int)(num + 7); } public static int IndexOfAny(ref byte searchSpace, byte value0, byte value1, int length) { nint num = 0; nint num2 = length; while (true) { if ((nuint)num2 >= (nuint)8u) { num2 -= 8; uint num3 = Unsafe.AddByteOffset(ref searchSpace, num); if (value0 != num3 && value1 != num3) { num3 = Unsafe.AddByteOffset(ref searchSpace, num + 1); if (value0 == num3 || value1 == num3) { goto IL_019b; } num3 = Unsafe.AddByteOffset(ref searchSpace, num + 2); if (value0 == num3 || value1 == num3) { goto IL_01a1; } num3 = Unsafe.AddByteOffset(ref searchSpace, num + 3); if (value0 != num3 && value1 != num3) { num3 = Unsafe.AddByteOffset(ref searchSpace, num + 4); if (value0 != num3 && value1 != num3) { num3 = Unsafe.AddByteOffset(ref searchSpace, num + 5); if (value0 != num3 && value1 != num3) { num3 = Unsafe.AddByteOffset(ref searchSpace, num + 6); if (value0 != num3 && value1 != num3) { num3 = Unsafe.AddByteOffset(ref searchSpace, num + 7); if (value0 == num3 || value1 == num3) { break; } num += 8; continue; } return (int)(num + 6); } return (int)(num + 5); } return (int)(num + 4); } goto IL_01a7; } } else { if ((nuint)num2 >= (nuint)4u) { num2 -= 4; uint num3 = Unsafe.AddByteOffset(ref searchSpace, num); if (value0 == num3 || value1 == num3) { goto IL_0198; } num3 = Unsafe.AddByteOffset(ref searchSpace, num + 1); if (value0 == num3 || value1 == num3) { goto IL_019b; } num3 = Unsafe.AddByteOffset(ref searchSpace, num + 2); if (value0 == num3 || value1 == num3) { goto IL_01a1; } num3 = Unsafe.AddByteOffset(ref searchSpace, num + 3); if (value0 == num3 || value1 == num3) { goto IL_01a7; } num += 4; } while (true) { if (num2 != 0) { num2--; uint num3 = Unsafe.AddByteOffset(ref searchSpace, num); if (value0 == num3 || value1 == num3) { break; } num++; continue; } return -1; } } goto IL_0198; IL_01a1: return (int)(num + 2); IL_019b: return (int)(num + 1); IL_01a7: return (int)(num + 3); IL_0198: return (int)num; } return (int)(num + 7); } public static int IndexOfAny(ref byte searchSpace, byte value0, byte value1, byte value2, int length) { nint num = 0; nint num2 = length; while (true) { if ((nuint)num2 >= (nuint)8u) { num2 -= 8; uint num3 = Unsafe.AddByteOffset(ref searchSpace, num); if (value0 != num3 && value1 != num3 && value2 != num3) { num3 = Unsafe.AddByteOffset(ref searchSpace, num + 1); if (value0 == num3 || value1 == num3 || value2 == num3) { goto IL_020a; } num3 = Unsafe.AddByteOffset(ref searchSpace, num + 2); if (value0 == num3 || value1 == num3 || value2 == num3) { goto IL_0210; } num3 = Unsafe.AddByteOffset(ref searchSpace, num + 3); if (value0 != num3 && value1 != num3 && value2 != num3) { num3 = Unsafe.AddByteOffset(ref searchSpace, num + 4); if (value0 != num3 && value1 != num3 && value2 != num3) { num3 = Unsafe.AddByteOffset(ref searchSpace, num + 5); if (value0 != num3 && value1 != num3 && value2 != num3) { num3 = Unsafe.AddByteOffset(ref searchSpace, num + 6); if (value0 != num3 && value1 != num3 && value2 != num3) { num3 = Unsafe.AddByteOffset(ref searchSpace, num + 7); if (value0 == num3 || value1 == num3 || value2 == num3) { break; } num += 8; continue; } return (int)(num + 6); } return (int)(num + 5); } return (int)(num + 4); } goto IL_0216; } } else { if ((nuint)num2 >= (nuint)4u) { num2 -= 4; uint num3 = Unsafe.AddByteOffset(ref searchSpace, num); if (value0 == num3 || value1 == num3 || value2 == num3) { goto IL_0207; } num3 = Unsafe.AddByteOffset(ref searchSpace, num + 1); if (value0 == num3 || value1 == num3 || value2 == num3) { goto IL_020a; } num3 = Unsafe.AddByteOffset(ref searchSpace, num + 2); if (value0 == num3 || value1 == num3 || value2 == num3) { goto IL_0210; } num3 = Unsafe.AddByteOffset(ref searchSpace, num + 3); if (value0 == num3 || value1 == num3 || value2 == num3) { goto IL_0216; } num += 4; } while (true) { if (num2 != 0) { num2--; uint num3 = Unsafe.AddByteOffset(ref searchSpace, num); if (value0 == num3 || value1 == num3 || value2 == num3) { break; } num++; continue; } return -1; } } goto IL_0207; IL_0207: return (int)num; IL_0210: return (int)(num + 2); IL_020a: return (int)(num + 1); IL_0216: return (int)(num + 3); } return (int)(num + 7); } public static int LastIndexOfAny(ref byte searchSpace, byte value0, byte value1, int length) { nint num = length; nint num2 = length; while (true) { if ((nuint)num2 >= (nuint)8u) { num2 -= 8; num -= 8; uint num3 = Unsafe.AddByteOffset(ref searchSpace, num + 7); if (value0 == num3 || value1 == num3) { break; } num3 = Unsafe.AddByteOffset(ref searchSpace, num + 6); if (value0 == num3 || value1 == nu
BepInEx/patchers/MonoMod.ILHelpers.dll
Decompiled 3 months agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using Microsoft.CodeAnalysis; [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: AssemblyCopyright("Copyright 2024 0x0ade, DaNike")] [assembly: CLSCompliant(false)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: AssemblyFileVersion("1.1.0.0")] [assembly: AssemblyInformationalVersion("1.1.0")] [assembly: AssemblyTitle("MonoMod.ILHelpers")] [assembly: AssemblyCompany("0x0ade, DaNike")] [assembly: AssemblyDescription("Package Description")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyVersion("1.1.0.0")] [assembly: TypeForwardedTo(typeof(Unsafe))] namespace System.Runtime.Versioning { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class NonVersionableAttribute : Attribute { } } namespace System.Runtime.CompilerServices { internal sealed class IsReadOnlyAttribute : Attribute { } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [Microsoft.CodeAnalysis.Embedded] [CompilerGenerated] [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[] A_0) { TransformFlags = A_0; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] [Microsoft.CodeAnalysis.Embedded] [CompilerGenerated] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte A_0) { NullableFlags = new byte[1] { A_0 }; } public NullableAttribute(byte[] A_0) { NullableFlags = A_0; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte A_0) { Flag = A_0; } } } namespace MonoMod { public static class ILHelpers { [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static T TailCallDelegatePtr<T>(IntPtr source) { return ((delegate*<T>)source)(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T TailCallFunc<T>(Func<T> func) { return func(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static ref T ObjectAsRef<T>(object obj) { fixed (object obj2 = obj) { T** ptr = (T**)(&obj2); return ref *(*ptr); } } } } namespace MonoMod.Backports.ILHelpers { public static class UnsafeRaw { [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static T Read<T>(void* source) { return System.Runtime.CompilerServices.Unsafe.Read<T>(source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static T ReadUnaligned<T>(void* source) { return System.Runtime.CompilerServices.Unsafe.ReadUnaligned<T>(source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static T ReadUnaligned<T>(ref byte source) { return System.Runtime.CompilerServices.Unsafe.ReadUnaligned<T>(ref source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void Write<T>(void* destination, T value) { System.Runtime.CompilerServices.Unsafe.Write(destination, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void WriteUnaligned<T>(void* destination, T value) { System.Runtime.CompilerServices.Unsafe.WriteUnaligned(destination, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void WriteUnaligned<T>(ref byte destination, T value) { System.Runtime.CompilerServices.Unsafe.WriteUnaligned(ref destination, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void Copy<T>(void* destination, ref T source) { System.Runtime.CompilerServices.Unsafe.Write(destination, source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void Copy<T>(ref T destination, void* source) { destination = System.Runtime.CompilerServices.Unsafe.Read<T>(source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void* AsPointer<T>(ref T value) { return System.Runtime.CompilerServices.Unsafe.AsPointer(ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void SkipInit<T>(out T value) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static int SizeOf<T>() { return System.Runtime.CompilerServices.Unsafe.SizeOf<T>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void CopyBlock(void* destination, void* source, uint byteCount) { // IL cpblk instruction System.Runtime.CompilerServices.Unsafe.CopyBlock(destination, source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void CopyBlock(ref byte destination, ref byte source, uint byteCount) { // IL cpblk instruction System.Runtime.CompilerServices.Unsafe.CopyBlock(ref destination, ref source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void CopyBlockUnaligned(void* destination, void* source, uint byteCount) { // IL cpblk instruction System.Runtime.CompilerServices.Unsafe.CopyBlockUnaligned(destination, source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void CopyBlockUnaligned(ref byte destination, ref byte source, uint byteCount) { // IL cpblk instruction System.Runtime.CompilerServices.Unsafe.CopyBlockUnaligned(ref destination, ref source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void InitBlock(void* startAddress, byte value, uint byteCount) { // IL initblk instruction System.Runtime.CompilerServices.Unsafe.InitBlock(startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void InitBlock(ref byte startAddress, byte value, uint byteCount) { // IL initblk instruction System.Runtime.CompilerServices.Unsafe.InitBlock(ref startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void InitBlockUnaligned(void* startAddress, byte value, uint byteCount) { // IL initblk instruction System.Runtime.CompilerServices.Unsafe.InitBlockUnaligned(startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void InitBlockUnaligned(ref byte startAddress, byte value, uint byteCount) { // IL initblk instruction System.Runtime.CompilerServices.Unsafe.InitBlockUnaligned(ref startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static T As<T>(object o) where T : class { return (T)o; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static ref T AsRef<T>(void* source) { return ref *(T*)source; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T AsRef<T>(in T source) { return ref source; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref TTo As<TFrom, TTo>(ref TFrom source) { return ref System.Runtime.CompilerServices.Unsafe.As<TFrom, TTo>(ref source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Unbox<T>(object box) where T : struct { return ref (T)box; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Add<T>(ref T source, int elementOffset) { return ref System.Runtime.CompilerServices.Unsafe.Add(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void* Add<T>(void* source, int elementOffset) { return (byte*)source + (nint)elementOffset * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<T>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Add<T>(ref T source, nint elementOffset) { return ref System.Runtime.CompilerServices.Unsafe.Add(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Add<T>(ref T source, nuint elementOffset) { return ref System.Runtime.CompilerServices.Unsafe.Add(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T AddByteOffset<T>(ref T source, nint byteOffset) { return ref System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref source, byteOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T AddByteOffset<T>(ref T source, nuint byteOffset) { return ref System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref source, byteOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Subtract<T>(ref T source, int elementOffset) { return ref System.Runtime.CompilerServices.Unsafe.Subtract(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void* Subtract<T>(void* source, int elementOffset) { return (byte*)source - (nint)elementOffset * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<T>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Subtract<T>(ref T source, nint elementOffset) { return ref System.Runtime.CompilerServices.Unsafe.Subtract(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Subtract<T>(ref T source, nuint elementOffset) { return ref System.Runtime.CompilerServices.Unsafe.Subtract(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T SubtractByteOffset<T>(ref T source, nint byteOffset) { return ref System.Runtime.CompilerServices.Unsafe.SubtractByteOffset(ref source, byteOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T SubtractByteOffset<T>(ref T source, nuint byteOffset) { return ref System.Runtime.CompilerServices.Unsafe.SubtractByteOffset(ref source, byteOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static nint ByteOffset<T>(ref T origin, ref T target) { return System.Runtime.CompilerServices.Unsafe.ByteOffset(target: ref target, origin: ref origin); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static bool AreSame<T>(ref T left, ref T right) { return System.Runtime.CompilerServices.Unsafe.AreSame(ref left, ref right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static bool IsAddressGreaterThan<T>(ref T left, ref T right) { return System.Runtime.CompilerServices.Unsafe.IsAddressGreaterThan(ref left, ref right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static bool IsAddressLessThan<T>(ref T left, ref T right) { return System.Runtime.CompilerServices.Unsafe.IsAddressLessThan(ref left, ref right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static bool IsNullRef<T>(ref T source) { return System.Runtime.CompilerServices.Unsafe.AsPointer(ref source) == null; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static ref T NullRef<T>() { return ref *(T*)null; } } }
BepInEx/plugins/EnhancedPrefabLoader.dll
Decompiled 3 months agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using EnhancedPrefabLoader; using EnhancedPrefabLoader.Extensions; using EnhancedPrefabLoader.Intercepters; using EnhancedPrefabLoader.Models; using HarmonyLib; using Microsoft.CodeAnalysis; using Newtonsoft.Json; using Scripts; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.Video; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")] [assembly: IgnoresAccessChecksTo("Assembly-CSharp")] [assembly: AssemblyCompany("EnhancedPrefabLoader")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("2.0.0.0")] [assembly: AssemblyInformationalVersion("2.0.0+40cdc7df25d66bcd28939d889a9240738f060bdd")] [assembly: AssemblyProduct("Enhanced Prefab Loader")] [assembly: AssemblyTitle("EnhancedPrefabLoader")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("2.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } internal sealed class ConfigurationManagerAttributes { public delegate void CustomHotkeyDrawerFunc(ConfigEntryBase setting, ref bool isCurrentlyAcceptingInput); public bool? ShowRangeAsPercent; public Action<ConfigEntryBase> CustomDrawer; public CustomHotkeyDrawerFunc CustomHotkeyDrawer; public bool? Browsable; public string Category; public object DefaultValue; public bool? HideDefaultButton; public bool? HideSettingName; public string Description; public string DispName; public int? Order; public bool? ReadOnly; public bool? IsAdvanced; public Func<object, string> ObjToStr; public Func<string, object> StrToObj; } [HarmonyPatch(typeof(CGameManager))] public class CGameManagerPatch { [HarmonyPatch("SaveGameData")] [HarmonyPrefix] private static void SaveGameDataPrefix(int saveSlotIndex) { string contents = JsonConvert.SerializeObject((object)AssetData.ItemSaveData); if (!Directory.Exists(Plugin.m_BaseDirectory + "/Saves")) { Directory.CreateDirectory(Plugin.m_BaseDirectory + "/Saves"); } File.WriteAllText(string.Format("{0}/Saves/{1}_{2}", Plugin.m_BaseDirectory, "EnhancedPrefabLoader", saveSlotIndex), contents); } } namespace EnhancedPrefabLoader { public class AssetBundleLoader : CSingleton<AssetBundleLoader> { [CompilerGenerated] private sealed class <>c__DisplayClass1_0 { public FileInfo fileInfo; public AssetBundleLoader <>4__this; internal void <LoadAssetBundlesAsync>b__0(AsyncOperation operation) { AssetBundleCreateRequest val = (AssetBundleCreateRequest)(object)((operation is AssetBundleCreateRequest) ? operation : null); if (val != null) { <>4__this.Logger.LogDebug((object)("Bundle loaded: " + Path.GetFileNameWithoutExtension(fileInfo.Name) + ". Starting Processing.")); ((MonoBehaviour)<>4__this).StartCoroutine(<>4__this.ProcessAssetBundleAsync(val.assetBundle, fileInfo)); } } } [CompilerGenerated] private sealed class <>c__DisplayClass2_0 { public VideoClipInfo videoClipInfo; internal bool <ProcessAssetBundleAsync>b__0(Component component) { return ((Object)component).name == videoClipInfo.VideoPlayerName; } } [CompilerGenerated] private sealed class <LoadAssetBundlesAsync>d__1 : IEnumerator<object>, IDisposable, IEnumerator { private int <>1__state; private object <>2__current; public AssetBundleLoader <>4__this; public IEnumerable<string> files; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <LoadAssetBundlesAsync>d__1(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { int num = <>1__state; AssetBundleLoader assetBundleLoader = <>4__this; if (num != 0) { return false; } <>1__state = -1; if (!assetBundleLoader.IsLoaded) { foreach (string file in files) { <>c__DisplayClass1_0 CS$<>8__locals0 = new <>c__DisplayClass1_0 { <>4__this = assetBundleLoader, fileInfo = new FileInfo(file) }; assetBundleLoader.Logger.LogDebug((object)("Loading assets from asset bundle: " + Path.GetFileNameWithoutExtension(CS$<>8__locals0.fileInfo.Name))); ((AsyncOperation)AssetBundle.LoadFromFileAsync(CS$<>8__locals0.fileInfo.Directory.FullName + "/" + Path.GetFileNameWithoutExtension(CS$<>8__locals0.fileInfo.Name))).completed += delegate(AsyncOperation operation) { AssetBundleCreateRequest val = (AssetBundleCreateRequest)(object)((operation is AssetBundleCreateRequest) ? operation : null); if (val != null) { CS$<>8__locals0.<>4__this.Logger.LogDebug((object)("Bundle loaded: " + Path.GetFileNameWithoutExtension(CS$<>8__locals0.fileInfo.Name) + ". Starting Processing.")); ((MonoBehaviour)CS$<>8__locals0.<>4__this).StartCoroutine(CS$<>8__locals0.<>4__this.ProcessAssetBundleAsync(val.assetBundle, CS$<>8__locals0.fileInfo)); } }; } } return false; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } [CompilerGenerated] private sealed class <ProcessAssetBundleAsync>d__2 : IEnumerator<object>, IDisposable, IEnumerator { private int <>1__state; private object <>2__current; public FileInfo fileInfo; public AssetBundleLoader <>4__this; public AssetBundle assetBundle; private AssetBundleInfo <assetBundleInfo>5__2; private List<SpriteInfo>.Enumerator <>7__wrap2; private SpriteInfo <sprite>5__4; private AssetBundleRequest <assetLoadRequest>5__5; private List<PrefabInfo>.Enumerator <>7__wrap5; private PrefabInfo <prefabInfo>5__7; private EObjectType <objectType>5__8; private List<ItemInfo>.Enumerator <>7__wrap8; private ItemInfo <item>5__10; private EItemType <itemType>5__11; private ItemMeshData <itemMeshData>5__12; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <ProcessAssetBundleAsync>d__2(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { switch (<>1__state) { case -3: case 1: try { } finally { <>m__Finally1(); } break; case -4: case 2: try { } finally { <>m__Finally2(); } break; case -5: case 3: case 4: try { } finally { <>m__Finally3(); } break; } <assetBundleInfo>5__2 = null; <>7__wrap2 = default(List<SpriteInfo>.Enumerator); <sprite>5__4 = null; <assetLoadRequest>5__5 = null; <>7__wrap5 = default(List<PrefabInfo>.Enumerator); <prefabInfo>5__7 = null; <>7__wrap8 = default(List<ItemInfo>.Enumerator); <item>5__10 = null; <itemMeshData>5__12 = null; <>1__state = -2; } private bool MoveNext() { //IL_05d3: Unknown result type (might be due to invalid IL or missing references) //IL_038c: Unknown result type (might be due to invalid IL or missing references) //IL_021f: Unknown result type (might be due to invalid IL or missing references) //IL_0479: Unknown result type (might be due to invalid IL or missing references) //IL_0483: Expected O, but got Unknown try { int num = <>1__state; AssetBundleLoader assetBundleLoader = <>4__this; switch (num) { default: return false; case 0: <>1__state = -1; <assetBundleInfo>5__2 = JsonConvert.DeserializeObject<AssetBundleInfo>(File.ReadAllText(fileInfo.FullName)); foreach (AssemblyInfo assembly in <assetBundleInfo>5__2.Assemblies) { assetBundleLoader.Logger.LogDebug((object)("Loading custom precompiled assembly: " + assembly.Name)); AssetData.Assemblies.Add(Assembly.LoadFrom(fileInfo.Directory.FullName + "/" + assembly.Name)); } <>7__wrap2 = <assetBundleInfo>5__2.Sprites.GetEnumerator(); <>1__state = -3; goto IL_0197; case 1: { <>1__state = -3; Dictionary<string, Sprite> sprites = AssetData.Sprites; string name = <sprite>5__4.Name; Object asset4 = <assetLoadRequest>5__5.asset; sprites[name] = (Sprite)(object)((asset4 is Sprite) ? asset4 : null); <assetLoadRequest>5__5 = null; <sprite>5__4 = null; goto IL_0197; } case 2: { <>1__state = -4; Object asset3 = <assetLoadRequest>5__5.asset; GameObject val = (GameObject)(object)((asset3 is GameObject) ? asset3 : null); using (List<VideoClipInfo>.Enumerator enumerator = <prefabInfo>5__7.VideoClips.GetEnumerator()) { while (enumerator.MoveNext()) { <>c__DisplayClass2_0 CS$<>8__locals0 = new <>c__DisplayClass2_0 { videoClipInfo = enumerator.Current }; assetBundleLoader.Logger.LogDebug((object)("Loading video source: " + CS$<>8__locals0.videoClipInfo.Name + " for game object " + ((Object)val).name)); Component[] componentsInChildren = val.GetComponentsInChildren<Component>(true); object obj; if (componentsInChildren == null) { obj = null; } else { Component? obj2 = componentsInChildren.Where((Component component) => ((Object)component).name == CS$<>8__locals0.videoClipInfo.VideoPlayerName).FirstOrDefault(); obj = ((obj2 != null) ? obj2.GetComponent<VideoPlayer>() : null); } VideoPlayer val2 = (VideoPlayer)obj; if (val2 != null) { assetBundleLoader.Logger.LogDebug((object)("Adding video source to video player: " + CS$<>8__locals0.videoClipInfo.VideoPlayerName)); val2.source = (VideoSource)1; val2.url = fileInfo.Directory.FullName + "/" + CS$<>8__locals0.videoClipInfo.Name; } } } AssetData.PrefabData.Add(<objectType>5__8, val); if (<prefabInfo>5__7.AddItemToFurnitureShop.HasValue && <prefabInfo>5__7.AddItemToFurnitureShop.Value) { FurnitureShopManager.Instance.Prefabs.Add(<prefabInfo>5__7); } <assetLoadRequest>5__5 = null; goto IL_03e0; } case 3: { <>1__state = -5; ref Mesh mesh = ref <itemMeshData>5__12.mesh; Object asset2 = <assetLoadRequest>5__5.asset; mesh = (Mesh)(object)((asset2 is Mesh) ? asset2 : null); <assetLoadRequest>5__5 = null; goto IL_0538; } case 4: { <>1__state = -5; ref Material material = ref <itemMeshData>5__12.material; Object asset = <assetLoadRequest>5__5.asset; material = (Material)(object)((asset is Material) ? asset : null); <assetLoadRequest>5__5 = null; goto IL_05cd; } IL_0538: if (!string.IsNullOrEmpty(<item>5__10.Material)) { assetBundleLoader.Logger.LogDebug((object)("Loading item material: " + <item>5__10.Material)); <assetLoadRequest>5__5 = assetBundle.LoadAssetAsync<Material>(<item>5__10.Material); <>2__current = <assetLoadRequest>5__5; <>1__state = 4; return true; } goto IL_05cd; IL_069a: <item>5__10 = null; goto IL_06a1; IL_03e0: <prefabInfo>5__7 = null; goto IL_03e7; IL_06a1: if (<>7__wrap8.MoveNext()) { <item>5__10 = <>7__wrap8.Current; if (Enum.TryParse<EItemType>(<item>5__10.ItemType, out <itemType>5__11)) { assetBundleLoader.Logger.LogDebug((object)("Item type found: " + <item>5__10.ItemType)); <itemMeshData>5__12 = new ItemMeshData(); assetBundleLoader.Logger.LogDebug((object)("Loading item: " + <item>5__10.Name)); if (!string.IsNullOrEmpty(<item>5__10.Mesh)) { assetBundleLoader.Logger.LogDebug((object)("Loading item mesh: " + <item>5__10.Mesh)); <assetLoadRequest>5__5 = assetBundle.LoadAssetAsync<Mesh>(<item>5__10.Mesh); <>2__current = <assetLoadRequest>5__5; <>1__state = 3; return true; } goto IL_0538; } goto IL_069a; } <>m__Finally3(); <>7__wrap8 = default(List<ItemInfo>.Enumerator); assetBundle.Unload(false); assetBundleLoader.IsLoaded = true; return false; IL_0197: if (<>7__wrap2.MoveNext()) { <sprite>5__4 = <>7__wrap2.Current; assetBundleLoader.Logger.LogDebug((object)("Loading asset sprite: " + <sprite>5__4.Name)); <assetLoadRequest>5__5 = assetBundle.LoadAssetAsync<Sprite>(<sprite>5__4.Name); <>2__current = <assetLoadRequest>5__5; <>1__state = 1; return true; } <>m__Finally1(); <>7__wrap2 = default(List<SpriteInfo>.Enumerator); <>7__wrap5 = <assetBundleInfo>5__2.Prefabs.GetEnumerator(); <>1__state = -4; goto IL_03e7; IL_05cd: AssetData.ItemMeshData.Add(<itemType>5__11, <itemMeshData>5__12); if ((<item>5__10.AddItemAsAccessory.HasValue && <item>5__10.AddItemAsAccessory.Value) || (<item>5__10.AddItemAsFigurine.HasValue && <item>5__10.AddItemAsFigurine.Value)) { RestockShopManager.Instance.Items.Add(<item>5__10); } else if (<item>5__10.AddItemAsBoardGame.HasValue && <item>5__10.AddItemAsBoardGame.Value) { BoardgameShopManager.Instance.Items.Add(<item>5__10); } <itemMeshData>5__12 = null; goto IL_069a; IL_03e7: if (<>7__wrap5.MoveNext()) { <prefabInfo>5__7 = <>7__wrap5.Current; if (Enum.TryParse<EObjectType>(<prefabInfo>5__7.ObjectType, out <objectType>5__8)) { assetBundleLoader.Logger.LogDebug((object)$"Loading object: {<prefabInfo>5__7.Name}, ObjectType: {<objectType>5__8}"); <assetLoadRequest>5__5 = assetBundle.LoadAssetAsync<GameObject>(<prefabInfo>5__7.Name); <>2__current = <assetLoadRequest>5__5; <>1__state = 2; return true; } goto IL_03e0; } <>m__Finally2(); <>7__wrap5 = default(List<PrefabInfo>.Enumerator); <>7__wrap8 = <assetBundleInfo>5__2.Items.GetEnumerator(); <>1__state = -5; goto IL_06a1; } } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; ((IDisposable)<>7__wrap2).Dispose(); } private void <>m__Finally2() { <>1__state = -1; ((IDisposable)<>7__wrap5).Dispose(); } private void <>m__Finally3() { <>1__state = -1; ((IDisposable)<>7__wrap8).Dispose(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } public bool IsLoaded { get; private set; } private ManualLogSource Logger { get; } = Logger.CreateLogSource("AssetBundleLoader"); private AssetBundleLoader() { } [IteratorStateMachine(typeof(<LoadAssetBundlesAsync>d__1))] public IEnumerator LoadAssetBundlesAsync(IEnumerable<string> files) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <LoadAssetBundlesAsync>d__1(0) { <>4__this = this, files = files }; } [IteratorStateMachine(typeof(<ProcessAssetBundleAsync>d__2))] private IEnumerator ProcessAssetBundleAsync(AssetBundle assetBundle, FileInfo fileInfo) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <ProcessAssetBundleAsync>d__2(0) { <>4__this = this, assetBundle = assetBundle, fileInfo = fileInfo }; } } public static class AssetData { public static List<Assembly> Assemblies { get; private set; } = new List<Assembly>(); public static List<RestockData> RestockData { get; private set; } = new List<RestockData>(); public static Dictionary<string, Sprite> Sprites { get; private set; } = new Dictionary<string, Sprite>(); public static Dictionary<EObjectType, GameObject> PrefabData { get; private set; } = new Dictionary<EObjectType, GameObject>(); public static Dictionary<EItemType, ItemData> ItemData { get; private set; } = new Dictionary<EItemType, ItemData>(); public static Dictionary<EItemType, ItemMeshData> ItemMeshData { get; private set; } = new Dictionary<EItemType, ItemMeshData>(); public static Dictionary<EItemType, ItemSaveData> ItemSaveData { get; set; } = new Dictionary<EItemType, ItemSaveData>(); } public class BoardgameShopManager : ItemShopManager<RestockItemBoardGameScreen> { private static BoardgameShopManager m_Instance; public static BoardgameShopManager Instance => m_Instance ?? (m_Instance = new BoardgameShopManager()); public override List<ItemInfo> Items { get; set; } = new List<ItemInfo>(); private BoardgameShopManager() { } protected override void AddPanelToShop(RestockItemBoardGameScreen shop, Transform panel) { ((RestockItemScreen)shop).m_RestockItemPanelUIList.Add(((Component)panel).GetComponent<RestockItemPanelUI>()); } protected override void AddItemToShop(ItemInfo itemInfo, EItemType itemType) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) Plugin.Logger.LogDebug((object)("Adding to board game shop " + itemInfo.Name)); CSingleton<InventoryBase>.Instance.m_StockItemData_SO.m_ShownBoardGameItemType.Add(itemType); } protected override int GetItemCount() { return Items.Count; } protected override int GetItemCountPerRow() { return 4; } } public class FurnitureShopManager : ShopManager<FurnitureShopUIScreen> { private static FurnitureShopManager m_Instance; public static FurnitureShopManager Instance => m_Instance ?? (m_Instance = new FurnitureShopManager()); public List<PrefabInfo> Prefabs { get; set; } = new List<PrefabInfo>(); private FurnitureShopManager() { } protected override void AddPanelToShop(FurnitureShopUIScreen shop, Transform panel) { shop.m_FurnitureShopPanelUIList.Add(((Component)panel).GetComponent<FurnitureShopPanelUI>()); } public override void AddItemsToInventory() { //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Expected O, but got Unknown //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: 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_00ed: Expected O, but got Unknown if (m_IsItemsAdded) { return; } foreach (PrefabInfo prefab in Prefabs) { Plugin.Logger.LogDebug((object)("Adding to furniture store " + prefab.Name)); EObjectType val = (EObjectType)Enum.Parse(typeof(EObjectType), prefab.ObjectType); AssetData.Sprites.TryGetValue(prefab.SpriteName, out var value); AssetData.PrefabData.TryGetValue(val, out var value2); FurniturePurchaseData item = new FurniturePurchaseData { name = prefab.Name, description = prefab.Description, levelRequirement = prefab.LevelRequirement, price = prefab.Price, objectType = val, icon = value }; ObjectData item2 = new ObjectData { name = prefab.Name, objectType = val, spawnPrefab = ((value2 != null) ? value2.GetComponent<InteractableObject>() : null) }; int i; for (i = 0; i < CSingleton<InventoryBase>.Instance.m_ObjectData_SO.m_FurniturePurchaseDataList.Count && CSingleton<InventoryBase>.Instance.m_ObjectData_SO.m_FurniturePurchaseDataList[i].levelRequirement <= prefab.LevelRequirement; i++) { } CSingleton<InventoryBase>.Instance.m_ObjectData_SO.m_FurniturePurchaseDataList.Insert(i, item); CSingleton<InventoryBase>.Instance.m_ObjectData_SO.m_ObjectDataList.Insert(i, item2); } m_IsItemsAdded = true; } protected override int GetItemCount() { return Prefabs.Count; } protected override int GetItemCountPerRow() { return 3; } } public abstract class ItemShopManager<T> : ShopManager<T> where T : GenericSliderScreen { public abstract List<ItemInfo> Items { get; set; } public override void AddItemsToInventory() { //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Expected O, but got Unknown //IL_010c: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_012e: Unknown result type (might be due to invalid IL or missing references) //IL_0139: Unknown result type (might be due to invalid IL or missing references) //IL_0145: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_015d: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Unknown result type (might be due to invalid IL or missing references) //IL_0164: Unknown result type (might be due to invalid IL or missing references) //IL_016b: Unknown result type (might be due to invalid IL or missing references) //IL_0177: Unknown result type (might be due to invalid IL or missing references) //IL_0183: Unknown result type (might be due to invalid IL or missing references) //IL_018f: Unknown result type (might be due to invalid IL or missing references) //IL_019b: Unknown result type (might be due to invalid IL or missing references) //IL_019d: Unknown result type (might be due to invalid IL or missing references) //IL_01a2: Unknown result type (might be due to invalid IL or missing references) //IL_01a7: Unknown result type (might be due to invalid IL or missing references) //IL_01a9: Unknown result type (might be due to invalid IL or missing references) //IL_01ae: Unknown result type (might be due to invalid IL or missing references) //IL_01b3: Unknown result type (might be due to invalid IL or missing references) //IL_01b5: Unknown result type (might be due to invalid IL or missing references) //IL_01ba: Unknown result type (might be due to invalid IL or missing references) //IL_01bf: Unknown result type (might be due to invalid IL or missing references) //IL_01cc: Expected O, but got Unknown //IL_01db: Unknown result type (might be due to invalid IL or missing references) //IL_01e3: Unknown result type (might be due to invalid IL or missing references) if (m_IsItemsAdded) { return; } foreach (ItemInfo item in Items) { Enum.TryParse<EItemType>(item.ItemType, out EItemType result); Enum.TryParse<EItemType>(item.FollowItemPrice, out EItemType result2); Enum.TryParse<EItemCategory>(item.ItemCategory, out EItemCategory result3); AssetData.Sprites.TryGetValue(item.SpriteName, out var value); List<EPriceChangeType> list = new List<EPriceChangeType>(); foreach (string item2 in item.PriceAffectedBy) { if (Enum.TryParse<EPriceChangeType>(item2, out EPriceChangeType result4)) { list.Add(result4); } } AssetData.RestockData.Add(new RestockData { name = item.Name, isBigBox = item.IsBigBox, licenseShopLevelRequired = item.LicenseLevelRequirement, licensePrice = item.LicensePrice, itemType = result, isHideItemUntilUnlocked = item.HideTillUnlocked, ignoreDoubleImage = item.IgnoreDoubleImage }); AssetData.ItemData.Add(result, new ItemData { name = item.Name, category = result3, icon = value, iconScale = 1f, baseCost = item.BaseCost, marketPriceMinPercent = item.MinMarketPricePercent, marketPriceMaxPercent = item.MaxMarketPricePercent, boxFollowItemPrice = result2, isNotBoosterPack = true, isTallItem = item.IsTallItem, isHideItemUntilUnlocked = item.HideTillUnlocked, posYOffsetInBox = item.InBoxOffsetY, scaleOffsetInBox = item.InBoxOffsetScale, itemDimension = item.ItemDeminsion, colliderPosOffset = item.CollidorPosOffset, colliderScale = item.ColliderScale, affectedPriceChangeType = list }); CSingleton<InventoryBase>.Instance.m_StockItemData_SO.m_ShownAllItemType.Add(result); AddItemToShop(item, result); } m_IsItemsAdded = true; } protected abstract void AddItemToShop(ItemInfo itemInfo, EItemType itemType); } [BepInPlugin("EnhancedPrefabLoader", "Enhanced Prefab Loader", "2.0.0")] public class Plugin : BaseUnityPlugin { [CompilerGenerated] private sealed class <FindAllPrefabLoaderJsons>d__3 : IEnumerable<string>, IEnumerable, IEnumerator<string>, IDisposable, IEnumerator { private int <>1__state; private string <>2__current; private int <>l__initialThreadId; private IEnumerator<string> <>7__wrap1; private IEnumerator<string> <>7__wrap2; string IEnumerator<string>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <FindAllPrefabLoaderJsons>d__3(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if ((uint)(num - -4) <= 1u || num == 1) { try { if (num == -4 || num == 1) { try { } finally { <>m__Finally2(); } } } finally { <>m__Finally1(); } } <>7__wrap1 = null; <>7__wrap2 = null; <>1__state = -2; } private bool MoveNext() { try { int num = <>1__state; if (num != 0) { if (num != 1) { return false; } <>1__state = -4; goto IL_00e2; } <>1__state = -1; Logger.LogDebug((object)"Searching folders for prefabLoader configuration files."); <>7__wrap1 = (from x in Directory.GetDirectories(Paths.PluginPath, "*", SearchOption.AllDirectories) where x.ToLower().EndsWith("prefabloader") select x).GetEnumerator(); <>1__state = -3; goto IL_00fc; IL_00fc: if (<>7__wrap1.MoveNext()) { string current = <>7__wrap1.Current; <>7__wrap2 = Directory.EnumerateFiles(current, "*.json", SearchOption.AllDirectories).GetEnumerator(); <>1__state = -4; goto IL_00e2; } <>m__Finally1(); <>7__wrap1 = null; return false; IL_00e2: if (<>7__wrap2.MoveNext()) { string current2 = <>7__wrap2.Current; Logger.LogDebug((object)("Found prefab loader config file: " + current2)); <>2__current = current2; <>1__state = 1; return true; } <>m__Finally2(); <>7__wrap2 = null; goto IL_00fc; } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap1 != null) { <>7__wrap1.Dispose(); } } private void <>m__Finally2() { <>1__state = -3; if (<>7__wrap2 != null) { <>7__wrap2.Dispose(); } } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] IEnumerator<string> IEnumerable<string>.GetEnumerator() { if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; return this; } return new <FindAllPrefabLoaderJsons>d__3(0); } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<string>)this).GetEnumerator(); } } public static string m_BaseDirectory; private readonly Harmony m_Harmony = new Harmony("EnhancedPrefabLoader"); private bool m_IsLoaded; public bool IsLoaded { get; private set; } internal static ManualLogSource Logger { get; private set; } private void Awake() { Logger = ((BaseUnityPlugin)this).Logger; Settings.Instance.Load(this); m_BaseDirectory = (from x in Directory.GetDirectories(Paths.PluginPath, "*", SearchOption.AllDirectories) where x.ToLower().EndsWith("enhancedprefabloader") select x).FirstOrDefault(); m_Harmony.PatchAll(); ListInterceptor<ItemData>.Handler = new ItemDataListInterceptor(); ListInterceptor<RestockData>.Handler = new RestockDataListInterceptor(); ListInterceptor<ItemMeshData>.Handler = new ItemMeshDataInterceptor(); ListInterceptor<FloatList>.Handler = new FloatListListInterceptor(); ListInterceptor<float>.Handler = new FloatListInterceptor(); ListInterceptor<bool>.Handler = new BoolListInterceptor(); ListInterceptor<int>.Handler = new IntListInterceptor(); SceneManager.sceneLoaded += OnSceneLoad; Logger.LogInfo((object)"Plugin Enhanced Prefab Loader v:2.0.0 by GhostNarwhal is loaded!"); } private void OnDestroy() { m_Harmony.UnpatchSelf(); Logger.LogInfo((object)"Plugin Enhanced Prefab Loader is unloaded!"); } private void OnSceneLoad(Scene scene, LoadSceneMode _) { if (((Scene)(ref scene)).name == "Title" && !m_IsLoaded) { Logger.LogDebug((object)"Loading precompiled scripts."); Assembly.LoadFrom(m_BaseDirectory + "/Scripts.dll"); Logger.LogDebug((object)"Loading assetbundles."); ((MonoBehaviour)this).StartCoroutine(CSingleton<AssetBundleLoader>.Instance.LoadAssetBundlesAsync(FindAllPrefabLoaderJsons())); m_IsLoaded = true; } } [IteratorStateMachine(typeof(<FindAllPrefabLoaderJsons>d__3))] private IEnumerable<string> FindAllPrefabLoaderJsons() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <FindAllPrefabLoaderJsons>d__3(-2); } } public class RestockShopManager : ItemShopManager<RestockItemScreen> { private static RestockShopManager m_Instance; public static RestockShopManager Instance => m_Instance ?? (m_Instance = new RestockShopManager()); public override List<ItemInfo> Items { get; set; } = new List<ItemInfo>(); private RestockShopManager() { } public override void AddItemsToInventory() { if (Items.Count > 0) { base.AddItemsToInventory(); } } protected override void AddPanelToShop(RestockItemScreen shop, Transform panel) { shop.m_RestockItemPanelUIList.Add(((Component)panel).GetComponent<RestockItemPanelUI>()); } protected override void AddItemToShop(ItemInfo itemInfo, EItemType itemType) { //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) if (itemInfo.AddItemAsAccessory.HasValue && itemInfo.AddItemAsAccessory.Value) { Plugin.Logger.LogDebug((object)("Adding to acessory shop " + itemInfo.Name)); CSingleton<InventoryBase>.Instance.m_StockItemData_SO.m_ShownAccessoryItemType.Add(itemType); } if (itemInfo.AddItemAsFigurine.HasValue && itemInfo.AddItemAsFigurine.Value) { Plugin.Logger.LogDebug((object)("Adding to figurine shop " + itemInfo.Name)); CSingleton<InventoryBase>.Instance.m_StockItemData_SO.m_ShownFigurineItemType.Add(itemType); } } protected override int GetItemCount() { return Items.Count; } protected override int GetItemCountPerRow() { return 4; } } public class Settings { private static Settings m_instance; public static Settings Instance => m_instance ?? (m_instance = new Settings()); public void Load(Plugin plugin) { } private Settings() { } } public abstract class ShopManager<T> where T : GenericSliderScreen { protected bool m_IsItemsAdded; public virtual void EvaluateItemPanelUI(ref T shop) { //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Expected O, but got Unknown if (!CSingleton<AssetBundleLoader>.Instance.IsLoaded) { return; } Transform val = ((Component)shop).transform.Find("ScreenGrp/AnimGrp/WebsiteContent_Grp/ScrollerGrp"); Transform val2 = val.Find("HorizontalLayout"); int result; int num = Math.DivRem(GetItemCount(), GetItemCountPerRow(), out result); if (result != 0) { num++; } for (int i = 0; i < num; i++) { foreach (Transform item in Object.Instantiate<Transform>(val2, val)) { Transform panel = item; AddPanelToShop(shop, panel); } } } public abstract void AddItemsToInventory(); protected abstract void AddPanelToShop(T shop, Transform panel); protected abstract int GetItemCount(); protected abstract int GetItemCountPerRow(); } public static class MyPluginInfo { public const string PLUGIN_GUID = "EnhancedPrefabLoader"; public const string PLUGIN_NAME = "Enhanced Prefab Loader"; public const string PLUGIN_VERSION = "2.0.0"; } } namespace EnhancedPrefabLoader.Patches { [HarmonyPatch(typeof(FurnitureShopUIScreen))] public class FurnitureShopUIScreenPatches { [HarmonyPatch("Init")] [HarmonyPrefix] private static void InitPrefix(ref FurnitureShopUIScreen __instance) { FurnitureShopManager.Instance.EvaluateItemPanelUI(ref __instance); } } [HarmonyPatch(typeof(InventoryBase))] public class InventoryBasePatches { [HarmonyPatch("Awake")] [HarmonyPostfix] public static void AwakePostfix(InventoryBase __instance) { FurnitureShopManager.Instance.AddItemsToInventory(); RestockShopManager.Instance.AddItemsToInventory(); BoardgameShopManager.Instance.AddItemsToInventory(); } } [HarmonyPatch(typeof(RestockItemBoardGameScreen))] public class RestockItemBoardGameScreenPatches { [HarmonyPatch("EvaluateRestockItemPanelUI")] [HarmonyPrefix] public static void EvaluateRestockItemPanelUIPrefix(ref RestockItemBoardGameScreen __instance) { BoardgameShopManager.Instance.EvaluateItemPanelUI(ref __instance); } } [HarmonyPatch(typeof(RestockItemScreen))] public class RestockItemScreenPatches { [HarmonyPatch("Init")] [HarmonyPrefix] public static void EvaluateRestockItemPanelUIPrefix(ref RestockItemScreen __instance) { RestockShopManager.Instance.EvaluateItemPanelUI(ref __instance); } } [HarmonyPatch(typeof(ShelfManager))] public class ShelfManagerPatches { [HarmonyPatch("SpawnInteractableObject")] [HarmonyPostfix] private static void SpawnInteractableObjectPostfix(EObjectType objType, ref InteractableObject __result) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) __result.m_ObjectType = objType; } [HarmonyPatch("LoadInteractableObjectData")] [HarmonyPrefix] private static void LoadInteractableObjectDataPrefix() { int currentSaveLoadSlotSelectedIndex = CSingleton<CGameManager>.Instance.m_CurrentSaveLoadSlotSelectedIndex; if (File.Exists(string.Format("{0}/Saves/{1}_{2}", Plugin.m_BaseDirectory, "EnhancedPrefabLoader", currentSaveLoadSlotSelectedIndex))) { AssetData.ItemSaveData = JsonConvert.DeserializeObject<Dictionary<EItemType, ItemSaveData>>(File.ReadAllText(string.Format("{0}/Saves/{1}_{2}", Plugin.m_BaseDirectory, "EnhancedPrefabLoader", currentSaveLoadSlotSelectedIndex))); } } } } namespace EnhancedPrefabLoader.Models { public class AssemblyInfo { public string Name { get; set; } } public class AssetBundleInfo { public List<AssemblyInfo> Assemblies { get; set; } = new List<AssemblyInfo>(); public List<SpriteInfo> Sprites { get; set; } = new List<SpriteInfo>(); public List<ItemInfo> Items { get; set; } = new List<ItemInfo>(); public List<PrefabInfo> Prefabs { get; set; } = new List<PrefabInfo>(); } public class ItemInfo { public string Name { get; set; } public string ItemCategory { get; set; } public string SpriteName { get; set; } public float BaseCost { get; set; } public bool? AddItemAsAccessory { get; set; } public bool? AddItemAsFigurine { get; set; } public bool? AddItemAsBoardGame { get; set; } public bool HideTillUnlocked { get; set; } public string ItemType { get; set; } public float LicensePrice { get; set; } public int LicenseLevelRequirement { get; set; } public string Mesh { get; set; } public string Material { get; set; } public bool IsBigBox { get; set; } public bool IgnoreDoubleImage { get; set; } public float MinMarketPricePercent { get; set; } public float MaxMarketPricePercent { get; set; } public string FollowItemPrice { get; set; } public bool IsTallItem { get; set; } public float InBoxOffsetY { get; set; } public float InBoxOffsetScale { get; set; } public Vector3 ItemDeminsion { get; set; } public Vector3 CollidorPosOffset { get; set; } public Vector3 ColliderScale { get; set; } public List<string> PriceAffectedBy { get; set; } = new List<string>(); } public class ItemSaveData { public bool IsUnlocked { get; set; } public float ItemPriceChangePercent { get; set; } public float ItemPrice { get; set; } public float GeneratedCostPrice { get; set; } public float GeneratedMarketPrice { get; set; } public float AverageItemCost { get; set; } public int CurrentItemCount { get; set; } public FloatList ItemPriceChangeHistory { get; set; } = new FloatList(); } public class PrefabInfo { public string Name { get; set; } public string SpriteName { get; set; } public float Price { get; set; } public string Description { get; set; } public int LevelRequirement { get; set; } public string ObjectType { get; set; } public bool? AddItemToFurnitureShop { get; set; } public bool? AddItemToDecoShop { get; set; } public List<VideoClipInfo> VideoClips { get; set; } = new List<VideoClipInfo>(); } public class SpriteInfo { public string Name { get; set; } } public class VideoClipInfo { public string Name { get; set; } public string VideoPlayerName { get; set; } } } namespace EnhancedPrefabLoader.Intercepters { public abstract class BaseListInterceptorHandler<T> : IListInterceptorHandler<T> { protected HashSet<string> m_AcceptedFieldNames = new HashSet<string>(); public abstract int Count(List<T> list, string fieldName); public abstract T OnGet(List<T> list, int index, string fieldName); public abstract void OnSet(List<T> list, int index, T value, string fieldName); protected virtual int NormalizeIndex(int index) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Expected I4, but got Unknown if (index < 200000 && ((EItemType)125).TryGetNext<EItemType>(out EItemType result, index - 124)) { return (int)result; } return index; } } public class BoolListInterceptor : BaseListInterceptorHandler<bool> { private HashSet<string> m_SupportedListNames = new HashSet<string>(); public BoolListInterceptor() { m_AcceptedFieldNames.Add("m_IsItemLicenseUnlocked"); } public override int Count(List<bool> list, string fieldName) { if (m_AcceptedFieldNames.Contains(fieldName)) { int count = CSingleton<InventoryBase>.Instance.m_StockItemData_SO.m_RestockDataList.Count; if (list.Count > count) { return list.Count; } return list.Count + AssetData.ItemSaveData.Count; } return list.Count; } public override bool OnGet(List<bool> list, int index, string fieldName) { //IL_003c: Unknown result type (might be due to invalid IL or missing references) if (m_AcceptedFieldNames.Contains(fieldName)) { int count = CSingleton<InventoryBase>.Instance.m_StockItemData_SO.m_RestockDataList.Count; if (index >= count) { index -= count; ItemSaveData value; bool flag = AssetData.ItemSaveData.TryGetValue(AssetData.RestockData[index].itemType, out value); if (flag) { bool flag2 = fieldName == "m_IsItemLicenseUnlocked" && value.IsUnlocked; flag = flag2; } return flag; } } return list[index]; } public override void OnSet(List<bool> list, int index, bool value, string fieldName) { //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) if (m_AcceptedFieldNames.Contains(fieldName)) { int count = CSingleton<InventoryBase>.Instance.m_StockItemData_SO.m_RestockDataList.Count; if (index >= count) { index -= count; if (!AssetData.ItemSaveData.TryGetValue(AssetData.RestockData[index].itemType, out var value2)) { value2 = new ItemSaveData(); AssetData.ItemSaveData[AssetData.RestockData[index].itemType] = value2; } if (fieldName == "m_IsItemLicenseUnlocked") { value2.IsUnlocked = value; } return; } } list[index] = value; } } public class FloatListInterceptor : BaseListInterceptorHandler<float> { private HashSet<string> m_SupportedListNames = new HashSet<string>(); public FloatListInterceptor() { m_AcceptedFieldNames.Add("m_GeneratedMarketPriceList"); m_AcceptedFieldNames.Add("m_GeneratedCostPriceList"); m_AcceptedFieldNames.Add("m_ItemPricePercentChangeList"); m_AcceptedFieldNames.Add("m_AverageItemCostList"); m_AcceptedFieldNames.Add("m_SetItemPriceList"); } public override int Count(List<float> list, string fieldName) { if (!m_AcceptedFieldNames.Contains(fieldName) || list.Count > 125) { return list.Count; } return list.Count + AssetData.ItemSaveData.Count; } public override float OnGet(List<float> list, int index, string fieldName) { if (m_AcceptedFieldNames.Contains(fieldName) && index >= 125) { index = NormalizeIndex(index); if (AssetData.ItemSaveData.TryGetValue((EItemType)index, out var value)) { return fieldName switch { "m_GeneratedMarketPriceList" => value.GeneratedMarketPrice, "m_GeneratedCostPriceList" => value.GeneratedCostPrice, "m_ItemPricePercentChangeList" => value.ItemPriceChangePercent, "m_AverageItemCostList" => value.AverageItemCost, "m_SetItemPriceList" => value.ItemPrice, _ => 0f, }; } return 0f; } return list[index]; } public override void OnSet(List<float> list, int index, float value, string fieldName) { if (m_AcceptedFieldNames.Contains(fieldName) && index >= 125) { index = NormalizeIndex(index); if (!AssetData.ItemSaveData.TryGetValue((EItemType)index, out var value2)) { value2 = new ItemSaveData(); AssetData.ItemSaveData[(EItemType)index] = value2; } if (fieldName == "m_AverageItemCostList") { value2.AverageItemCost = value; } if (fieldName == "m_SetItemPriceList") { value2.ItemPrice = value; } if (fieldName == "m_GeneratedCostPriceList") { value2.GeneratedCostPrice = value; } if (fieldName == "m_GeneratedMarketPriceList") { value2.GeneratedMarketPrice = value; } } else { list[index] = value; } } } public class FloatListListInterceptor : BaseListInterceptorHandler<FloatList> { public FloatListListInterceptor() { m_AcceptedFieldNames.Add("m_ItemPricePercentPastChangeList"); } public override int Count(List<FloatList> list, string fieldName) { if (!m_AcceptedFieldNames.Contains(fieldName) || list.Count > 125) { return list.Count; } return list.Count + AssetData.ItemSaveData.Count; } public override FloatList OnGet(List<FloatList> list, int index, string fieldName) { if (m_AcceptedFieldNames.Contains(fieldName) && index >= 125) { index = NormalizeIndex(index); if (AssetData.ItemSaveData.TryGetValue((EItemType)index, out var value) && fieldName == "m_ItemPricePercentPastChangeList") { if (value.ItemPriceChangeHistory.floatDataList == null) { value.ItemPriceChangeHistory.floatDataList = new List<float>(); } return value.ItemPriceChangeHistory; } } return list[index]; } public override void OnSet(List<FloatList> list, int index, FloatList value, string fieldName) { if (m_AcceptedFieldNames.Contains(fieldName) && index >= 125) { index = NormalizeIndex(index); if (!AssetData.ItemSaveData.TryGetValue((EItemType)index, out var value2)) { value2 = new ItemSaveData(); AssetData.ItemSaveData[(EItemType)index] = value2; } if (fieldName == "m_ItemPricePercentPastChangeList") { value2.ItemPriceChangeHistory = value; } } else { list[index] = value; } } } public class IntListInterceptor : BaseListInterceptorHandler<int> { public IntListInterceptor() { m_AcceptedFieldNames.Add("m_CurrentTotalItemCountList"); } public override int Count(List<int> list, string fieldName) { if (!m_AcceptedFieldNames.Contains(fieldName) || list.Count > 125) { return list.Count; } return list.Count + AssetData.ItemSaveData.Count; } public override int OnGet(List<int> list, int index, string fieldName) { if (m_AcceptedFieldNames.Contains(fieldName) && index >= 125) { index = NormalizeIndex(index); if (AssetData.ItemSaveData.TryGetValue((EItemType)index, out var value)) { return (fieldName == "m_CurrentTotalItemCountList") ? value.CurrentItemCount : 0; } return 0; } return list[index]; } public override void OnSet(List<int> list, int index, int value, string fieldName) { if (m_AcceptedFieldNames.Contains(fieldName) && index >= 125) { index = NormalizeIndex(index); if (!AssetData.ItemSaveData.TryGetValue((EItemType)index, out var value2)) { value2 = new ItemSaveData(); AssetData.ItemSaveData[(EItemType)index] = value2; } if (fieldName == "m_CurrentTotalItemCountList") { value2.CurrentItemCount = value; } } else { list[index] = value; } } } public class ItemDataListInterceptor : BaseListInterceptorHandler<ItemData> { public ItemDataListInterceptor() { m_AcceptedFieldNames.Add("m_ItemDataList"); } public override int Count(List<ItemData> list, string fieldName) { if (!m_AcceptedFieldNames.Contains(fieldName)) { return list.Count; } return list.Count + AssetData.ItemData.Count; } public override ItemData OnGet(List<ItemData> list, int index, string fieldName) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Expected O, but got Unknown if (m_AcceptedFieldNames.Contains(fieldName) && index >= 125) { index = NormalizeIndex(index); if (!AssetData.ItemData.TryGetValue((EItemType)index, out var value)) { return new ItemData(); } return value; } return list[index]; } public override void OnSet(List<ItemData> list, int index, ItemData value, string fieldName) { if (m_AcceptedFieldNames.Contains(fieldName) && index >= 125) { index = NormalizeIndex(index); if (index < AssetData.ItemData.Count) { AssetData.ItemData[(EItemType)index] = value; } } else { list[index] = value; } } } public class ItemMeshDataInterceptor : BaseListInterceptorHandler<ItemMeshData> { public ItemMeshDataInterceptor() { m_AcceptedFieldNames.Add("m_ItemMeshDataList"); } public override int Count(List<ItemMeshData> list, string fieldName) { if (!m_AcceptedFieldNames.Contains(fieldName)) { return list.Count; } return list.Count + AssetData.ItemMeshData.Count; } public override ItemMeshData OnGet(List<ItemMeshData> list, int index, string fieldName) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Expected O, but got Unknown if (m_AcceptedFieldNames.Contains(fieldName) && index >= 125) { index = NormalizeIndex(index); if (!AssetData.ItemMeshData.TryGetValue((EItemType)index, out var value)) { return new ItemMeshData(); } return value; } return list[index]; } public override void OnSet(List<ItemMeshData> list, int index, ItemMeshData value, string fieldName) { if (m_AcceptedFieldNames.Contains(fieldName) && index >= 125) { index = NormalizeIndex(index); if (index < AssetData.ItemMeshData.Count) { AssetData.ItemMeshData[(EItemType)index] = value; } } else { list[index] = value; } } } public class RestockDataListInterceptor : BaseListInterceptorHandler<RestockData> { public RestockDataListInterceptor() { m_AcceptedFieldNames.Add("m_RestockDataList"); } public override int Count(List<RestockData> list, string fieldName) { if (!m_AcceptedFieldNames.Contains(fieldName)) { return list.Count; } return list.Count + AssetData.RestockData.Count; } public override RestockData OnGet(List<RestockData> list, int index, string fieldName) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown if (m_AcceptedFieldNames.Contains(fieldName) && index >= list.Count) { index -= list.Count; if (index >= AssetData.RestockData.Count) { return new RestockData(); } return AssetData.RestockData[index]; } return list[index]; } public override void OnSet(List<RestockData> list, int index, RestockData value, string fieldName) { if (m_AcceptedFieldNames.Contains(fieldName) && index >= list.Count) { index -= list.Count; if (index < AssetData.RestockData.Count) { AssetData.RestockData[index] = value; } } else { list[index] = value; } } } } namespace EnhancedPrefabLoader.Extensions { public static class EnumExtensions { public static bool TryGetNext<T>(this T value, out T result, int offset = 1) where T : struct, Enum { T[] array = (from T x in Enum.GetValues(typeof(T)) orderby Convert.ToInt32(x) select x).ToArray(); int num = Array.IndexOf(array, value) + offset; if (num < array.Length) { result = array[num]; return true; } result = default(T); return false; } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class IgnoresAccessChecksToAttribute : Attribute { internal IgnoresAccessChecksToAttribute(string assemblyName) { } } }
BepInEx/plugins/Scripts.dll
Decompiled 3 months agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using Microsoft.CodeAnalysis; using UnityEngine; using UnityEngine.Video; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")] [assembly: AssemblyCompany("Scripts")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("2.0.0.0")] [assembly: AssemblyInformationalVersion("2.0.0+40cdc7df25d66bcd28939d889a9240738f060bdd")] [assembly: AssemblyProduct("Scripts")] [assembly: AssemblyTitle("Scripts")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("2.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } public class CeilingHangingInteractableObject : InteractableObject { protected override void Update() { //IL_0017: 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_002d: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Unknown result type (might be due to invalid IL or missing references) if (!base.m_IsMovingObject) { return; } ((Component)this).transform.position = Vector3.Lerp(((Component)this).transform.position, base.m_TargetMoveObjectPosition, Time.deltaTime * 7.5f); bool flag = false; int mask = LayerMask.GetMask(new string[2] { "MoveStateBlockedArea", "Customer" }); if (Physics.OverlapBox(base.m_MoveStateValidArea.position, base.m_MoveStateValidArea.lossyScale / 2f, base.m_MoveStateValidArea.rotation, mask).Length == 0) { if (base.m_PlaceObjectInShopOnly) { if (Physics.OverlapBox(base.m_MoveStateValidArea.position, base.m_MoveStateValidArea.lossyScale / 2f, base.m_MoveStateValidArea.rotation, LayerMask.GetMask(new string[1] { "MoveStateValidArea" })).Length != 0) { flag = true; } } else if (base.m_PlaceObjectInShopOnly && Physics.OverlapBox(base.m_MoveStateValidArea.position, base.m_MoveStateValidArea.lossyScale / 2f, base.m_MoveStateValidArea.rotation, LayerMask.GetMask(new string[1] { "MoveStateValidWarehouseArea" })).Length != 0) { flag = true; } } base.m_IsMovingObjectValidState = flag; ShelfManager.SetMoveObjectPreviewModelValidState(flag); } protected override void OnPlacedMovedObject() { //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_0163: Unknown result type (might be due to invalid IL or missing references) //IL_017e: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Unknown result type (might be due to invalid IL or missing references) CSingleton<InteractionPlayerController>.Instance.OnExitMoveObjectMode(); base.m_IsMovingObject = false; ((Component)this).gameObject.layer = base.m_OriginalLayer; ((Collider)base.m_BoxCollider).enabled = true; for (int i = 0; i < base.m_BoxColliderList.Count; i++) { ((Collider)base.m_BoxColliderList[i]).enabled = true; } int mask = LayerMask.GetMask(new string[1] { "ShopModel" }); Vector3 position = ((Component)base.m_PickupObjectMesh).transform.position; position.y += 0.2f; RaycastHit val = default(RaycastHit); if (Physics.Raycast(position, Vector3.up, ref val, 50f, mask)) { ((Component)this).transform.position = ((RaycastHit)(ref val)).point; } ((Component)base.m_MoveStateValidArea).gameObject.SetActive(true); ShelfManager.DisableMoveObjectPreviewMode(); if (Object.op_Implicit((Object)(object)base.m_BoxCollider)) { ((Component)CSingleton<ShelfManager>.Instance.m_MoveObjectCustomerBlocker).gameObject.SetActive(false); } if (!base.m_IsBoxedUp && Object.op_Implicit((Object)(object)base.m_InteractablePackagingBox_Shelf)) { if (Object.op_Implicit((Object)(object)base.m_Shelf_WorldUIGrp)) { ((Component)base.m_Shelf_WorldUIGrp).transform.position = ((Component)this).transform.position; } base.m_InteractablePackagingBox_Shelf.EmptyBoxShelf(); ((InteractableObject)base.m_InteractablePackagingBox_Shelf).OnDestroyed(); } if (Object.op_Implicit((Object)(object)base.m_Shelf_WorldUIGrp) && !base.m_IsBoxedUp) { ((Component)base.m_Shelf_WorldUIGrp).transform.position = ((Component)this).transform.position; ((Component)base.m_Shelf_WorldUIGrp).transform.rotation = ((Component)this).transform.rotation; } if (Object.op_Implicit((Object)(object)base.m_NavMeshCut)) { base.m_NavMeshCut.SetActive(false); base.m_NavMeshCut.SetActive(true); } } } namespace Scripts { public class CustomInteractableObject : InteractableObject { protected override void Awake() { } protected override void Update() { //IL_0017: 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_002d: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Unknown result type (might be due to invalid IL or missing references) if (!base.m_IsMovingObject) { return; } ((Component)this).transform.position = Vector3.Lerp(((Component)this).transform.position, base.m_TargetMoveObjectPosition, Time.deltaTime * 7.5f); bool flag = false; int mask = LayerMask.GetMask(new string[2] { "MoveStateBlockedArea", "Customer" }); if (Physics.OverlapBox(base.m_MoveStateValidArea.position, base.m_MoveStateValidArea.lossyScale / 2f, base.m_MoveStateValidArea.rotation, mask).Length == 0) { if (base.m_PlaceObjectInShopOnly) { if (Physics.OverlapBox(base.m_MoveStateValidArea.position, base.m_MoveStateValidArea.lossyScale / 2f, base.m_MoveStateValidArea.rotation, LayerMask.GetMask(new string[1] { "MoveStateValidArea" })).Length != 0) { flag = true; } } else if (base.m_PlaceObjectInShopOnly && Physics.OverlapBox(base.m_MoveStateValidArea.position, base.m_MoveStateValidArea.lossyScale / 2f, base.m_MoveStateValidArea.rotation, LayerMask.GetMask(new string[1] { "MoveStateValidWarehouseArea" })).Length != 0) { flag = true; } } base.m_IsMovingObjectValidState = flag; ShelfManager.SetMoveObjectPreviewModelValidState(flag); } protected override void OnPlacedMovedObject() { //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_0163: Unknown result type (might be due to invalid IL or missing references) //IL_017e: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Unknown result type (might be due to invalid IL or missing references) CSingleton<InteractionPlayerController>.Instance.OnExitMoveObjectMode(); base.m_IsMovingObject = false; ((Component)this).gameObject.layer = base.m_OriginalLayer; ((Collider)base.m_BoxCollider).enabled = true; for (int i = 0; i < base.m_BoxColliderList.Count; i++) { ((Collider)base.m_BoxColliderList[i]).enabled = true; } int mask = LayerMask.GetMask(new string[1] { "ShopModel" }); Vector3 position = ((Component)base.m_PickupObjectMesh).transform.position; position.y += 0.2f; RaycastHit val = default(RaycastHit); if (Physics.Raycast(position, Vector3.down, ref val, 100f, mask)) { ((Component)this).transform.position = ((RaycastHit)(ref val)).point; } ((Component)base.m_MoveStateValidArea).gameObject.SetActive(true); ShelfManager.DisableMoveObjectPreviewMode(); if (Object.op_Implicit((Object)(object)base.m_BoxCollider)) { ((Component)CSingleton<ShelfManager>.Instance.m_MoveObjectCustomerBlocker).gameObject.SetActive(false); } if (!base.m_IsBoxedUp && Object.op_Implicit((Object)(object)base.m_InteractablePackagingBox_Shelf)) { if (Object.op_Implicit((Object)(object)base.m_Shelf_WorldUIGrp)) { ((Component)base.m_Shelf_WorldUIGrp).transform.position = ((Component)this).transform.position; } base.m_InteractablePackagingBox_Shelf.EmptyBoxShelf(); ((InteractableObject)base.m_InteractablePackagingBox_Shelf).OnDestroyed(); } if (Object.op_Implicit((Object)(object)base.m_Shelf_WorldUIGrp) && !base.m_IsBoxedUp) { ((Component)base.m_Shelf_WorldUIGrp).transform.position = ((Component)this).transform.position; ((Component)base.m_Shelf_WorldUIGrp).transform.rotation = ((Component)this).transform.rotation; } if (Object.op_Implicit((Object)(object)base.m_NavMeshCut)) { base.m_NavMeshCut.SetActive(false); base.m_NavMeshCut.SetActive(true); } } } public interface IListInterceptorHandler<T> { T OnGet(List<T> list, int index, string fieldName); void OnSet(List<T> list, int index, T value, string fieldName); int Count(List<T> list, string fieldName); } public static class ListInterceptor<T> { public static IListInterceptorHandler<T> Handler { get; set; } public static T InvokeGet(List<T> list, int index, string fieldName) { if (list != null) { if (Handler != null) { return Handler.OnGet(list, index, fieldName); } if (index >= 0 && index < list.Count) { return list[index]; } throw new ArgumentOutOfRangeException("index"); } throw new ArgumentNullException("list"); } public static int InvokeCount(List<T> list, string fieldName) { if (list != null) { if (Handler != null) { return Handler.Count(list, fieldName); } return list.Count; } throw new ArgumentNullException("list"); } public static void InvokeSet(List<T> list, int index, T value, string fieldName) { if (list == null) { throw new ArgumentNullException("list"); } if (Handler == null) { if (index < 0 || index >= list.Count) { throw new ArgumentOutOfRangeException("index"); } list[index] = value; } else { Handler.OnSet(list, index, value, fieldName); } } } public class VideoPlayerController : MonoBehaviour { public bool m_StopOnPickupObject; public VideoPlayer m_VideoPlayer; public InteractableObject m_InteractableObject; private void Update() { if (m_InteractableObject.GetIsBoxedUp() && m_VideoPlayer.isPlaying) { m_VideoPlayer.Stop(); } if (m_InteractableObject.GetIsMovingObject() && m_StopOnPickupObject && m_VideoPlayer.isPlaying) { m_VideoPlayer.Stop(); } if (!m_InteractableObject.GetIsMovingObject() && !m_InteractableObject.GetIsBoxedUp() && !m_VideoPlayer.isPlaying) { m_VideoPlayer.Play(); } } } public class WallHangingInteractableObject : InteractableObject { public float m_RaycastDistance; public bool m_IsBidirectional; private List<string> m_WallObjectNames = new List<string>(4) { "WarehousewallBlocker", "GlassdoorBlocker", "Blocker3", "Blocker5" }; protected override void Update() { //IL_0017: 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_002d: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) if (!base.m_IsMovingObject) { return; } ((Component)this).transform.position = Vector3.Lerp(((Component)this).transform.position, base.m_TargetMoveObjectPosition, Time.deltaTime * 7.5f); RaycastHit val = default(RaycastHit); if (Physics.OverlapBox(base.m_MoveStateValidArea.position, base.m_MoveStateValidArea.lossyScale / 2f, base.m_MoveStateValidArea.rotation, LayerMask.GetMask(new string[1] { "MoveStateBlockedArea" })).Length == 0) { bool num; if (!m_IsBidirectional) { num = Physics.Raycast(base.m_MoveStateValidArea.position, base.m_MoveStateValidArea.forward, ref val, m_RaycastDistance); } else { if (Physics.Raycast(base.m_MoveStateValidArea.position, base.m_MoveStateValidArea.forward, ref val, m_RaycastDistance)) { goto IL_0104; } num = Physics.Raycast(base.m_MoveStateValidArea.position, base.m_MoveStateValidArea.forward * -1f, ref val, m_RaycastDistance); } if (num) { goto IL_0104; } goto IL_012b; } base.m_IsMovingObjectValidState = false; ShelfManager.SetMoveObjectPreviewModelValidState(false); return; IL_0104: if (m_WallObjectNames.Contains(((Object)((RaycastHit)(ref val)).transform).name)) { base.m_IsMovingObjectValidState = true; ShelfManager.SetMoveObjectPreviewModelValidState(true); return; } goto IL_012b; IL_012b: base.m_IsMovingObjectValidState = false; ShelfManager.SetMoveObjectPreviewModelValidState(false); } protected override void OnPlacedMovedObject() { //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_0122: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) CSingleton<InteractionPlayerController>.Instance.OnExitMoveObjectMode(); base.m_IsMovingObject = false; ((Component)this).gameObject.layer = base.m_OriginalLayer; ((Collider)base.m_BoxCollider).enabled = true; for (int i = 0; i < base.m_BoxColliderList.Count; i++) { ((Collider)base.m_BoxColliderList[i]).enabled = true; } ((Component)base.m_MoveStateValidArea).gameObject.SetActive(true); ShelfManager.DisableMoveObjectPreviewMode(); if (Object.op_Implicit((Object)(object)base.m_BoxCollider)) { ((Component)CSingleton<ShelfManager>.Instance.m_MoveObjectCustomerBlocker).gameObject.SetActive(false); } if (!base.m_IsBoxedUp && Object.op_Implicit((Object)(object)base.m_InteractablePackagingBox_Shelf)) { if (Object.op_Implicit((Object)(object)base.m_Shelf_WorldUIGrp)) { ((Component)base.m_Shelf_WorldUIGrp).transform.position = ((Component)this).transform.position; } base.m_InteractablePackagingBox_Shelf.EmptyBoxShelf(); ((InteractableObject)base.m_InteractablePackagingBox_Shelf).OnDestroyed(); } if (Object.op_Implicit((Object)(object)base.m_Shelf_WorldUIGrp) && !base.m_IsBoxedUp) { ((Component)base.m_Shelf_WorldUIGrp).transform.position = ((Component)this).transform.position; ((Component)base.m_Shelf_WorldUIGrp).transform.rotation = ((Component)this).transform.rotation; } if (Object.op_Implicit((Object)(object)base.m_NavMeshCut)) { base.m_NavMeshCut.SetActive(false); base.m_NavMeshCut.SetActive(true); } } } public static class MyPluginInfo { public const string PLUGIN_GUID = "Scripts"; public const string PLUGIN_NAME = "Scripts"; public const string PLUGIN_VERSION = "2.0.0"; } }