Decompiled source of MangHoMagnet v1.0.26
com.github.manghomagnet.dll
Decompiled 5 days agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using AngleSharp.Dom; using AngleSharp.Html.Dom; using AngleSharp.Html.Parser; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using Steamworks; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("com.github.manghomagnet")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.26.0")] [assembly: AssemblyInformationalVersion("1.0.26+423286e242150378842c28a5fdbad0160505ed8f")] [assembly: AssemblyProduct("com.github.manghomagnet")] [assembly: AssemblyTitle("MangHoMagnet")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.26.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace BepInEx { [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] [Conditional("CodeGeneration")] internal sealed class BepInAutoPluginAttribute : Attribute { public BepInAutoPluginAttribute(string? id = null, string? name = null, string? version = null) { } } } namespace BepInEx.Preloader.Core.Patching { [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] [Conditional("CodeGeneration")] internal sealed class PatcherAutoPluginAttribute : Attribute { public PatcherAutoPluginAttribute(string? id = null, string? name = null, string? version = null) { } } } namespace MangHoMagnet { [BepInPlugin("com.github.manghomagnet", "MangHoMagnet", "1.0.26")] public class Plugin : BaseUnityPlugin { private enum LobbyCheckStatus { Unknown, Checking, Timeout, Valid, Full, Invalid, SteamUnavailable } private enum ValidationMode { None, FormatOnly, Steam } private sealed class PostInfo { public string Id { get; } public string Url { get; } public string Title { get; } public string Author { get; } public string Date { get; } public string Views { get; } public PostInfo(string id, string title, string author, string date, string views, string url) { Id = id; Url = url; Title = title; Author = author; Date = date; Views = views; } public PostInfo WithDate(string date) { if (string.IsNullOrWhiteSpace(date) || date == Date) { return this; } return new PostInfo(Id, Title, Author, date, Views, Url); } } private sealed class PostSource { public string Id { get; private set; } public string Title { get; private set; } public string Author { get; private set; } public string Date { get; private set; } public string Views { get; private set; } public string Url { get; private set; } public DateTime AddedUtc { get; private set; } public PostSource(PostInfo postInfo) { Id = postInfo.Id; Title = postInfo.Title; Author = postInfo.Author; Date = postInfo.Date; Views = postInfo.Views; Url = postInfo.Url; AddedUtc = DateTime.UtcNow; } public void UpdateFrom(PostInfo postInfo) { Id = postInfo.Id; Title = postInfo.Title; Author = postInfo.Author; Date = postInfo.Date; Views = postInfo.Views; Url = postInfo.Url; AddedUtc = DateTime.UtcNow; } } private sealed class LobbyEntry { public string Link { get; } public uint AppId { get; private set; } public ulong LobbyId { get; private set; } public ulong HostId { get; private set; } public DateTime FirstSeenUtc { get; } public DateTime LastSeenUtc { get; private set; } public DateTime LastCheckUtc { get; set; } = DateTime.MinValue; public DateTime CheckStartedUtc { get; set; } = DateTime.MinValue; public bool IsCheckPending { get; set; } public LobbyCheckStatus Status { get; set; } public bool AutoJoinAttempted { get; set; } public int MemberCount { get; set; } = -1; public int MemberLimit { get; set; } = -1; public List<PostSource> Sources { get; } = new List<PostSource>(); public bool HasLobbyId => LobbyId != 0; public LobbyEntry(string link) { Link = link; FirstSeenUtc = DateTime.UtcNow; LastSeenUtc = FirstSeenUtc; Status = LobbyCheckStatus.Unknown; } public void Touch() { LastSeenUtc = DateTime.UtcNow; } public void SetLobbyInfo(uint appId, ulong lobbyId, ulong hostId) { AppId = appId; LobbyId = lobbyId; HostId = hostId; } public void AddOrUpdateSource(PostInfo postInfo) { PostInfo postInfo2 = postInfo; PostSource postSource = Sources.FirstOrDefault((PostSource source) => source.Url.Equals(postInfo2.Url, StringComparison.OrdinalIgnoreCase)); if (postSource != null) { postSource.UpdateFrom(postInfo2); } else { Sources.Add(new PostSource(postInfo2)); } } } private sealed class LobbyEntryView { public string Link { get; set; } = string.Empty; public string PostId { get; set; } = string.Empty; public string PostTitle { get; set; } = string.Empty; public string Author { get; set; } = string.Empty; public string PostDate { get; set; } = string.Empty; public string Views { get; set; } = string.Empty; public string PostUrl { get; set; } = string.Empty; public int MemberCount { get; set; } = -1; public int MemberLimit { get; set; } = -1; public int SourceCount { get; set; } public DateTime LastSeenUtc { get; set; } public LobbyCheckStatus Status { get; set; } } private sealed class ListParseDiagnostics { public string Title { get; set; } = string.Empty; public int RowCount { get; set; } public int SubjectMatchCount { get; set; } public int MissingTitleCount { get; set; } public int MissingHrefCount { get; set; } public int PostInfoCount { get; set; } } [CompilerGenerated] private sealed class <ExtractSteamLinks>d__160 : IEnumerable<string>, IEnumerable, IEnumerator<string>, IEnumerator, IDisposable { private int <>1__state; private string <>2__current; private int <>l__initialThreadId; private string html; public string <>3__html; private IEnumerator <>7__wrap1; string IEnumerator<string>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <ExtractSteamLinks>d__160(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } <>7__wrap1 = null; <>1__state = -2; } private bool MoveNext() { try { switch (<>1__state) { default: return false; case 0: <>1__state = -1; <>7__wrap1 = SteamLinkRegex.Matches(html).GetEnumerator(); <>1__state = -3; break; case 1: <>1__state = -3; break; } if (<>7__wrap1.MoveNext()) { Match match = (Match)<>7__wrap1.Current; <>2__current = match.Value; <>1__state = 1; return true; } <>m__Finally1(); <>7__wrap1 = null; return false; } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap1 is IDisposable disposable) { disposable.Dispose(); } } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] IEnumerator<string> IEnumerable<string>.GetEnumerator() { <ExtractSteamLinks>d__160 <ExtractSteamLinks>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; <ExtractSteamLinks>d__ = this; } else { <ExtractSteamLinks>d__ = new <ExtractSteamLinks>d__160(0); } <ExtractSteamLinks>d__.html = <>3__html; return <ExtractSteamLinks>d__; } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<string>)this).GetEnumerator(); } } private static readonly Regex SteamLinkRegex = new Regex("steam://joinlobby/\\d+/\\d+/\\d+", RegexOptions.IgnoreCase | RegexOptions.Compiled); private static readonly Regex SteamLinkParseRegex = new Regex("steam://joinlobby/(?<app>\\d+)/(?<lobby>\\d+)/(?<host>\\d+)", RegexOptions.IgnoreCase | RegexOptions.Compiled); private static readonly Regex TagRegex = new Regex("<.*?>", RegexOptions.Compiled | RegexOptions.Singleline); private readonly HashSet<string> _seenPostUrls = new HashSet<string>(StringComparer.OrdinalIgnoreCase); private readonly Dictionary<string, LobbyEntry> _lobbyByLink = new Dictionary<string, LobbyEntry>(StringComparer.OrdinalIgnoreCase); private readonly Dictionary<ulong, LobbyEntry> _lobbyById = new Dictionary<ulong, LobbyEntry>(); private readonly List<LobbyEntry> _lobbyEntries = new List<LobbyEntry>(); private readonly object _lobbyLock = new object(); private readonly SemaphoreSlim _pollGate = new SemaphoreSlim(1, 1); private readonly Queue<ulong> _pendingLobbyChecks = new Queue<ulong>(); private readonly Dictionary<string, PostInfo> _postInfoByUrl = new Dictionary<string, PostInfo>(StringComparer.OrdinalIgnoreCase); private readonly Dictionary<string, DateTime> _postLastFetchUtc = new Dictionary<string, DateTime>(StringComparer.OrdinalIgnoreCase); private readonly object _pendingLobbyLock = new object(); private const int MaxLobbyChecksPerFrame = 2; private const float LobbyCheckTimeoutSeconds = 2f; private const float LobbyCheckIntervalSeconds = 0.25f; private const float InGameCheckIntervalSeconds = 1f; private const float ColIdWidth = 80f; private const float ColAuthorWidth = 170f; private const float ColDateWidth = 200f; private const float ColViewsWidth = 70f; private const float MaxTitleWidth = 520f; private const float MinTitleWidth = 160f; private const float OpenPostWidth = 110f; private const float JoinButtonWidth = 260f; private const float ActionGapWidth = 10f; private const float ActionButtonSpacing = 6f; private const float ActionButtonHeight = 24f; private const float TableRightPadding = 12f; private HttpClient? _http; private Harmony? _harmony; private CancellationTokenSource? _cts; private DateTime _lastJoinUtc = DateTime.MinValue; private DateTime _lastPollUtc = DateTime.MinValue; private DateTime _nextPollUtc = DateTime.MinValue; private ConfigEntry<bool> _enabled; private ConfigEntry<string> _galleryListUrl; private ConfigEntry<string> _subjectKeyword; private ConfigEntry<bool> _pauseAutoPollInGame; private ConfigEntry<bool> _autoJoin; private ConfigEntry<int> _pollIntervalSeconds; private ConfigEntry<int> _maxPostsPerPoll; private ConfigEntry<int> _postRefetchCooldownSeconds; private ConfigEntry<int> _joinCooldownSeconds; private ConfigEntry<int> _maxLobbyEntries; private ConfigEntry<bool> _validateLobbies; private ConfigEntry<string> _validationMode; private ConfigEntry<int> _validationIntervalSeconds; private ConfigEntry<bool> _suppressLobbyPopups; private ConfigEntry<int> _expectedAppId; private ConfigEntry<string> _userAgent; private ConfigEntry<bool> _logFoundLinks; private ConfigEntry<KeyboardShortcut> _toggleKey; private ConfigEntry<bool> _showUiOnStart; private ConfigEntry<int> _uiWidth; private ConfigEntry<int> _uiHeight; private bool _showUi; private bool _inputBlockedByUs; private int _lobbyVersion; private int _uiVersion; private Vector2 _scrollPos; private Rect _windowRect = new Rect(20f, 20f, 1650f, 620f); private List<LobbyEntryView> _lobbySnapshot = new List<LobbyEntryView>(); private bool _steamValidationEnabled; private Callback<LobbyDataUpdate_t>? _lobbyDataCallback; private bool _loggedListEmpty; private bool _loggedNoLinks; private DateTime _lastInGameCheckUtc = DateTime.MinValue; private float _nextLobbyCheckTime; private bool _autoPollingPaused; private bool _isInGame; private Type? _cachedConnectionServiceType; private MethodInfo? _cachedGetServiceMethod; private Type? _cachedInRoomStateType; private Type? _cachedHostStateType; private GUIStyle? _headerStyle; private GUIStyle? _cellStyle; private GUIStyle? _dateStyle; private GUIStyle? _linkStyle; private GUIStyle? _smallLabelStyle; private GUIStyle? _menuLabelStyle; private GUIStyle? _windowStyle; private GUIStyle? _headerBoxStyle; private GUIStyle? _rowBoxStyle; private GUIStyle? _buttonStyle; private GUIStyle? _joinButtonStyle; private GUIStyle? _joinButtonValidStyle; private GUIStyle? _joinButtonFullStyle; private GUIStyle? _joinButtonInvalidStyle; private GUIStyle? _joinButtonTimeoutStyle; private GUIStyle? _toggleStyle; private Texture2D? _windowBackgroundTex; private Texture2D? _headerBackgroundTex; public const string Id = "com.github.manghomagnet"; internal static ManualLogSource Log { get; private set; } = null; internal static Plugin Instance { get; private set; } = null; public static string Name => "MangHoMagnet"; public static string Version => "1.0.26"; private void Awake() { Log = ((BaseUnityPlugin)this).Logger; Instance = this; try { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); } catch { } BindConfig(); ApplyHarmonyPatches(); TryInitializeSteamValidation(); _showUi = _showUiOnStart.Value; SetNextPollUtc(); _http = CreateHttpClient(_userAgent.Value); _cts = new CancellationTokenSource(); Task.Run(() => PollLoopAsync(_cts.Token)); Log.LogInfo((object)("Plugin " + Name + " is loaded!")); } private void OnDestroy() { _cts?.Cancel(); _http?.Dispose(); Harmony? harmony = _harmony; if (harmony != null) { harmony.UnpatchSelf(); } } private void UpdateInGameState() { if (!_pauseAutoPollInGame.Value || !_enabled.Value) { if (_autoPollingPaused) { _autoPollingPaused = false; _isInGame = false; SetNextPollUtc(); } return; } DateTime utcNow = DateTime.UtcNow; if (!((utcNow - _lastInGameCheckUtc).TotalSeconds < 1.0)) { _lastInGameCheckUtc = utcNow; bool isInGame = IsInGame(); bool autoPollingPaused = _autoPollingPaused; _isInGame = isInGame; _autoPollingPaused = _pauseAutoPollInGame.Value && _enabled.Value && _isInGame; if (autoPollingPaused && !_autoPollingPaused) { SetNextPollUtc(); } } } private bool IsInGame() { if (TryGetPhotonInRoom(out var inRoom)) { return inRoom; } if (TryGetConnectionState(out Type currentStateType)) { if ((object)_cachedInRoomStateType == null) { _cachedInRoomStateType = AccessTools.TypeByName("InRoomState"); } if ((object)_cachedHostStateType == null) { _cachedHostStateType = AccessTools.TypeByName("HostState"); } if (_cachedInRoomStateType != null && currentStateType == _cachedInRoomStateType) { return true; } if (_cachedHostStateType != null && currentStateType == _cachedHostStateType) { return true; } } return false; } private static bool TryGetPhotonInRoom(out bool inRoom) { inRoom = false; Type type = AccessTools.TypeByName("Photon.Pun.PhotonNetwork"); if (type == null) { return false; } PropertyInfo property = type.GetProperty("InRoom", BindingFlags.Static | BindingFlags.Public); if (property == null) { return false; } if (property.GetValue(null) is bool flag) { inRoom = flag; return true; } return false; } private bool TryGetConnectionState(out Type? currentStateType) { currentStateType = null; Type type = AccessTools.TypeByName("GameHandler"); if (type == null) { return false; } if ((object)_cachedConnectionServiceType == null) { _cachedConnectionServiceType = AccessTools.TypeByName("ConnectionService"); } if (_cachedConnectionServiceType == null) { return false; } if ((object)_cachedGetServiceMethod == null) { _cachedGetServiceMethod = type.GetMethods(BindingFlags.Static | BindingFlags.Public).FirstOrDefault((MethodInfo method) => method.Name == "GetService" && method.IsGenericMethodDefinition); } if (_cachedGetServiceMethod == null) { return false; } object obj = null; try { MethodInfo methodInfo = _cachedGetServiceMethod.MakeGenericMethod(_cachedConnectionServiceType); obj = methodInfo.Invoke(null, null); } catch { return false; } if (obj == null) { return false; } object obj3 = null; try { obj3 = _cachedConnectionServiceType.GetField("StateMachine", BindingFlags.Instance | BindingFlags.Public)?.GetValue(obj); if (obj3 == null) { obj3 = _cachedConnectionServiceType.GetProperty("StateMachine", BindingFlags.Instance | BindingFlags.Public)?.GetValue(obj); } } catch { return false; } if (obj3 == null) { return false; } try { object obj5 = obj3.GetType().GetProperty("CurrentState", BindingFlags.Instance | BindingFlags.Public)?.GetValue(obj3); if (obj5 == null) { return false; } currentStateType = obj5.GetType(); return true; } catch { return false; } } private void Update() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) KeyboardShortcut value = _toggleKey.Value; if (((KeyboardShortcut)(ref value)).IsDown()) { ToggleUi(); } UpdateInGameState(); if (_steamValidationEnabled) { try { SteamAPI.RunCallbacks(); } catch { } float unscaledTime = Time.unscaledTime; if (unscaledTime >= _nextLobbyCheckTime) { _nextLobbyCheckTime = unscaledTime + 0.25f; ProcessLobbyChecks(); UpdateCheckTimeouts(); } } } private void OnGUI() { //IL_00c5: 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_00f9: Expected O, but got Unknown //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) if (_showUi) { EnsureGuiStyles(); float maxWindowWidth = GetMaxWindowWidth(); if ((float)_uiWidth.Value > maxWindowWidth) { _uiWidth.Value = Mathf.RoundToInt(maxWindowWidth); } if (((Rect)(ref _windowRect)).width != (float)_uiWidth.Value || ((Rect)(ref _windowRect)).height != (float)_uiHeight.Value) { ((Rect)(ref _windowRect)).width = _uiWidth.Value; ((Rect)(ref _windowRect)).height = _uiHeight.Value; } int num = Volatile.Read(ref _lobbyVersion); if (num != _uiVersion) { _lobbySnapshot = GetLobbySnapshot(); _uiVersion = num; } _windowRect = GUILayout.Window(7813421, _windowRect, new WindowFunction(DrawWindowContents), "MangHoMagnet", _windowStyle ?? GUI.skin.window, Array.Empty<GUILayoutOption>()); } } private void DrawWindowContents(int id) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_03ba: Unknown result type (might be due to invalid IL or missing references) //IL_03e3: Unknown result type (might be due to invalid IL or missing references) //IL_03e8: Unknown result type (might be due to invalid IL or missing references) //IL_047f: Unknown result type (might be due to invalid IL or missing references) Color contentColor = GUI.contentColor; GUI.contentColor = Color.white; if (_headerStyle == null || _cellStyle == null || _linkStyle == null || _smallLabelStyle == null) { GUI.contentColor = contentColor; return; } GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); if (GUILayout.Button("Refresh Now", _buttonStyle ?? GUI.skin.button, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(140f) })) { RequestManualPoll(); } if (GUILayout.Button("Hide (F8)", _buttonStyle ?? GUI.skin.button, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) })) { ToggleUi(); } GUILayout.Space(8f); _autoJoin.Value = GUILayout.Toggle(_autoJoin.Value, "Auto Join", _toggleStyle ?? GUI.skin.toggle, Array.Empty<GUILayoutOption>()); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUIStyle val = _menuLabelStyle ?? _smallLabelStyle; GUILayout.Label("Last poll: " + ((_lastPollUtc == DateTime.MinValue) ? "-" : _lastPollUtc.ToLocalTime().ToString("HH:mm:ss")), val, Array.Empty<GUILayoutOption>()); GUILayout.Space(16f); int remainingSeconds = GetRemainingSeconds(); string text = ((!_enabled.Value) ? "Next refresh: paused" : (_autoPollingPaused ? "Next refresh: paused (in game)" : $"Next refresh: {remainingSeconds}s")); GUILayout.Label(text, val, Array.Empty<GUILayoutOption>()); GUILayout.EndHorizontal(); if (_autoPollingPaused) { GUILayout.Label("Auto scan paused while in game", val, Array.Empty<GUILayoutOption>()); } float scrollViewWidth = GetScrollViewWidth(); float scrollViewContentWidth = GetScrollViewContentWidth(scrollViewWidth); GUIStyle val2 = _headerBoxStyle ?? GUI.skin.box; GUIStyle style = _rowBoxStyle ?? GUI.skin.box; float contentWidthForStyle = GetContentWidthForStyle(scrollViewContentWidth, val2); float contentWidthForStyle2 = GetContentWidthForStyle(scrollViewContentWidth, style); float num = Mathf.Min(contentWidthForStyle, contentWidthForStyle2); float num2 = 80f; float num3 = 170f; float num4 = 200f; float num5 = 70f; float num6 = 386f; float num7 = num2 + num3 + num4 + num5 + num6 + 520f; float num8 = Mathf.Min(num - 12f, num7); num8 = Mathf.Max(300f, num8); float num9 = num8 - (num2 + num3 + num4 + num5 + num6); float num10 = Mathf.Clamp(num9, 160f, 520f); if (num10 > num9) { num10 = Math.Max(80f, num9); } float num11 = num8 + (float)val2.padding.left + (float)val2.padding.right; GUILayout.BeginHorizontal(val2, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(num11), GUILayout.ExpandWidth(false) }); GUILayout.Label("번호", _headerStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(num2) }); GUILayout.Label("제목", _headerStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(num10) }); GUILayout.Label("글쓴이", _headerStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(num3) }); GUILayout.Label("작성일", _headerStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(num4) }); GUILayout.Label("조회수", _headerStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(num5) }); GUILayout.Space(num6); GUILayout.EndHorizontal(); _scrollPos.x = 0f; _scrollPos = GUILayout.BeginScrollView(_scrollPos, false, true, (GUILayoutOption[])(object)new GUILayoutOption[3] { GUILayout.ExpandHeight(true), GUILayout.Width(scrollViewWidth), GUILayout.ExpandWidth(false) }); GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(num8), GUILayout.ExpandWidth(false) }); if (_lobbySnapshot.Count == 0) { GUILayout.Label("No lobby links yet.", Array.Empty<GUILayoutOption>()); } else { foreach (LobbyEntryView item in _lobbySnapshot) { DrawLobbyEntry(item, num2, num10, num3, num4, num5, num8, num6); } } GUILayout.EndVertical(); GUILayout.EndScrollView(); GUI.DragWindow(); GUI.contentColor = contentColor; } private void DrawLobbyEntry(LobbyEntryView entry, float colIdWidth, float titleWidth, float colAuthorWidth, float colDateWidth, float colViewsWidth, float rowContentWidth, float colActionsWidth) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_0143: Unknown result type (might be due to invalid IL or missing references) if (_cellStyle == null || _linkStyle == null) { return; } Color backgroundColor = GUI.backgroundColor; GUI.backgroundColor = GetStatusBackground(entry.Status); GUIStyle val = _rowBoxStyle ?? GUI.skin.box; float num = rowContentWidth + (float)val.padding.left + (float)val.padding.right; GUILayout.BeginVertical(val, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(num), GUILayout.ExpandWidth(false) }); GUI.backgroundColor = backgroundColor; GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(rowContentWidth), GUILayout.ExpandWidth(false) }); GUILayout.Label(DisplayOrDash(entry.PostId), _cellStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(colIdWidth) }); GUILayout.Label(DisplayOrDash(entry.PostTitle), _cellStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(titleWidth) }); GUILayout.Label(DisplayOrDash(entry.Author), _cellStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(colAuthorWidth) }); GUIStyle val2 = _dateStyle ?? _cellStyle; if (val2 != null && _cellStyle != null) { val2.normal.textColor = GetDateHighlightColor(entry.PostDate, _cellStyle.normal.textColor); } GUILayout.Label(DisplayOrDash(entry.PostDate), val2 ?? _cellStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(colDateWidth) }); GUILayout.Label(DisplayOrDash(entry.Views), _cellStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(colViewsWidth) }); GUILayout.EndHorizontal(); float num2 = Math.Max(0f, rowContentWidth - colActionsWidth); GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(rowContentWidth), GUILayout.ExpandWidth(false) }); GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(num2), GUILayout.ExpandWidth(false) }); GUILayout.Label(entry.Link, _linkStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(num2) }); GUILayout.EndVertical(); GUILayout.Space(10f); float num3 = 24f; if (!string.IsNullOrWhiteSpace(entry.PostUrl)) { if (GUILayout.Button("Open Post", _buttonStyle ?? GUI.skin.button, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(110f), GUILayout.Height(num3) })) { Application.OpenURL(entry.PostUrl); } } else { GUILayout.Space(110f); } GUILayout.Space(6f); string text = BuildJoinButtonLabel(entry); GUIStyle joinButtonStyle = GetJoinButtonStyle(entry); if (GUILayout.Button(text, joinButtonStyle, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(260f), GUILayout.Height(num3) })) { TryJoinLobby(entry.Link, force: true); } GUILayout.EndHorizontal(); GUILayout.EndVertical(); } private void ToggleUi() { _showUi = !_showUi; TrySetWindowBlockingInput(_showUi); } private static string DisplayOrDash(string value) { if (!string.IsNullOrWhiteSpace(value)) { return value; } return "-"; } private static Color GetStatusBackground(LobbyCheckStatus status) { //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: 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_00b4: Unknown result type (might be due to invalid IL or missing references) return (Color)(status switch { LobbyCheckStatus.Valid => new Color(0.86f, 0.97f, 0.9f), LobbyCheckStatus.Full => new Color(1f, 0.95f, 0.8f), LobbyCheckStatus.Invalid => new Color(1f, 0.86f, 0.86f), LobbyCheckStatus.Checking => new Color(0.86f, 0.93f, 1f), LobbyCheckStatus.Timeout => new Color(0.93f, 0.93f, 0.96f), LobbyCheckStatus.SteamUnavailable => new Color(0.94f, 0.94f, 0.95f), _ => GUI.backgroundColor, }); } private void EnsureGuiStyles() { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Expected O, but got Unknown //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Expected O, but got Unknown //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Expected O, but got Unknown //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: 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_00dd: Expected O, but got Unknown //IL_00e8: 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) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Expected O, but got Unknown //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Expected O, but got Unknown //IL_01c0: Unknown result type (might be due to invalid IL or missing references) //IL_01e4: Unknown result type (might be due to invalid IL or missing references) //IL_0204: Unknown result type (might be due to invalid IL or missing references) //IL_0228: Unknown result type (might be due to invalid IL or missing references) //IL_024c: Unknown result type (might be due to invalid IL or missing references) //IL_026c: Unknown result type (might be due to invalid IL or missing references) //IL_0281: Unknown result type (might be due to invalid IL or missing references) //IL_0286: Unknown result type (might be due to invalid IL or missing references) //IL_028f: Unknown result type (might be due to invalid IL or missing references) //IL_0299: Expected O, but got Unknown //IL_029e: Expected O, but got Unknown //IL_02f9: Unknown result type (might be due to invalid IL or missing references) //IL_030a: Unknown result type (might be due to invalid IL or missing references) //IL_031b: Unknown result type (might be due to invalid IL or missing references) //IL_032c: Unknown result type (might be due to invalid IL or missing references) //IL_033d: Unknown result type (might be due to invalid IL or missing references) //IL_034e: Unknown result type (might be due to invalid IL or missing references) //IL_035f: Unknown result type (might be due to invalid IL or missing references) //IL_0370: Unknown result type (might be due to invalid IL or missing references) //IL_0381: Unknown result type (might be due to invalid IL or missing references) //IL_0386: Unknown result type (might be due to invalid IL or missing references) //IL_038b: Unknown result type (might be due to invalid IL or missing references) //IL_0395: Expected O, but got Unknown //IL_039a: Expected O, but got Unknown //IL_03df: Unknown result type (might be due to invalid IL or missing references) //IL_03e4: Unknown result type (might be due to invalid IL or missing references) //IL_03e9: Unknown result type (might be due to invalid IL or missing references) //IL_03f3: Expected O, but got Unknown //IL_03f8: Expected O, but got Unknown //IL_0403: Unknown result type (might be due to invalid IL or missing references) //IL_040d: Expected O, but got Unknown //IL_047f: Unknown result type (might be due to invalid IL or missing references) //IL_0490: Unknown result type (might be due to invalid IL or missing references) //IL_04a1: Unknown result type (might be due to invalid IL or missing references) //IL_04b2: Unknown result type (might be due to invalid IL or missing references) //IL_04c3: Unknown result type (might be due to invalid IL or missing references) //IL_04d4: Unknown result type (might be due to invalid IL or missing references) //IL_04e5: Unknown result type (might be due to invalid IL or missing references) //IL_04f6: Unknown result type (might be due to invalid IL or missing references) //IL_0503: Unknown result type (might be due to invalid IL or missing references) //IL_050d: Expected O, but got Unknown //IL_0518: Unknown result type (might be due to invalid IL or missing references) //IL_052d: Unknown result type (might be due to invalid IL or missing references) //IL_0542: Unknown result type (might be due to invalid IL or missing references) //IL_0557: Unknown result type (might be due to invalid IL or missing references) //IL_056c: Unknown result type (might be due to invalid IL or missing references) //IL_0581: Unknown result type (might be due to invalid IL or missing references) //IL_0596: Unknown result type (might be due to invalid IL or missing references) //IL_05ab: Unknown result type (might be due to invalid IL or missing references) //IL_05cb: Unknown result type (might be due to invalid IL or missing references) //IL_05f0: Unknown result type (might be due to invalid IL or missing references) //IL_0615: Unknown result type (might be due to invalid IL or missing references) //IL_063a: Unknown result type (might be due to invalid IL or missing references) //IL_0654: Unknown result type (might be due to invalid IL or missing references) //IL_065e: Expected O, but got Unknown //IL_0686: Unknown result type (might be due to invalid IL or missing references) //IL_0697: Unknown result type (might be due to invalid IL or missing references) //IL_06a8: Unknown result type (might be due to invalid IL or missing references) //IL_06b9: Unknown result type (might be due to invalid IL or missing references) //IL_06ca: Unknown result type (might be due to invalid IL or missing references) //IL_06db: Unknown result type (might be due to invalid IL or missing references) //IL_06ec: Unknown result type (might be due to invalid IL or missing references) //IL_06fd: Unknown result type (might be due to invalid IL or missing references) //IL_070d: Unknown result type (might be due to invalid IL or missing references) //IL_0717: Expected O, but got Unknown //IL_0721: Unknown result type (might be due to invalid IL or missing references) //IL_072b: Expected O, but got Unknown //IL_0735: Unknown result type (might be due to invalid IL or missing references) //IL_073f: Expected O, but got Unknown //IL_0749: Unknown result type (might be due to invalid IL or missing references) //IL_0753: Expected O, but got Unknown //IL_075d: Unknown result type (might be due to invalid IL or missing references) //IL_0767: Expected O, but got Unknown //IL_0771: Unknown result type (might be due to invalid IL or missing references) //IL_077b: Expected O, but got Unknown //IL_0785: Unknown result type (might be due to invalid IL or missing references) //IL_078f: Expected O, but got Unknown //IL_0799: Unknown result type (might be due to invalid IL or missing references) //IL_07a3: Expected O, but got Unknown //IL_07ad: Unknown result type (might be due to invalid IL or missing references) //IL_07b7: Expected O, but got Unknown //IL_07c1: Unknown result type (might be due to invalid IL or missing references) //IL_07cb: Expected O, but got Unknown //IL_07d5: Unknown result type (might be due to invalid IL or missing references) //IL_07df: Expected O, but got Unknown if (_headerStyle == null) { _windowBackgroundTex = CreateSolidTexture(new Color(0.97f, 0.97f, 0.98f)); _headerBackgroundTex = CreateSolidTexture(new Color(0.9f, 0.92f, 0.95f)); _headerStyle = new GUIStyle(GUI.skin.label) { fontStyle = (FontStyle)1, alignment = (TextAnchor)3, wordWrap = false, clipping = (TextClipping)1 }; _cellStyle = new GUIStyle(GUI.skin.label) { alignment = (TextAnchor)3, wordWrap = false, clipping = (TextClipping)1 }; _dateStyle = new GUIStyle(_cellStyle); _linkStyle = new GUIStyle(GUI.skin.label) { alignment = (TextAnchor)3, wordWrap = true, clipping = (TextClipping)1 }; _smallLabelStyle = new GUIStyle(GUI.skin.label) { alignment = (TextAnchor)3, wordWrap = false }; _menuLabelStyle = new GUIStyle(_smallLabelStyle); _headerStyle.fontSize = Math.Max(_headerStyle.fontSize, 15); _cellStyle.fontSize = Math.Max(_cellStyle.fontSize, 14); _linkStyle.fontSize = Math.Max(_linkStyle.fontSize, 13); _smallLabelStyle.fontSize = Math.Max(_smallLabelStyle.fontSize + 1, 12); _menuLabelStyle.fontSize = Math.Max(_menuLabelStyle.fontSize + 4, 16); _headerStyle.normal.textColor = new Color(0.1f, 0.1f, 0.12f); _cellStyle.normal.textColor = new Color(0.12f, 0.12f, 0.14f); _dateStyle.normal.textColor = _cellStyle.normal.textColor; _linkStyle.normal.textColor = new Color(0.1f, 0.33f, 0.74f); _smallLabelStyle.normal.textColor = new Color(0.18f, 0.18f, 0.2f); _menuLabelStyle.normal.textColor = _cellStyle.normal.textColor; _windowStyle = new GUIStyle(GUI.skin.window) { padding = new RectOffset(12, 12, 22, 12) }; if ((Object)(object)_windowBackgroundTex != (Object)null) { _windowStyle.normal.background = _windowBackgroundTex; _windowStyle.onNormal.background = _windowBackgroundTex; } Color textColor = default(Color); ((Color)(ref textColor))..ctor(0.1f, 0.1f, 0.12f); _windowStyle.normal.textColor = textColor; _windowStyle.hover.textColor = textColor; _windowStyle.active.textColor = textColor; _windowStyle.focused.textColor = textColor; _windowStyle.onNormal.textColor = textColor; _windowStyle.onHover.textColor = textColor; _windowStyle.onActive.textColor = textColor; _windowStyle.onFocused.textColor = textColor; _headerBoxStyle = new GUIStyle(GUI.skin.box) { padding = new RectOffset(6, 6, 4, 4) }; if ((Object)(object)_headerBackgroundTex != (Object)null) { _headerBoxStyle.normal.background = _headerBackgroundTex; _headerBoxStyle.onNormal.background = _headerBackgroundTex; } _rowBoxStyle = new GUIStyle(GUI.skin.box) { padding = new RectOffset(6, 6, 4, 4) }; _buttonStyle = new GUIStyle(GUI.skin.button); Color textColor2 = default(Color); ((Color)(ref textColor2))..ctor(0.1f, 0.1f, 0.12f); _buttonStyle.fontSize = Math.Max(_buttonStyle.fontSize, 15); _buttonStyle.wordWrap = false; _buttonStyle.clipping = (TextClipping)1; _buttonStyle.fixedHeight = 24f; _buttonStyle.stretchHeight = false; _buttonStyle.normal.textColor = textColor2; _buttonStyle.hover.textColor = textColor2; _buttonStyle.active.textColor = textColor2; _buttonStyle.focused.textColor = textColor2; _buttonStyle.onNormal.textColor = textColor2; _buttonStyle.onHover.textColor = textColor2; _buttonStyle.onActive.textColor = textColor2; _buttonStyle.onFocused.textColor = textColor2; _joinButtonStyle = new GUIStyle(_buttonStyle); _joinButtonStyle.normal.textColor = Color.white; _joinButtonStyle.hover.textColor = Color.white; _joinButtonStyle.active.textColor = Color.white; _joinButtonStyle.focused.textColor = Color.white; _joinButtonStyle.onNormal.textColor = Color.white; _joinButtonStyle.onHover.textColor = Color.white; _joinButtonStyle.onActive.textColor = Color.white; _joinButtonStyle.onFocused.textColor = Color.white; _joinButtonValidStyle = CreateJoinStateStyle(_joinButtonStyle, new Color(0.1f, 0.55f, 0.24f)); _joinButtonFullStyle = CreateJoinStateStyle(_joinButtonStyle, new Color(0.78f, 0.42f, 0.05f)); _joinButtonInvalidStyle = CreateJoinStateStyle(_joinButtonStyle, new Color(0.8f, 0.12f, 0.12f)); _joinButtonTimeoutStyle = CreateJoinStateStyle(_joinButtonStyle, new Color(0.45f, 0.45f, 0.5f)); _toggleStyle = new GUIStyle(GUI.skin.toggle); _toggleStyle.fontSize = Math.Max(_toggleStyle.fontSize, 15); _toggleStyle.normal.textColor = textColor2; _toggleStyle.hover.textColor = textColor2; _toggleStyle.active.textColor = textColor2; _toggleStyle.focused.textColor = textColor2; _toggleStyle.onNormal.textColor = textColor2; _toggleStyle.onHover.textColor = textColor2; _toggleStyle.onActive.textColor = textColor2; _toggleStyle.onFocused.textColor = textColor2; _headerStyle.margin = new RectOffset(0, 0, 0, 0); _cellStyle.margin = new RectOffset(0, 0, 0, 0); _dateStyle.margin = new RectOffset(0, 0, 0, 0); _linkStyle.margin = new RectOffset(0, 0, 0, 0); _smallLabelStyle.margin = new RectOffset(0, 0, 0, 0); _menuLabelStyle.margin = new RectOffset(0, 0, 0, 0); _headerBoxStyle.margin = new RectOffset(0, 0, 0, 0); _rowBoxStyle.margin = new RectOffset(0, 0, 0, 0); _buttonStyle.margin = new RectOffset(0, 0, 0, 0); _joinButtonStyle.margin = new RectOffset(0, 0, 0, 0); _toggleStyle.margin = new RectOffset(0, 0, 0, 0); if (_joinButtonValidStyle != null) { _joinButtonValidStyle.margin = _joinButtonStyle.margin; _joinButtonValidStyle.fixedHeight = _joinButtonStyle.fixedHeight; _joinButtonValidStyle.stretchHeight = _joinButtonStyle.stretchHeight; } if (_joinButtonFullStyle != null) { _joinButtonFullStyle.margin = _joinButtonStyle.margin; _joinButtonFullStyle.fixedHeight = _joinButtonStyle.fixedHeight; _joinButtonFullStyle.stretchHeight = _joinButtonStyle.stretchHeight; } if (_joinButtonInvalidStyle != null) { _joinButtonInvalidStyle.margin = _joinButtonStyle.margin; _joinButtonInvalidStyle.fixedHeight = _joinButtonStyle.fixedHeight; _joinButtonInvalidStyle.stretchHeight = _joinButtonStyle.stretchHeight; } if (_joinButtonTimeoutStyle != null) { _joinButtonTimeoutStyle.margin = _joinButtonStyle.margin; _joinButtonTimeoutStyle.fixedHeight = _joinButtonStyle.fixedHeight; _joinButtonTimeoutStyle.stretchHeight = _joinButtonStyle.stretchHeight; } } } private void BindConfig() { //IL_0269: Unknown result type (might be due to invalid IL or missing references) _enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Enable MangHoMagnet."); _galleryListUrl = ((BaseUnityPlugin)this).Config.Bind<string>("General", "GalleryListUrl", "https://gall.dcinside.com/mgallery/board/lists?id=bingbong", "DCInside gallery list URL to scan."); _subjectKeyword = ((BaseUnityPlugin)this).Config.Bind<string>("Filter", "SubjectKeyword", string.Empty, "Ignored (no subject filtering; scans for Steam links in posts)."); _pollIntervalSeconds = ((BaseUnityPlugin)this).Config.Bind<int>("General", "PollIntervalSeconds", 10, "Seconds between list scans."); _pauseAutoPollInGame = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "PauseAutoPollInGame", true, "Pause automatic polling while in game (manual refresh still works)."); _maxPostsPerPoll = ((BaseUnityPlugin)this).Config.Bind<int>("General", "MaxPostsPerPoll", 50, "Maximum number of posts to scan per poll (minimum 50 to cover the first page)."); _postRefetchCooldownSeconds = ((BaseUnityPlugin)this).Config.Bind<int>("General", "PostRefetchCooldownSeconds", 60, "Minimum seconds between re-fetching the same post when metadata changes."); _maxLobbyEntries = ((BaseUnityPlugin)this).Config.Bind<int>("General", "MaxLobbyEntries", 200, "Maximum number of lobby links kept in memory."); _validateLobbies = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ValidateLobbies", true, "Enable lobby validation and highlight entries in the UI."); _validationMode = ((BaseUnityPlugin)this).Config.Bind<string>("General", "ValidationMode", "FormatOnly", "Validation mode: None, FormatOnly, Steam. Steam mode can trigger in-game dialogs."); _suppressLobbyPopups = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "SuppressLobbyPopups", true, "Auto-dismiss in-game lobby error dialogs while validating Steam lobbies."); _validationIntervalSeconds = ((BaseUnityPlugin)this).Config.Bind<int>("General", "ValidationIntervalSeconds", 60, "Minimum seconds between Steam lobby validation checks per link."); _expectedAppId = ((BaseUnityPlugin)this).Config.Bind<int>("General", "ExpectedAppId", 3527290, "Expected Steam App ID for lobby links."); _autoJoin = ((BaseUnityPlugin)this).Config.Bind<bool>("Join", "AutoJoin", false, "Automatically open valid Steam join links when found."); _joinCooldownSeconds = ((BaseUnityPlugin)this).Config.Bind<int>("Join", "JoinCooldownSeconds", 10, "Minimum seconds between automatic joins."); _userAgent = ((BaseUnityPlugin)this).Config.Bind<string>("Network", "UserAgent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36", "User-Agent header used for requests."); _logFoundLinks = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "LogFoundLinks", true, "Log newly discovered Steam join links."); _toggleKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("UI", "ToggleKey", new KeyboardShortcut((KeyCode)289, Array.Empty<KeyCode>()), "Toggle the lobby list window."); _showUiOnStart = ((BaseUnityPlugin)this).Config.Bind<bool>("UI", "ShowOnStart", false, "Show the lobby list window on startup."); _uiWidth = ((BaseUnityPlugin)this).Config.Bind<int>("UI", "WindowWidth", 1650, "Lobby list window width in pixels."); _uiHeight = ((BaseUnityPlugin)this).Config.Bind<int>("UI", "WindowHeight", 620, "Lobby list window height in pixels."); } private int GetRemainingSeconds() { if (_nextPollUtc == DateTime.MinValue) { return 0; } if (_autoPollingPaused || !_enabled.Value) { return 0; } return Math.Max(0, (int)Math.Ceiling((_nextPollUtc - DateTime.UtcNow).TotalSeconds)); } private void SetNextPollUtc() { int num = Math.Max(_pollIntervalSeconds.Value, 1); _nextPollUtc = DateTime.UtcNow.AddSeconds(num); } private float GetScrollViewWidth() { GUIStyle verticalScrollbar = GUI.skin.verticalScrollbar; float num = ((verticalScrollbar != null) ? verticalScrollbar.fixedWidth : 0f); if (num <= 0f) { num = 16f; } GUIStyle? windowStyle = _windowStyle; RectOffset val = ((windowStyle != null) ? windowStyle.padding : null) ?? GUI.skin.window.padding; int num2 = val.left + val.right; return Mathf.Max(((Rect)(ref _windowRect)).width - (float)num2 - 8f, 720f); } private float GetMaxWindowWidth() { GUIStyle verticalScrollbar = GUI.skin.verticalScrollbar; float num = ((verticalScrollbar != null) ? verticalScrollbar.fixedWidth : 0f); if (num <= 0f) { num = 16f; } GUIStyle? windowStyle = _windowStyle; RectOffset val = ((windowStyle != null) ? windowStyle.padding : null) ?? GUI.skin.window.padding; int num2 = val.left + val.right; float num3 = 1426f; float num4 = 720f + (float)num2 + 8f; float num5 = num3 + 12f + num + (float)num2 + 8f; return Mathf.Max(num4, num5); } private float GetScrollViewContentWidth(float viewWidth) { GUIStyle verticalScrollbar = GUI.skin.verticalScrollbar; float num = ((verticalScrollbar != null) ? verticalScrollbar.fixedWidth : 0f); if (num <= 0f) { num = 16f; } return Mathf.Max(viewWidth - num - 2f, 300f); } private static float GetContentWidthForStyle(float width, GUIStyle style) { if (style == null) { return width; } int num = style.padding.left + style.padding.right; return Mathf.Max(width - (float)num, 300f); } private void TryInitializeSteamValidation() { if (!_validateLobbies.Value) { _steamValidationEnabled = false; return; } if (GetValidationMode() != ValidationMode.Steam) { _steamValidationEnabled = false; return; } try { _lobbyDataCallback = Callback<LobbyDataUpdate_t>.Create((DispatchDelegate<LobbyDataUpdate_t>)OnLobbyDataUpdated); _steamValidationEnabled = true; } catch (Exception ex) { _steamValidationEnabled = false; Log.LogWarning((object)("Steam lobby validation disabled: " + ex.Message)); } } private void ApplyHarmonyPatches() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Expected O, but got Unknown //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Expected O, but got Unknown if (_harmony != null) { return; } try { _harmony = new Harmony("com.github.manghomagnet"); Type type = AccessTools.TypeByName("SteamLobbyHandler"); if (type == null) { Log.LogWarning((object)"Failed to find SteamLobbyHandler type for popup suppression."); return; } MethodInfo methodInfo = AccessTools.Method(type, "OnLobbyDataUpdate", (Type[])null, (Type[])null); if (methodInfo == null) { Log.LogWarning((object)"Failed to find SteamLobbyHandler.OnLobbyDataUpdate for popup suppression."); return; } HarmonyMethod val = new HarmonyMethod(typeof(Plugin), "SteamLobbyHandler_OnLobbyDataUpdate_Prefix", (Type[])null); _harmony.Patch((MethodBase)methodInfo, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } catch (Exception ex) { Log.LogWarning((object)("Failed to apply Harmony patches: " + ex.Message)); } } private static void SteamLobbyHandler_OnLobbyDataUpdate_Prefix(object __instance, ref LobbyDataUpdate_t param) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) Plugin instance = Instance; if (!((Object)(object)instance == (Object)null) && instance.ShouldSuppressLobbyPopup(__instance, param)) { param.m_bSuccess = 1; } } private bool ShouldSuppressLobbyPopup(object handler, LobbyDataUpdate_t param) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) if (!_suppressLobbyPopups.Value) { return false; } if (!_validateLobbies.Value || GetValidationMode() != ValidationMode.Steam) { return false; } if (param.m_bSuccess == 1) { return false; } if (handler == null) { return false; } return TryIsGameLobbyRequestActive(handler, param) == false; } private static bool? TryIsGameLobbyRequestActive(object handler, LobbyDataUpdate_t param) { //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Unknown result type (might be due to invalid IL or missing references) try { FieldInfo fieldInfo = AccessTools.Field(handler.GetType(), "m_currentlyFetchingGameVersion"); if (fieldInfo == null) { return null; } object value = fieldInfo.GetValue(handler); if (value == null) { return null; } Type type = value.GetType(); PropertyInfo property = type.GetProperty("IsSome", BindingFlags.Instance | BindingFlags.Public); if (property == null) { return null; } object value2 = property.GetValue(value); if (!(value2 is bool)) { return null; } if (!(bool)value2) { return false; } PropertyInfo property2 = type.GetProperty("Value", BindingFlags.Instance | BindingFlags.Public); if (property2 == null) { return true; } object value3 = property2.GetValue(value); if (value3 is CSteamID val) { return val.m_SteamID == param.m_ulSteamIDLobby; } FieldInfo fieldInfo2 = value3?.GetType().GetField("m_SteamID", BindingFlags.Instance | BindingFlags.Public); if (fieldInfo2 != null && value3 != null && fieldInfo2.GetValue(value3) is ulong num) { return num == param.m_ulSteamIDLobby; } return true; } catch { return null; } } private static HttpClient CreateHttpClient(string userAgent) { HttpClientHandler handler = new HttpClientHandler { AutomaticDecompression = (DecompressionMethods.GZip | DecompressionMethods.Deflate) }; HttpClient httpClient = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(10.0) }; if (!string.IsNullOrWhiteSpace(userAgent)) { httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(userAgent); } httpClient.DefaultRequestHeaders.Accept.ParseAdd("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); return httpClient; } private async Task<string?> FetchStringAsync(string url, CancellationToken token, string context) { if (_http == null) { return null; } try { using HttpResponseMessage response = await _http.GetAsync(url, token); if (!response.IsSuccessStatusCode) { Log.LogWarning((object)$"Failed to fetch {context}: {url} (status {(int)response.StatusCode} {response.ReasonPhrase})"); return null; } return await response.Content.ReadAsStringAsync(); } catch (Exception ex) { Log.LogWarning((object)("Failed to fetch " + context + ": " + url + " (" + ex.Message + ")")); return null; } } private async Task PollLoopAsync(CancellationToken token) { while (!token.IsCancellationRequested) { try { if (_enabled.Value && !_autoPollingPaused) { await PollOnceAsync(token); } } catch (OperationCanceledException) { } catch (Exception arg) { Log.LogWarning((object)$"Poll loop error: {arg}"); } int num = Math.Max(_pollIntervalSeconds.Value, 1); try { await Task.Delay(TimeSpan.FromSeconds(num), token); } catch (OperationCanceledException) { } } } private void RequestManualPoll() { if (_cts != null && !_cts.IsCancellationRequested) { Task.Run(() => PollOnceAsync(_cts.Token)); } } private async Task PollOnceAsync(CancellationToken token) { await _pollGate.WaitAsync(token); try { if (_http == null) { return; } string listUrl = (_galleryListUrl.Value ?? string.Empty).Trim(); if (listUrl.Length == 0) { return; } string text = await FetchStringAsync(listUrl, token, "list page"); if (string.IsNullOrWhiteSpace(text)) { return; } _lastPollUtc = DateTime.UtcNow; string subjectKeyword = (_subjectKeyword.Value ?? string.Empty).Trim(); int maxPosts = Math.Max(_maxPostsPerPoll.Value, 50); ListParseDiagnostics diagnostics; List<PostInfo> list = ExtractPostInfos(text, subjectKeyword, maxPosts, out diagnostics); if (list.Count == 0) { if (!_loggedListEmpty) { LogListDiagnostics(diagnostics, listUrl); _loggedListEmpty = true; } return; } _loggedListEmpty = false; int scannedPosts = 0; int foundLinks = 0; foreach (PostInfo postInfo in list) { if (token.IsCancellationRequested) { return; } bool flag = _seenPostUrls.Add(postInfo.Url); bool flag2 = flag; if (!flag && _postInfoByUrl.TryGetValue(postInfo.Url, out PostInfo value) && HasListMetadataChanged(value, postInfo)) { flag2 = true; } _postInfoByUrl[postInfo.Url] = postInfo; if (!flag2 || (!flag && ShouldThrottlePostFetch(postInfo.Url))) { continue; } string text2 = await FetchStringAsync(postInfo.Url, token, "post"); if (string.IsNullOrWhiteSpace(text2)) { continue; } scannedPosts++; string text3 = ExtractExactPostDate(text2); PostInfo postInfo2 = (string.IsNullOrWhiteSpace(text3) ? postInfo : postInfo.WithDate(text3)); TrackPostFetch(postInfo.Url); foreach (string item in ExtractSteamLinks(text2)) { if (_logFoundLinks.Value) { Log.LogInfo((object)("Found lobby link: " + item + " (post: " + postInfo2.Url + ")")); } AddLobbyEntry(item, postInfo2); TryJoinLobby(item, force: false); foundLinks++; } } if (foundLinks == 0) { if (!_loggedNoLinks) { Log.LogWarning((object)$"No lobby links found this poll. ScannedPosts={scannedPosts}, Rows={diagnostics.RowCount}, SubjectMatches={diagnostics.SubjectMatchCount}, Title='{diagnostics.Title}'."); _loggedNoLinks = true; } } else { _loggedNoLinks = false; } } finally { SetNextPollUtc(); _pollGate.Release(); } } private bool ShouldThrottlePostFetch(string url) { if (string.IsNullOrWhiteSpace(url)) { return false; } int num = Math.Max(_postRefetchCooldownSeconds.Value, 0); if (num <= 0) { return false; } if (_postLastFetchUtc.TryGetValue(url, out var value) && DateTime.UtcNow - value < TimeSpan.FromSeconds(num)) { return true; } return false; } private void TrackPostFetch(string url) { if (!string.IsNullOrWhiteSpace(url)) { _postLastFetchUtc[url] = DateTime.UtcNow; } } private List<PostInfo> ExtractPostInfos(string html, string subjectKeyword, int maxPosts, out ListParseDiagnostics diagnostics) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown diagnostics = new ListParseDiagnostics(); if (string.IsNullOrWhiteSpace(html)) { return new List<PostInfo>(); } HtmlParser val = new HtmlParser(); IHtmlDocument val2 = val.ParseDocument(html); diagnostics.Title = ((IDocument)val2).Title ?? string.Empty; IHtmlCollection<IElement> val3 = ((IParentNode)val2).QuerySelectorAll("tr.ub-content"); diagnostics.RowCount = val3.Length; List<PostInfo> list = new List<PostInfo>(); foreach (IElement item in (IEnumerable<IElement>)val3) { if (maxPosts <= 0) { break; } PostInfo postInfo = TryExtractPostInfo(item, subjectKeyword, diagnostics); if (postInfo != null) { list.Add(postInfo); maxPosts--; } } diagnostics.PostInfoCount = list.Count; return list; } private static PostInfo? TryExtractPostInfo(IElement row, string subjectKeyword, ListParseDiagnostics diagnostics) { if (!SubjectMatches(row, subjectKeyword)) { return null; } diagnostics.SubjectMatchCount++; IElement val = ((IParentNode)row).QuerySelector("td.gall_tit a"); if (val == null) { diagnostics.MissingTitleCount++; return null; } string attribute = val.GetAttribute("href"); if (string.IsNullOrWhiteSpace(attribute)) { diagnostics.MissingHrefCount++; return null; } if (!attribute.Contains("board/view", StringComparison.OrdinalIgnoreCase)) { return null; } string text = CleanText(((INode)val).TextContent); int num = ExtractReplyCount(row); if (num > 0 && !text.Contains($"[{num}]", StringComparison.Ordinal)) { text = $"{text} [{num}]"; } string id = ExtractPostId(row); string author = ExtractAuthor(row); string date = ExtractPostDate(row); string views = ExtractViewCount(row); string url = NormalizeUrl(WebUtility.HtmlDecode(attribute)); return new PostInfo(id, text, author, date, views, url); } private static bool SubjectMatches(IElement row, string subjectKeyword) { return true; } private static string ExtractPostId(IElement row) { string text = row.GetAttribute("data-no"); if (string.IsNullOrWhiteSpace(text)) { IElement obj = ((IParentNode)row).QuerySelector("td.gall_num"); text = CleanText(((obj != null) ? ((INode)obj).TextContent : null) ?? string.Empty); } return text ?? string.Empty; } private static string ExtractAuthor(IElement row) { IElement obj = ((IParentNode)row).QuerySelector("td.gall_writer"); return CleanText(((obj != null) ? ((INode)obj).TextContent : null) ?? string.Empty); } private static string ExtractPostDate(IElement row) { IElement val = ((IParentNode)row).QuerySelector("td.gall_date"); if (val == null) { return string.Empty; } string full = val.GetAttribute("title") ?? string.Empty; string shortText = ((INode)val).TextContent ?? string.Empty; return FormatDate(full, shortText); } private static string ExtractExactPostDate(string html) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Expected O, but got Unknown if (string.IsNullOrWhiteSpace(html)) { return string.Empty; } HtmlParser val = new HtmlParser(); IHtmlDocument val2 = val.ParseDocument(html); foreach (IElement item in (IEnumerable<IElement>)((IParentNode)val2).QuerySelectorAll(".gall_date")) { string text = item.GetAttribute("title"); if (string.IsNullOrWhiteSpace(text)) { text = ((INode)item).TextContent; } string value = CleanText(text ?? string.Empty); if (!string.IsNullOrWhiteSpace(value)) { if (TryParseExactDate(value, out var parsed)) { return parsed.ToString("yyyy.MM.dd HH:mm:ss", CultureInfo.InvariantCulture); } string text2 = NormalizeExactDateText(value); if (!string.IsNullOrWhiteSpace(text2)) { return text2; } } } return string.Empty; } private static string ExtractViewCount(IElement row) { IElement obj = ((IParentNode)row).QuerySelector("td.gall_count"); string text = CleanText(((obj != null) ? ((INode)obj).TextContent : null) ?? string.Empty); if (string.IsNullOrWhiteSpace(text)) { return text; } string text2 = Regex.Replace(text, "\\D", string.Empty); if (!string.IsNullOrWhiteSpace(text2)) { return text2; } return text; } private static int ExtractReplyCount(IElement row) { IElement obj = ((IParentNode)row).QuerySelector("span.reply_num"); return ParseIntFromText((obj != null) ? ((INode)obj).TextContent : null); } private static int ParseIntFromText(string? text) { if (string.IsNullOrWhiteSpace(text)) { return 0; } Match match = Regex.Match(text, "\\d+"); if (!match.Success || !int.TryParse(match.Value, out var result)) { return 0; } return result; } private static string FormatDate(string full, string shortText) { string s = (full ?? string.Empty).Trim(); if (DateTime.TryParseExact(s, new string[2] { "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm" }, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out var result) || DateTime.TryParse(s, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out result) || DateTime.TryParse(s, out result)) { return result.ToString("MM-dd HH:mm"); } return CleanText(shortText); } private static bool TryParseExactDate(string value, out DateTime parsed) { if (!DateTime.TryParseExact(value, new string[6] { "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm" }, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out parsed)) { return DateTime.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out parsed); } return true; } private static string NormalizeExactDateText(string value) { Match match = Regex.Match(value, "(?<date>\\d{4}[./-]\\d{2}[./-]\\d{2})\\s+(?<time>\\d{2}:\\d{2}(?::\\d{2})?)"); if (!match.Success) { return value; } string text = match.Groups["date"].Value.Replace('-', '.').Replace('/', '.'); string text2 = match.Groups["time"].Value; if (text2.Length == 5) { text2 += ":00"; } return text + " " + text2; } private static bool HasListMetadataChanged(PostInfo previous, PostInfo current) { if (!string.Equals(previous.Title, current.Title, StringComparison.Ordinal)) { return true; } if (!string.Equals(previous.Author, current.Author, StringComparison.Ordinal)) { return true; } if (!string.Equals(previous.Date, current.Date, StringComparison.Ordinal)) { return true; } if (!string.Equals(previous.Views, current.Views, StringComparison.Ordinal)) { if (TryParseViewCount(previous.Views, out var count) && TryParseViewCount(current.Views, out var count2)) { return count2 - count >= 2; } return true; } return false; } private ValidationMode GetValidationMode() { string value = (_validationMode.Value ?? string.Empty).Trim(); if (string.IsNullOrWhiteSpace(value)) { return ValidationMode.FormatOnly; } if (Enum.TryParse<ValidationMode>(value, ignoreCase: true, out var result)) { return result; } return ValidationMode.FormatOnly; } private static string NormalizeUrl(string href) { if (href.StartsWith("http", StringComparison.OrdinalIgnoreCase)) { return href; } if (href.StartsWith("//", StringComparison.OrdinalIgnoreCase)) { return "https:" + href; } if (href.StartsWith("/", StringComparison.OrdinalIgnoreCase)) { return "https://gall.dcinside.com" + href; } return "https://gall.dcinside.com/" + href; } private static string CleanText(string html) { if (string.IsNullOrWhiteSpace(html)) { return string.Empty; } string value = TagRegex.Replace(html, string.Empty); return WebUtility.HtmlDecode(value).Trim(); } private static Color GetDateHighlightColor(string? dateText, Color baseColor) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0085: 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_00db: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) if (string.IsNullOrWhiteSpace(dateText)) { return baseColor; } if (!TryParseExactDate(dateText, out var parsed)) { return baseColor; } TimeSpan timeSpan = DateTime.Now - parsed; if (timeSpan < TimeSpan.Zero) { timeSpan = TimeSpan.Zero; } if (timeSpan <= TimeSpan.FromMinutes(10.0)) { return new Color(0.12f, 0.7f, 0.18f); } if (timeSpan <= TimeSpan.FromHours(1.0)) { return new Color(0.22f, 0.62f, 0.2f); } if (timeSpan <= TimeSpan.FromHours(3.0)) { return new Color(0.92f, 0.78f, 0.22f); } if (timeSpan <= TimeSpan.FromHours(12.0)) { return new Color(0.95f, 0.55f, 0.15f); } if (timeSpan <= TimeSpan.FromHours(24.0)) { return new Color(0.6f, 0.6f, 0.6f); } return baseColor; } private string BuildLinkInfoText(LobbyEntryView entry) { string statusLabel = GetStatusLabel(entry); string membersLabel = GetMembersLabel(entry); if (string.IsNullOrWhiteSpace(membersLabel)) { return statusLabel; } return statusLabel + " | " + membersLabel; } private string BuildJoinButtonLabel(LobbyEntryView entry) { bool flag = entry.MemberCount >= 0 && entry.MemberLimit > 0; if (flag && entry.MemberCount >= entry.MemberLimit) { return $"Join (Full | Members {entry.MemberCount}/{entry.MemberLimit})"; } return entry.Status switch { LobbyCheckStatus.Invalid => "Join (Invalid)", LobbyCheckStatus.Timeout => "Join (Timeout)", LobbyCheckStatus.Full => flag ? $"Join (Full | Members {entry.MemberCount}/{entry.MemberLimit})" : "Join (Full)", LobbyCheckStatus.Valid => flag ? $"Join (Members {entry.MemberCount}/{entry.MemberLimit})" : "Join (Valid)", LobbyCheckStatus.Checking => "Join (Checking)", LobbyCheckStatus.SteamUnavailable => "Join (Steam offline)", _ => "Join", }; } private GUIStyle GetJoinButtonStyle(LobbyEntryView entry) { GUIStyle val = _joinButtonStyle ?? _buttonStyle ?? GUI.skin.button; bool flag = entry.MemberCount >= 0 && entry.MemberLimit > 0 && entry.MemberCount >= entry.MemberLimit; if (entry.Status == LobbyCheckStatus.Invalid) { return _joinButtonInvalidStyle ?? val; } if (entry.Status == LobbyCheckStatus.Timeout) { return _joinButtonTimeoutStyle ?? val; } if (flag || entry.Status == LobbyCheckStatus.Full) { return _joinButtonFullStyle ?? val; } if (entry.Status == LobbyCheckStatus.Valid) { return _joinButtonValidStyle ?? val; } return val; } private static GUIStyle CreateJoinStateStyle(GUIStyle baseStyle, Color color) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0055: 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) GUIStyle val = new GUIStyle(baseStyle); val.normal.textColor = color; val.hover.textColor = color; val.active.textColor = color; val.focused.textColor = color; val.onNormal.textColor = color; val.onHover.textColor = color; val.onActive.textColor = color; val.onFocused.textColor = color; return val; } private string GetStatusLabel(LobbyEntryView entry) { return entry.Status switch { LobbyCheckStatus.Unknown => "Not checked", LobbyCheckStatus.Checking => "Checking", LobbyCheckStatus.Timeout => "Timeout", LobbyCheckStatus.Valid => (GetValidationMode() == ValidationMode.FormatOnly) ? "Valid (format)" : "Valid", LobbyCheckStatus.Full => "Full", LobbyCheckStatus.Invalid => "Invalid", LobbyCheckStatus.SteamUnavailable => "Steam unavailable", _ => "Unknown", }; } private static string GetMembersLabel(LobbyEntryView entry) { if (entry.MemberLimit > 0 && entry.MemberCount >= 0) { return $"Members {entry.MemberCount}/{entry.MemberLimit}"; } if (entry.MemberCount >= 0) { return $"Members {entry.MemberCount}"; } return string.Empty; } private static Texture2D CreateSolidTexture(Color color) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown //IL_000b: Unknown result type (might be due to invalid IL or missing references) Texture2D val = new Texture2D(1, 1); val.SetPixel(0, 0, color); val.Apply(); return val; } private void LogListDiagnostics(ListParseDiagnostics diagnostics, string listUrl) { Log.LogWarning((object)$"List parse returned 0 posts. Rows={diagnostics.RowCount}, SubjectMatches={diagnostics.SubjectMatchCount}, MissingTitle={diagnostics.MissingTitleCount}, MissingHref={diagnostics.MissingHrefCount}, Title='{diagnostics.Title}', Url={listUrl}"); } [IteratorStateMachine(typeof(<ExtractSteamLinks>d__160))] private IEnumerable<string> ExtractSteamLinks(string html) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <ExtractSteamLinks>d__160(-2) { <>3__html = html }; } private static bool TryParseLobbyLink(string link, out uint appId, out ulong lobbyId, out ulong hostId) { appId = 0u; lobbyId = 0uL; hostId = 0uL; Match match = SteamLinkParseRegex.Match(link); if (!match.Success) { return false; } if (uint.TryParse(match.Groups["app"].Value, out appId) && ulong.TryParse(match.Groups["lobby"].Value, out lobbyId)) { return ulong.TryParse(match.Groups["host"].Value, out hostId); } return false; } private void OnLobbyDataUpdated(LobbyDataUpdate_t callback) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) ulong ulSteamIDLobby = callback.m_ulSteamIDLobby; LobbyEntry value; lock (_lobbyLock) { if (!_lobbyById.TryGetValue(ulSteamIDLobby, out value)) { return; } value.IsCheckPending = false; value.CheckStartedUtc = DateTime.MinValue; } if (callback.m_bSuccess == 0) { lock (_lobbyLock) { value.Status = LobbyCheckStatus.Invalid; value.MemberCount = -1; value.MemberLimit = -1; } } else { try { CSteamID val = default(CSteamID); ((CSteamID)(ref val))..ctor(ulSteamIDLobby); int numLobbyMembers = SteamMatchmaking.GetNumLobbyMembers(val); int lobbyMemberLimit = SteamMatchmaking.GetLobbyMemberLimit(val); LobbyCheckStatus lobbyCheckStatus = LobbyCheckStatus.Valid; if (lobbyMemberLimit > 0 && numLobbyMembers >= lobbyMemberLimit) { lobbyCheckStatus = LobbyCheckStatus.Full; } lock (_lobbyLock) { value.Status = lobbyCheckStatus; value.MemberCount = numLobbyMembers; value.MemberLimit = lobbyMemberLimit; } if (lobbyCheckStatus == LobbyCheckStatus.Valid) { TryJoinLobby(value.Link, force: false); } } catch (Exception ex) { Log.LogWarning((object)("Steam lobby validation error: " + ex.Message)); lock (_lobbyLock) { value.Status = LobbyCheckStatus.SteamUnavailable; value.MemberCount = -1; value.MemberLimit = -1; } } } Interlocked.Increment(ref _lobbyVersion); } private void ProcessLobbyChecks() { //IL_0094: Unknown result type (might be due to invalid IL or missing references) int num = 0; while (num < 2) { ulong num2; lock (_pendingLobbyLock) { if (_pendingLobbyChecks.Count == 0) { break; } num2 = _pendingLobbyChecks.Dequeue(); } LobbyEntry value; lock (_lobbyLock) { if (!_lobbyById.TryGetValue(num2, out value) || !value.IsCheckPending) { continue; } value.CheckStartedUtc = DateTime.UtcNow; goto IL_0091; } IL_0091: bool flag = false; try { flag = SteamMatchmaking.RequestLobbyData(new CSteamID(num2)); } catch (Exception ex) { Log.LogWarning((object)("Steam lobby validation failed: " + ex.Message)); } if (!flag) { lock (_lobbyLock) { if (_lobbyById.TryGetValue(num2, out value)) { value.IsCheckPending = false; value.CheckStartedUtc = DateTime.MinValue; value.Status = LobbyCheckStatus.SteamUnavailable; } } Interlocked.Increment(ref _lobbyVersion); } num++; } } private void UpdateCheckTimeouts() { DateTime utcNow = DateTime.UtcNow; bool flag = false; lock (_lobbyLock) { foreach (LobbyEntry lobbyEntry in _lobbyEntries) { if (lobbyEntry.IsCheckPending && !(lobbyEntry.CheckStartedUtc == DateTime.MinValue) && !(utcNow - lobbyEntry.CheckStartedUtc < TimeSpan.FromSeconds(2.0))) { lobbyEntry.IsCheckPending = false; lobbyEntry.CheckStartedUtc = DateTime.MinValue; lobbyEntry.Status = LobbyCheckStatus.Timeout; lobbyEntry.MemberCount = -1; lobbyEntry.MemberLimit = -1; flag = true; } } } if (flag) { Interlocked.Increment(ref _lobbyVersion); } } private void AddLobbyEntry(string link, PostInfo postInfo) { if (string.IsNullOrWhiteSpace(link)) { return; } bool flag = false; ulong num = 0uL; lock (_lobbyLock) { if (!_lobbyByLink.TryGetValue(link, out LobbyEntry value)) { value = new LobbyEntry(link); _lobbyByLink[link] = value; _lobbyEntries.Add(value); } value.AddOrUpdateSource(postInfo); value.Touch(); TrimLobbyEntries(); if (!value.HasLobbyId) { if (TryParseLobbyLink(link, out var appId, out var lobbyId, out var hostId)) { value.SetLobbyInfo(appId, lobbyId, hostId); _lobbyById[lobbyId] = value; } else { value.Status = LobbyCheckStatus.Invalid; value.IsCheckPending = false; value.CheckStartedUtc = DateTime.MinValue; } } if (value.HasLobbyId) { uint num2 = (uint)Math.Max(_expectedAppId.Value, 0); if (num2 != 0 && value.AppId != num2) { value.Status = LobbyCheckStatus.Invalid; value.MemberCount = -1; value.MemberLimit = -1; value.IsCheckPending = false; value.CheckStartedUtc = DateTime.MinValue; } else { ValidationMode validationMode = GetValidationMode(); if (_validateLobbies.Value) { switch (validationMode) { case ValidationMode.None: break; case ValidationMode.FormatOnly: value.Status = LobbyCheckStatus.Valid; value.MemberCount = -1; value.MemberLimit = -1; value.IsCheckPending = false; value.CheckStartedUtc = DateTime.MinValue; goto end_IL_0018; default: if (_steamValidationEnabled && !value.IsCheckPending) { int num3 = Math.Max(_validationIntervalSeconds.Value, 5); if (value.LastCheckUtc == DateTime.MinValue || DateTime.UtcNow - value.LastCheckUtc >= TimeSpan.FromSeconds(num3)) { value.LastCheckUtc = DateTime.UtcNow; value.IsCheckPending = true; value.Status = LobbyCheckStatus.Checking; value.MemberCount = -1; value.MemberLimit = -1; value.CheckStartedUtc = DateTime.UtcNow; flag = true; num = value.LobbyId; } } else if (_steamValidationEnabled) { value.Status = LobbyCheckStatus.Checking; value.MemberCount = -1; value.MemberLimit = -1; } else { value.Status = LobbyCheckStatus.SteamUnavailable; value.MemberCount = -1; value.MemberLimit = -1; value.IsCheckPending = false; value.CheckStartedUtc = DateTime.MinValue; } goto end_IL_0018; } } value.Status = LobbyCheckStatus.Unknown; value.MemberCount = -1; value.MemberLimit = -1; value.IsCheckPending = false; value.CheckStartedUtc = DateTime.MinValue; } } end_IL_0018:; } if (flag && num != 0L) { lock (_pendingLobbyLock) { _pendingLobbyChecks.Enqueue(num); } } Interlocked.Increment(ref _lobbyVersion); } private void TrimLobbyEntries() { int num = Math.Max(_maxLobbyEntries.Value, 10); while (_lobbyEntries.Count > num) { LobbyEntry lobbyEntry = _lobbyEntries.OrderBy((LobbyEntry e) => e.FirstSeenUtc).First(); _lobbyEntries.Remove(lobbyEntry); _lobbyByLink.Remove(lobbyEntry.Link); } } private List<LobbyEntryView> GetLobbySnapshot() { lock (_lobbyLock) { return (from @group in _lobbyEntries.Select(delegate(LobbyEntry entry) { PostSource source = entry.Sources.OrderByDescending((PostSource item) => item.AddedUtc).FirstOrDefault(); long sortPostId = entry.Sources.Select((PostSource item) => ParsePostId(item.Id)).DefaultIfEmpty(0L).Max(); return new { Entry = entry, Source = source, SortPostId = sortPostId }; }).GroupBy(item => (!string.IsNullOrWhiteSpace(item.Source?.Id)) ? item.Source.Id : item.Entry.Link, StringComparer.OrdinalIgnoreCase) select (from item in @group orderby GetStatusSortRank(item.Entry.Status) descending, item.Entry.LastSeenUtc descending select item).First() into item orderby item.SortPostId descending, item.Entry.LastSeenUtc descending select new LobbyEntryView { Link = item.Entry.Link, SourceCount = item.Entry.Sources.Count, LastSeenUtc = item.Entry.LastSeenUtc, PostUrl = (item.Source?.Url ?? string.Empty), PostId = (item.Source?.Id ?? string.Empty), PostTitle = (item.Source?.Title ?? string.Empty), Author = (item.Source?.Author ?? string.Empty), PostDate = (item.Source?.Date ?? string.Empty), Views = (item.Source?.Views ?? string.Empty), MemberCount = item.Entry.MemberCount, MemberLimit = item.Entry.MemberLimit, Status = item.Entry.Status }).ToList(); } } private static int GetStatusSortRank(LobbyCheckStatus status) { return status switch { LobbyCheckStatus.Valid => 5, LobbyCheckStatus.Full => 4, LobbyCheckStatus.Checking => 3, LobbyCheckStatus.Unknown => 2, LobbyCheckStatus.Timeout => 1, LobbyCheckStatus.SteamUnavailable => 1, LobbyCheckStatus.Invalid => 0, _ => 0, }; } private static long ParsePostId(string id) { if (long.TryParse(id, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { return result; } return 0L; } private static bool TryParseViewCount(string value, out int count) { count = 0; if (string.IsNullOrWhiteSpace(value)) { return false; } string text = new string(value.Where(char.IsDigit).ToArray()); if (text.Length == 0) { return false; } return int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out count); } private void TryJoinLobby(string link, bool force) { if (!force && !_autoJoin.Value) { return; } int num = Math.Max(_joinCooldownSeconds.Value, 0); if (!force && num > 0 && DateTime.UtcNow - _lastJoinUtc < TimeSpan.FromSeconds(num)) { return; } if (!force) { if (!TryMarkAutoJoin(link)) { return; } } else { MarkAutoJoinAttempted(link); } try { ProcessStartInfo startInfo = new ProcessStartInfo(link) { UseShellExecute = true }; Process.Start(startInfo); _lastJoinUtc = DateTime.UtcNow; Log.LogInfo((object)("Joining lobby: " + link)); } catch (Exception ex) { Log.LogWarning((object)("Failed to open lobby link: " + ex.Message)); } } private bool TryMarkAutoJoin(string link) { if (string.IsNullOrWhiteSpace(link)) { return false; } lock (_lobbyLock) { if (!_lobbyByLink.TryGetValue(link, out LobbyEntry value)) { return false; } if (value.Status != LobbyCheckStatus.Valid) { return false; } if (value.AutoJoinAttempted) { return false; } value.AutoJoinAttempted = true; return true; } } private void MarkAutoJoinAttempted(string link) { if (string.IsNullOrWhiteSpace(link)) { return; } lock (_lobbyLock) { if (_lobbyByLink.TryGetValue(link, out LobbyEntry value)) { value.AutoJoinAttempted = true; } } } private void TrySetWindowBlockingInput(bool block) { try { Type type = Type.GetType("GUIManager, Assembly-CSharp"); if (type == null) { return; } object obj = type.GetProperty("instance", BindingFlags.Static | BindingFlags.Public)?.GetValue(null); if (obj == null) { return; } object obj2 = null; FieldInfo field = type.GetField("windowBlockingInput", BindingFlags.Instance | BindingFlags.Public); obj2 = ((!(field != null)) ? type.GetProperty("windowBlockingInput", BindingFlags.Instance | BindingFlags.Public)?.GetValue(obj) : field.GetValue(obj)); bool flag = default(bool); int num; if (obj2 is bool) { flag = (bool)obj2; num = 1; } else { num = 0; } bool flag2 = (byte)((uint)num & (flag ? 1u : 0u)) != 0; if (block) { if (!flag2) { SetWindowBlocking(obj, type, value: true); _inputBlockedByUs = true; } } else if (_inputBlockedByUs) { SetWindowBlocking(obj, type, value: false); _inputBlockedByUs = false; } } catch { } } private static void SetWindowBlocking(object instance, Type type, bool value) { FieldInfo field = type.GetField("windowBlockingInput", BindingFlags.Instance | BindingFlags.Public); if (field != null) { field.SetValue(instance, value); } else { type.GetProperty("windowBlockingInput", BindingFlags.Instance | BindingFlags.Public)?.SetValue(instance, value); } } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class IgnoresAccessChecksToAttribute : Attribute { public IgnoresAccessChecksToAttribute(string assemblyName) { } } }
AngleSharp.dll
Decompiled 5 days ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using AngleSharp.Attributes; using AngleSharp.Browser; using AngleSharp.Browser.Dom; using AngleSharp.Browser.Dom.Events; using AngleSharp.Common; using AngleSharp.Css; using AngleSharp.Css.Dom; using AngleSharp.Css.Parser; using AngleSharp.Dom; using AngleSharp.Dom.Events; using AngleSharp.Html; using AngleSharp.Html.Dom; using AngleSharp.Html.Dom.Events; using AngleSharp.Html.Forms; using AngleSharp.Html.Forms.Submitters; using AngleSharp.Html.Forms.Submitters.Json; using AngleSharp.Html.InputTypes; using AngleSharp.Html.LinkRels; using AngleSharp.Html.Parser; using AngleSharp.Html.Parser.Tokens; using AngleSharp.Io; using AngleSharp.Io.Dom; using AngleSharp.Io.Processors; using AngleSharp.Mathml; using AngleSharp.Mathml.Dom; using AngleSharp.Media; using AngleSharp.Media.Dom; using AngleSharp.Scripting; using AngleSharp.Svg; using AngleSharp.Svg.Dom; using AngleSharp.Text; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCopyright("Copyright © AngleSharp, 2013-2023")] [assembly: ComVisible(false)] [assembly: InternalsVisibleTo("AngleSharp.Core.Tests, PublicKey=002400000480000094000000060200000024000052534131000400000100010001adf274fa2b375134e8e4558d606f1a0f96f5cd0c6b99970f7cce9887477209d7c29f814e2508d8bd2526e99e8cd273bd1158a3984f1ea74830ec5329a77c6ff201a15edeb8b36ab046abd1bce211fe8dbb076d7d806f46b15bfda44def04ead0669971e96c5f666c9eda677f28824fff7aa90d32929ed91d529a7a41699893")] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyCompany("AngleSharp")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("AngleSharp is the ultimate angle brackets parser library. It parses HTML5, CSS3, and XML to construct a DOM based on the official W3C specification.")] [assembly: AssemblyFileVersion("1.0.7.0")] [assembly: AssemblyInformationalVersion("1.0.7+44cebe134e597d91b3d53fdf3a8fb3897710c09c")] [assembly: AssemblyProduct("AngleSharp")] [assembly: AssemblyTitle("AngleSharp")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/AngleSharp/AngleSharp")] [assembly: AssemblyVersion("1.0.7.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace AngleSharp { public sealed class BrowsingContext : EventTarget, IBrowsingContext, IEventTarget, IDisposable { private readonly IEnumerable<object> _originalServices; private readonly List<object> _services; private readonly Sandboxes _security; private readonly IBrowsingContext? _parent; private readonly IDocument? _creator; private readonly IHistory? _history; private readonly Dictionary<string, WeakReference<IBrowsingContext>> _children; public IDocument? Active { get; set; } public IDocument? Creator => _creator; public IEnumerable<object> OriginalServices => _originalServices; public IWindow? Current => Active?.DefaultView; public IBrowsingContext? Parent => _parent; public IHistory? SessionHistory => _history; public Sandboxes Security => _security; public BrowsingContext(IConfiguration? configuration = null) : this((configuration ?? Configuration.Default).Services, Sandboxes.None) { } private BrowsingContext(Sandboxes security) { _services = new List<object>(); _originalServices = _services; _security = security; _children = new Dictionary<string, WeakReference<IBrowsingContext>>(); } internal BrowsingContext(IEnumerable<object> services, Sandboxes security) : this(security) { _services.AddRange(services); _originalServices = services; _history = GetService<IHistory>(); } internal BrowsingContext(IBrowsingContext parent, Sandboxes security) : this(parent.OriginalServices, security) { _parent = parent; _creator = _parent.Active; } public T? GetService<T>() where T : class { int count = _services.Count; int num = 0; while (num < count) { object obj = _services[num]; T val = obj as T; if (val == null) { if (!(obj is Func<IBrowsingContext, T> func)) { num++; continue; } val = func(this); _services[num] = val; } return val; } return null; } public IEnumerable<T> GetServices<T>() where T : class { int count = _services.Count; for (int i = 0; i < count; i++) { object obj = _services[i]; T val = obj as T; if (val == null) { if (!(obj is Func<IBrowsingContext, T> func)) { continue; } val = func(this); _services[i] = val; } yield return val; } } public IBrowsingContext CreateChild(string? name, Sandboxes security) { BrowsingContext browsingContext = new BrowsingContext(this, security); if (name != null && name.Length > 0) { _children[name] = new WeakReference<IBrowsingContext>(browsingContext); } return browsingContext; } public IBrowsingContext? FindChild(string name) { IBrowsingContext target = null; if (!string.IsNullOrEmpty(name) && _children.TryGetValue(name, out WeakReference<IBrowsingContext> value)) { value.TryGetTarget(out target); } return target; } public static IBrowsingContext New(IConfiguration? configuration = null) { if (configuration == null) { configuration = Configuration.Default; } return new BrowsingContext(configuration.Services, Sandboxes.None); } public static IBrowsingContext NewFrom<TService>(TService instance) { return new BrowsingContext(Configuration.Default.WithOnly(instance).Services, Sandboxes.None); } void IDisposable.Dispose() { Active?.Dispose(); Active = null; } } public static class BrowsingContextExtensions { public static Task<IDocument> OpenNewAsync(this IBrowsingContext context, string? url = null, CancellationToken cancellation = default(CancellationToken)) { string url2 = url; return context.OpenAsync(delegate(VirtualResponse m) { m.Address(url2 ?? "http://localhost/"); }, cancellation); } public static Task<IDocument> OpenAsync(this IBrowsingContext context, IResponse response, CancellationToken cancel = default(CancellationToken)) { response = response ?? throw new ArgumentNullException("response"); if (context == null) { context = BrowsingContext.New(); } Encoding defaultEncoding = context.GetDefaultEncoding(); IDocumentFactory factory = context.GetFactory<IDocumentFactory>(); CreateDocumentOptions options = new CreateDocumentOptions(response, defaultEncoding); return factory.CreateAsync(context, options, cancel); } public static Task<IDocument> OpenAsync(this IBrowsingContext context, DocumentRequest request, CancellationToken cancel = default(CancellationToken)) { request = request ?? throw new ArgumentNullException("request"); if (context == null) { context = BrowsingContext.New(); } return context.NavigateToAsync(request, cancel); } public static Task<IDocument> OpenAsync(this IBrowsingContext context, Url url, CancellationToken cancel = default(CancellationToken)) { url = url ?? throw new ArgumentNullException("url"); return context.OpenAsync(DocumentRequest.Get(url, null, context?.Active?.DocumentUri), cancel); } public static async Task<IDocument> OpenAsync(this IBrowsingContext context, Action<VirtualResponse> request, CancellationToken cancel = default(CancellationToken)) { request = request ?? throw new ArgumentNullException("request"); using IResponse response = VirtualResponse.Create(request); return await context.OpenAsync(response, cancel).ConfigureAwait(continueOnCapturedContext: false); } public static Task<IDocument> OpenAsync(this IBrowsingContext context, string address, CancellationToken cancellation = default(CancellationToken)) { address = address ?? throw new ArgumentNullException("address"); return context.OpenAsync(Url.Create(address), cancellation); } internal static Task<IDocument> NavigateToAsync(this IBrowsingContext context, DocumentRequest request, CancellationToken cancel = default(CancellationToken)) { return context.GetNavigationHandler(request.Target)?.NavigateAsync(request, cancel) ?? Task.FromResult<IDocument>(null); } public static void NavigateTo(this IBrowsingContext context, IDocument document) { context.SessionHistory?.PushState(document, document.Title, document.Url); context.Active = document; } public static INavigationHandler? GetNavigationHandler(this IBrowsingContext context, Url url) { Url url2 = url; return context.GetServices<INavigationHandler>().FirstOrDefault((INavigationHandler m) => m.SupportsProtocol(url2.Scheme)); } public static Encoding GetDefaultEncoding(this IBrowsingContext context) { IEncodingProvider? provider = context.GetProvider<IEncodingProvider>(); string language = context.GetLanguage(); return provider?.Suggest(language) ?? Encoding.UTF8; } public static CultureInfo GetCulture(this IBrowsingContext context) { return context.GetService<CultureInfo>() ?? CultureInfo.CurrentUICulture; } public static CultureInfo GetCultureFrom(this IBrowsingContext context, string language) { try { return new CultureInfo(language); } catch (CultureNotFoundException ex) { context.TrackError(ex); return context.GetCulture(); } } public static string GetLanguage(this IBrowsingContext context) { return context.GetCulture().Name; } public static TFactory GetFactory<TFactory>(this IBrowsingContext context) where TFactory : class { return context.GetServices<TFactory>().Single(); } public static TProvider? GetProvider<TProvider>(this IBrowsingContext context) where TProvider : class { return context.GetServices<TProvider>().SingleOrDefault(); } public static IResourceService<TResource>? GetResourceService<TResource>(this IBrowsingContext context, string type) where TResource : IResourceInfo { foreach (IResourceService<TResource> service in context.GetServices<IResourceService<TResource>>()) { if (service.SupportsType(type)) { return service; } } return null; } public static string GetCookie(this IBrowsingContext context, Url url) { return context.GetProvider<ICookieProvider>()?.GetCookie(url) ?? string.Empty; } public static void SetCookie(this IBrowsingContext context, Url url, string value) { context.GetProvider<ICookieProvider>()?.SetCookie(url, value); } public static ISpellCheckService? GetSpellCheck(this IBrowsingContext context, string language) { ISpellCheckService spellCheckService = null; IEnumerable<ISpellCheckService> services = context.GetServices<ISpellCheckService>(); CultureInfo cultureFrom = context.GetCultureFrom(language); string twoLetterISOLanguageName = cultureFrom.TwoLetterISOLanguageName; foreach (ISpellCheckService item in services) { CultureInfo culture = item.Culture; if (culture != null) { string twoLetterISOLanguageName2 = culture.TwoLetterISOLanguageName; if (culture.Equals(cultureFrom)) { return item; } if (spellCheckService == null && twoLetterISOLanguageName2.Is(twoLetterISOLanguageName)) { spellCheckService = item; } } } return spellCheckService; } public static IStylingService? GetCssStyling(this IBrowsingContext context) { return context.GetStyling(MimeTypeNames.Css); } public static IStylingService? GetStyling(this IBrowsingContext context, string type) { foreach (IStylingService service in context.GetServices<IStylingService>()) { if (service.SupportsType(type)) { return service; } } return null; } public static bool IsScripting(this IBrowsingContext context) { return context.GetServices<IScriptingService>().Any(); } public static IScriptingService? GetJsScripting(this IBrowsingContext context) { return context.GetScripting(MimeTypeNames.DefaultJavaScript); } public static IScriptingService? GetScripting(this IBrowsingContext context, string type) { foreach (IScriptingService service in context.GetServices<IScriptingService>()) { if (service.SupportsType(type)) { return service; } } return null; } public static ICommand? GetCommand(this IBrowsingContext context, string commandId) { return context.GetProvider<ICommandProvider>()?.GetCommand(commandId); } public static void TrackError(this IBrowsingContext context, Exception ex) { AngleSharp.Browser.Dom.Events.TrackEvent eventData = new AngleSharp.Browser.Dom.Events.TrackEvent("error", ex); context.Fire(eventData); } public static Task InteractAsync<T>(this IBrowsingContext context, string eventName, T data) { InteractivityEvent<T> interactivityEvent = new InteractivityEvent<T>(eventName, data); context.Fire(interactivityEvent); return interactivityEvent.Result ?? Task.FromResult(result: false); } public static IBrowsingContext ResolveTargetContext(this IBrowsingContext context, string? target) { bool flag = false; IBrowsingContext browsingContext = context; if (target != null && target.Length > 0) { browsingContext = context.FindChildFor(target); flag = browsingContext == null; } if (flag) { browsingContext = context.CreateChildFor(target); } return browsingContext; } public static IBrowsingContext CreateChildFor(this IBrowsingContext context, string? target) { Sandboxes security = Sandboxes.None; if (target == "_blank") { target = null; } return context.CreateChild(target, security); } public static IBrowsingContext? FindChildFor(this IBrowsingContext context, string target) { if (!string.IsNullOrEmpty(target)) { switch (target) { case "_self": break; case "_parent": return context.Parent ?? context; case "_top": return context; default: return context.FindChild(target); } } return context; } public static IEnumerable<Task> GetDownloads<T>(this IBrowsingContext context) where T : INode { IResourceLoader service = context.GetService<IResourceLoader>(); if (service == null) { return Array.Empty<Task>(); } return from m in service.GetDownloads() where m.Source is T select m.Task; } } public class Configuration : IConfiguration { private readonly IEnumerable<object> _services; public static IConfiguration Default => new Configuration(); public IEnumerable<object> Services => _services; private static T Instance<T>(T instance) { return instance; } private static Func<IBrowsingContext, T> Creator<T>(Func<IBrowsingContext, T> creator) { return creator; } public Configuration(IEnumerable<object>? services = null) { _services = services ?? new object[16] { Instance((IElementFactory<Document, HtmlElement>)new HtmlElementFactory()), Instance((IElementFactory<Document, MathElement>)new MathElementFactory()), Instance((IElementFactory<Document, SvgElement>)new SvgElementFactory()), Instance((IEventFactory)new DefaultEventFactory()), Instance((IInputTypeFactory)new DefaultInputTypeFactory()), Instance((IAttributeSelectorFactory)new DefaultAttributeSelectorFactory()), Instance((IPseudoElementSelectorFactory)new DefaultPseudoElementSelectorFactory()), Instance((IPseudoClassSelectorFactory)new DefaultPseudoClassSelectorFactory()), Instance((ILinkRelationFactory)new DefaultLinkRelationFactory()), Instance((IDocumentFactory)new DefaultDocumentFactory()), Instance((IAttributeObserver)new DefaultAttributeObserver()), Instance((IMetaHandler)new EncodingMetaHandler()), Instance((IHtmlEncoder)new DefaultHtmlEncoder()), Creator((Func<IBrowsingContext, ICssSelectorParser>)((IBrowsingContext ctx) => new CssSelectorParser(ctx))), Creator((Func<IBrowsingContext, IHtmlParser>)((IBrowsingContext ctx) => new HtmlParser(ctx))), Creator((Func<IBrowsingContext, INavigationHandler>)((IBrowsingContext ctx) => new DefaultNavigationHandler(ctx))) }; } } public static class ConfigurationExtensions { public static IConfiguration With(this IConfiguration configuration, object service) { configuration = configuration ?? throw new ArgumentNullException("configuration"); service = service ?? throw new ArgumentNullException("service"); return new Configuration(configuration.Services.Concat(service)); } public static IConfiguration WithOnly<TService>(this IConfiguration configuration, TService service) { if (service == null) { throw new ArgumentNullException("service"); } return configuration.Without<TService>().With(service); } public static IConfiguration WithOnly<TService>(this IConfiguration configuration, Func<IBrowsingContext, TService> creator) { creator = creator ?? throw new ArgumentNullException("creator"); return configuration.Without<TService>().With(creator); } public static IConfiguration Without(this IConfiguration configuration, object service) { configuration = configuration ?? throw new ArgumentNullException("configuration"); service = service ?? throw new ArgumentNullException("service"); return new Configuration(configuration.Services.Except(service)); } public static IConfiguration With(this IConfiguration configuration, IEnumerable<object> services) { configuration = configuration ?? throw new ArgumentNullException("configuration"); services = services ?? throw new ArgumentNullException("services"); return new Configuration(services.Concat(configuration.Services)); } public static IConfiguration Without(this IConfiguration configuration, IEnumerable<object> services) { configuration = configuration ?? throw new ArgumentNullException("configuration"); services = services ?? throw new ArgumentNullException("services"); return new Configuration(configuration.Services.Except(services)); } public static IConfiguration With<TService>(this IConfiguration configuration, Func<IBrowsingContext, TService> creator) { creator = creator ?? throw new ArgumentNullException("creator"); return configuration.With((object)creator); } public static IConfiguration Without<TService>(this IConfiguration configuration) { configuration = configuration ?? throw new ArgumentNullException("configuration"); IEnumerable<object> services = configuration.Services.OfType<TService>().Cast<object>(); IEnumerable<Func<IBrowsingContext, TService>> services2 = configuration.Services.OfType<Func<IBrowsingContext, TService>>(); return configuration.Without(services).Without(services2); } public static bool Has<TService>(this IConfiguration configuration) { configuration = configuration ?? throw new ArgumentNullException("configuration"); if (!configuration.Services.OfType<TService>().Any()) { return configuration.Services.OfType<Func<IBrowsingContext, TService>>().Any(); } return true; } public static IConfiguration WithDefaultLoader(this IConfiguration configuration, LoaderOptions? setup = null) { LoaderOptions config = setup ?? new LoaderOptions(); if (!configuration.Has<IRequester>()) { configuration = configuration.With(new DefaultHttpRequester()); } if (!config.IsNavigationDisabled) { configuration = configuration.With((Func<IBrowsingContext, IDocumentLoader>)((IBrowsingContext ctx) => new DefaultDocumentLoader(ctx, config.Filter))); } if (config.IsResourceLoadingEnabled) { configuration = configuration.With((Func<IBrowsingContext, IResourceLoader>)((IBrowsingContext ctx) => new DefaultResourceLoader(ctx, config.Filter))); } return configuration; } public static IConfiguration WithCulture(this IConfiguration configuration, string name) { CultureInfo culture = new CultureInfo(name); return configuration.WithCulture(culture); } public static IConfiguration WithCulture(this IConfiguration configuration, CultureInfo culture) { return configuration.With(culture); } public static IConfiguration WithMetaRefresh(this IConfiguration configuration, Predicate<Url>? shouldRefresh = null) { RefreshMetaHandler service = new RefreshMetaHandler(shouldRefresh); return configuration.With(service); } public static IConfiguration WithLocaleBasedEncoding(this IConfiguration configuration) { LocaleEncodingProvider service = new LocaleEncodingProvider(); return configuration.With(service); } public static IConfiguration WithDefaultCookies(this IConfiguration configuration) { MemoryCookieProvider service = new MemoryCookieProvider(); return configuration.With(service); } } public static class FormatExtensions { public static string ToCss(this IStyleFormattable style) { return style.ToCss(CssStyleFormatter.Instance); } public static string ToCss(this IStyleFormattable style, IStyleFormatter formatter) { StringBuilder sb = StringBuilderPool.Obtain(); using (StringWriter writer = new StringWriter(sb)) { style.ToCss(writer, formatter); } return sb.ToPool(); } public static void ToCss(this IStyleFormattable style, TextWriter writer) { style.ToCss(writer, CssStyleFormatter.Instance); } public static Task ToCssAsync(this IStyleFormattable style, TextWriter writer) { return writer.WriteAsync(style.ToCss()); } public static async Task ToCssAsync(this IStyleFormattable style, Stream stream) { using StreamWriter writer = new StreamWriter(stream); await style.ToCssAsync(writer).ConfigureAwait(continueOnCapturedContext: false); } public static string ToHtml(this IMarkupFormattable markup) { return markup.ToHtml(HtmlMarkupFormatter.Instance); } public static string ToHtml(this IMarkupFormattable markup, IMarkupFormatter formatter) { StringBuilder sb = StringBuilderPool.Obtain(); using (StringWriter writer = new StringWriter(sb)) { markup.ToHtml(writer, formatter); } return sb.ToPool(); } public static void ToHtml(this IMarkupFormattable markup, TextWriter writer) { markup.ToHtml(writer, HtmlMarkupFormatter.Instance); } public static string Minify(this IMarkupFormattable markup) { return markup.ToHtml(new MinifyMarkupFormatter()); } public static string Prettify(this IMarkupFormattable markup) { return markup.ToHtml(new PrettyMarkupFormatter()); } public static Task ToHtmlAsync(this IMarkupFormattable markup, TextWriter writer) { return writer.WriteAsync(markup.ToHtml()); } public static async Task ToHtmlAsync(this IMarkupFormattable markup, Stream stream) { using StreamWriter writer = new StreamWriter(stream); await markup.ToHtmlAsync(writer).ConfigureAwait(continueOnCapturedContext: false); } } public interface IBrowsingContext : IEventTarget, IDisposable { IWindow? Current { get; } IDocument? Active { get; set; } IHistory? SessionHistory { get; } Sandboxes Security { get; } IBrowsingContext? Parent { get; } IDocument? Creator { get; } IEnumerable<object> OriginalServices { get; } T? GetService<T>() where T : class; IEnumerable<T> GetServices<T>() where T : class; IBrowsingContext CreateChild(string? name, Sandboxes security); IBrowsingContext? FindChild(string name); } public interface IConfiguration { IEnumerable<object> Services { get; } } public interface IMarkupFormattable { void ToHtml(TextWriter writer, IMarkupFormatter formatter); } public interface IMarkupFormatter { string Text(ICharacterData text); string LiteralText(ICharacterData text); string Comment(IComment comment); string Processing(IProcessingInstruction processing); string Doctype(IDocumentType doctype); string OpenTag(IElement element, bool selfClosing); string CloseTag(IElement element, bool selfClosing); } public interface IStyleFormattable { void ToCss(TextWriter writer, IStyleFormatter formatter); } public interface IStyleFormatter { string Sheet(IEnumerable<IStyleFormattable> rules); string Declaration(string name, string value, bool important); string BlockDeclarations(IEnumerable<IStyleFormattable> declarations); string Rule(string name, string value); string Rule(string name, string prelude, string rules); string BlockRules(IEnumerable<IStyleFormattable> rules); string Comment(string data); } } namespace AngleSharp.Xhtml { public class XhtmlMarkupFormatter : IMarkupFormatter { public static readonly IMarkupFormatter Instance = new XhtmlMarkupFormatter(); private readonly bool _emptyTagsToSelfClosing; public bool IsSelfClosingEmptyTags => _emptyTagsToSelfClosing; public XhtmlMarkupFormatter() : this(emptyTagsToSelfClosing: true) { } public XhtmlMarkupFormatter(bool emptyTagsToSelfClosing) { _emptyTagsToSelfClosing = emptyTagsToSelfClosing; } public virtual string CloseTag(IElement element, bool selfClosing) { string prefix = element.Prefix; string localName = element.LocalName; string text = ((!string.IsNullOrEmpty(prefix)) ? (prefix + ":" + localName) : localName); if (!selfClosing && (!_emptyTagsToSelfClosing || element.HasChildNodes)) { return "</" + text + ">"; } return string.Empty; } public virtual string Comment(IComment comment) { return "<!--" + comment.Data + "-->"; } public virtual string Doctype(IDocumentType doctype) { string publicIdentifier = doctype.PublicIdentifier; string systemIdentifier = doctype.SystemIdentifier; string text = ((string.IsNullOrEmpty(publicIdentifier) && string.IsNullOrEmpty(systemIdentifier)) ? string.Empty : (" " + (string.IsNullOrEmpty(publicIdentifier) ? ("SYSTEM \"" + systemIdentifier + "\"") : ("PUBLIC \"" + publicIdentifier + "\" \"" + systemIdentifier + "\"")))); return "<!DOCTYPE " + doctype.Name + text + ">"; } public virtual string OpenTag(IElement element, bool selfClosing) { string prefix = element.Prefix; StringBuilder stringBuilder = StringBuilderPool.Obtain(); stringBuilder.Append('<'); if (!string.IsNullOrEmpty(prefix)) { stringBuilder.Append(prefix).Append(':'); } stringBuilder.Append(element.LocalName); foreach (IAttr attribute in element.Attributes) { stringBuilder.Append(' ').Append(Attribute(attribute)); } if (selfClosing || (_emptyTagsToSelfClosing && !element.HasChildNodes)) { stringBuilder.Append(" /"); } stringBuilder.Append('>'); return stringBuilder.ToPool(); } public virtual string Processing(IProcessingInstruction processing) { string text = processing.Target + " " + processing.Data; return "<?" + text + "?>"; } public virtual string LiteralText(ICharacterData text) { return text.Data; } public virtual string Text(ICharacterData text) { return EscapeText(text.Data); } protected virtual string Attribute(IAttr attribute) { string namespaceUri = attribute.NamespaceUri; string localName = attribute.LocalName; string value = attribute.Value; StringBuilder stringBuilder = StringBuilderPool.Obtain(); if (string.IsNullOrEmpty(namespaceUri)) { stringBuilder.Append(localName); } else if (namespaceUri.Is(NamespaceNames.XmlUri)) { stringBuilder.Append(NamespaceNames.XmlPrefix).Append(':').Append(localName); } else if (namespaceUri.Is(NamespaceNames.XLinkUri)) { stringBuilder.Append(NamespaceNames.XLinkPrefix).Append(':').Append(localName); } else if (namespaceUri.Is(NamespaceNames.XmlNsUri)) { stringBuilder.Append(XmlNamespaceLocalName(localName)); } else { stringBuilder.Append(attribute.Name); } stringBuilder.Append('=').Append('"'); for (int i = 0; i < value.Length; i++) { switch (value[i]) { case '&': stringBuilder.Append("&"); break; case '\u00a0': stringBuilder.Append(" "); break; case '<': stringBuilder.Append("<"); break; case '"': stringBuilder.Append("""); break; default: stringBuilder.Append(value[i]); break; } } return stringBuilder.Append('"').ToPool(); } public static string EscapeText(string content) { StringBuilder stringBuilder = StringBuilderPool.Obtain(); for (int i = 0; i < content.Length; i++) { switch (content[i]) { case '&': stringBuilder.Append("&"); break; case '\u00a0': stringBuilder.Append(" "); break; case '>': stringBuilder.Append(">"); break; case '<': stringBuilder.Append("<"); break; default: stringBuilder.Append(content[i]); break; } } return stringBuilder.ToPool(); } public static string XmlNamespaceLocalName(string localName) { if (localName.Is(NamespaceNames.XmlNsPrefix)) { return localName; } return NamespaceNames.XmlNsPrefix + ':' + localName; } } } namespace AngleSharp.Text { public static class CharExtensions { public static int FromHex(this char c) { if (!c.IsDigit()) { return c - (c.IsLowercaseAscii() ? 87 : 55); } return c - 48; } public static string ToHex(this byte num) { char[] array = new char[2]; int num2 = num >> 4; array[0] = (char)(num2 + ((num2 < 10) ? 48 : 55)); num2 = num - 16 * num2; array[1] = (char)(num2 + ((num2 < 10) ? 48 : 55)); return new string(array); } public static string ToHex(this char character) { int num = character; return num.ToString("x"); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsInRange(this char c, int lower, int upper) { if (c >= lower) { return c <= upper; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsNormalQueryCharacter(this char c) { if (c.IsInRange(33, 126) && c != '"' && c != '`' && c != '#' && c != '<') { return c != '>'; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsNormalPathCharacter(this char c) { if (c.IsInRange(32, 126) && c != '"' && c != '`' && c != '#' && c != '<' && c != '>' && c != ' ') { return c != '?'; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsUppercaseAscii(this char c) { if (c >= 'A') { return c <= 'Z'; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsLowercaseAscii(this char c) { if (c >= 'a') { return c <= 'z'; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsAlphanumericAscii(this char c) { if (!c.IsDigit() && !c.IsUppercaseAscii()) { return c.IsLowercaseAscii(); } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHex(this char c) { if (!c.IsDigit() && (c < 'A' || c > 'F')) { if (c >= 'a') { return c <= 'f'; } return false; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsNonAscii(this char c) { if (c != '\uffff') { return c >= '\u0080'; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsNonPrintable(this char c) { if ((c < '\0' || c > '\b') && (c < '\u000e' || c > '\u001f')) { if (c >= '\u007f') { return c <= '\u009f'; } return false; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsLetter(this char c) { if (!c.IsUppercaseAscii()) { return c.IsLowercaseAscii(); } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsName(this char c) { if (!c.IsNonAscii() && !c.IsLetter() && c != '_' && c != '-') { return c.IsDigit(); } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsCustomElementName(this char c) { if (c != '_' && c != '-' && c != '.' && !c.IsDigit() && !c.IsLowercaseAscii() && c != '·' && !c.IsInRange(192, 214) && !c.IsInRange(216, 246) && !c.IsInRange(248, 893) && !c.IsInRange(895, 8191) && !c.IsInRange(8204, 8205) && !c.IsInRange(8255, 8256) && !c.IsInRange(8304, 8591) && !c.IsInRange(11264, 12271) && !c.IsInRange(12289, 55295) && !c.IsInRange(63744, 64975) && !c.IsInRange(65008, 65533)) { return c.IsInRange(65536, 2031615); } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsNameStart(this char c) { if (!c.IsNonAscii() && !c.IsUppercaseAscii() && !c.IsLowercaseAscii()) { return c == '_'; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsLineBreak(this char c) { if (c != '\n') { return c == '\r'; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsSpaceCharacter(this char c) { if (c != ' ' && c != '\t' && c != '\n' && c != '\r') { return c == '\f'; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsWhiteSpaceCharacter(this char c) { if (!c.IsInRange(9, 13) && c != ' ' && c != '\u0085' && c != '\u00a0' && c != '\u1680' && c != '\u180e' && !c.IsInRange(8192, 8202) && c != '\u2028' && c != '\u2029' && c != '\u202f' && c != '\u205f') { return c == '\u3000'; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsDigit(this char c) { if (c >= '0') { return c <= '9'; } return false; } public static bool IsUrlCodePoint(this char c) { if (!c.IsAlphanumericAscii() && c != '!' && c != '$' && c != '&' && c != '\'' && c != '(' && c != ')' && c != '*' && c != '+' && c != '-' && c != ',' && c != '.' && c != '/' && c != ':' && c != ';' && c != '=' && c != '?' && c != '@' && c != '_' && c != '~' && !c.IsInRange(160, 55295) && !c.IsInRange(57344, 64975) && !c.IsInRange(65008, 65533) && !c.IsInRange(65536, 131069) && !c.IsInRange(131072, 196605) && !c.IsInRange(196608, 262141) && !c.IsInRange(262144, 327677) && !c.IsInRange(327680, 393213) && !c.IsInRange(393216, 458749) && !c.IsInRange(458752, 524285) && !c.IsInRange(524288, 589821) && !c.IsInRange(589824, 655357) && !c.IsInRange(655360, 720893) && !c.IsInRange(720896, 786429) && !c.IsInRange(786432, 851965) && !c.IsInRange(851968, 917501) && !c.IsInRange(917504, 983037) && !c.IsInRange(983040, 1048573)) { return c.IsInRange(1048576, 1114109); } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsInvalid(this int c) { if (c != 0 && c <= 1114111) { if (c > 55296) { return c < 57343; } return false; } return true; } } public static class Punycode { private const int PunycodeBase = 36; private const int Tmin = 1; private const int Tmax = 26; private static readonly string acePrefix = "xn--"; private static readonly char[] possibleDots = new char[4] { '.', '。', '.', '。' }; public static IDictionary<char, char> Symbols = new Dictionary<char, char> { { '。', '.' }, { '.', '.' }, { 'G', 'g' }, { 'o', 'o' }, { 'c', 'c' }, { 'X', 'x' }, { '0', '0' }, { '1', '1' }, { '2', '2' }, { '5', '5' }, { '⁰', '0' }, { '¹', '1' }, { '²', '2' }, { '³', '3' }, { '⁴', '4' }, { '⁵', '5' }, { '⁶', '6' }, { '⁷', '7' }, { '⁸', '8' }, { '⁹', '9' }, { '₀', '0' }, { '₁', '1' }, { '₂', '2' }, { '₃', '3' }, { '₄', '4' }, { '₅', '5' }, { '₆', '6' }, { '₇', '7' }, { '₈', '8' }, { '₉', '9' }, { 'ᵃ', 'a' }, { 'ᵇ', 'b' }, { 'ᶜ', 'c' }, { 'ᵈ', 'd' }, { 'ᵉ', 'e' }, { 'ᶠ', 'f' }, { 'ᵍ', 'g' }, { 'ʰ', 'h' }, { 'ⁱ', 'i' }, { 'ʲ', 'j' }, { 'ᵏ', 'k' }, { 'ˡ', 'l' }, { 'ᵐ', 'm' }, { 'ⁿ', 'n' }, { 'ᵒ', 'o' }, { 'ᵖ', 'p' }, { 'ʳ', 'r' }, { 'ˢ', 's' }, { 'ᵗ', 't' }, { 'ᵘ', 'u' }, { 'ᵛ', 'v' }, { 'ʷ', 'w' }, { 'ˣ', 'x' }, { 'ʸ', 'y' }, { 'ᶻ', 'z' }, { 'ᴬ', 'A' }, { 'ᴮ', 'B' }, { 'ᴰ', 'D' }, { 'ᴱ', 'E' }, { 'ᴳ', 'G' }, { 'ᴴ', 'H' }, { 'ᴵ', 'I' }, { 'ᴶ', 'J' }, { 'ᴷ', 'K' }, { 'ᴸ', 'L' }, { 'ᴹ', 'M' }, { 'ᴺ', 'N' }, { 'ᴼ', 'O' }, { 'ᴾ', 'P' }, { 'ᴿ', 'R' }, { 'ᵀ', 'T' }, { 'ᵁ', 'U' }, { 'ⱽ', 'V' }, { 'ᵂ', 'W' } }; public static string Encode(string text) { if (text.Length == 0) { return text; } StringBuilder stringBuilder = new StringBuilder(text.Length); int num = 0; int num2 = 0; int num3 = 0; while (num < text.Length) { num = text.IndexOfAny(possibleDots, num2); if (num < 0) { num = text.Length; } if (num == num2) { break; } stringBuilder.Append(acePrefix); int num4 = 0; int num5 = 0; for (num4 = num2; num4 < num; num4++) { if (text[num4] < '\u0080') { stringBuilder.Append(EncodeBasic(text[num4])); num5++; } else if (char.IsSurrogatePair(text, num4)) { num4++; } } int num6 = num5; if (num6 == num - num2) { stringBuilder.Remove(num3, acePrefix.Length); } else { if (text.Length - num2 >= acePrefix.Length && text.Substring(num2, acePrefix.Length).Isi(acePrefix)) { break; } int num7 = 0; if (num6 > 0) { stringBuilder.Append('-'); } int num8 = 128; int num9 = 0; int num10 = 72; while (num5 < num - num2) { int num11 = 0; int num12 = 0; int num13 = 0; num12 = 134217727; for (num11 = num2; num11 < num; num11 += ((!IsSupplementary(num13)) ? 1 : 2)) { num13 = char.ConvertToUtf32(text, num11); if (num13 >= num8 && num13 < num12) { num12 = num13; } } num9 += (num12 - num8) * (num5 - num7 + 1); num8 = num12; for (num11 = num2; num11 < num; num11 += ((!IsSupplementary(num13)) ? 1 : 2)) { num13 = char.ConvertToUtf32(text, num11); if (num13 < num8) { num9++; } else { if (num13 != num8) { continue; } int num14 = num9; int num15 = 36; while (true) { int num16 = ((num15 <= num10) ? 1 : ((num15 >= num10 + 26) ? 26 : (num15 - num10))); if (num14 < num16) { break; } stringBuilder.Append(EncodeDigit(num16 + (num14 - num16) % (36 - num16))); num14 = (num14 - num16) / (36 - num16); num15 += 36; } stringBuilder.Append(EncodeDigit(num14)); num10 = AdaptChar(num9, num5 - num7 + 1, num5 == num6); num9 = 0; num5++; if (IsSupplementary(num12)) { num5++; num7++; } } } num9++; num8++; } } if (stringBuilder.Length - num3 > 63) { throw new ArgumentException(); } if (num != text.Length) { stringBuilder.Append(possibleDots[0]); } num2 = num + 1; num3 = stringBuilder.Length; } int num17 = ((!IsDot(text[text.Length - 1])) ? 1 : 0); int num18 = 255 - num17; if (stringBuilder.Length > num18) { stringBuilder.Remove(num18, stringBuilder.Length - num18); } return stringBuilder.ToString(); } private static bool IsSupplementary(int test) { return test >= 65536; } private static bool IsDot(char c) { for (int i = 0; i < possibleDots.Length; i++) { if (possibleDots[i] == c) { return true; } } return false; } private static char EncodeDigit(int digit) { if (digit > 25) { return (char)(digit + 22); } return (char)(digit + 97); } private static char EncodeBasic(char character) { if (char.IsUpper(character)) { character = (char)(character + 32); } return character; } private static int AdaptChar(int delta, int numPoints, bool firstTime) { uint num = 0u; delta = (firstTime ? (delta / 700) : (delta / 2)); delta += delta / numPoints; num = 0u; while (delta > 455) { delta /= 35; num += 36; } return (int)(num + 36 * delta / (delta + 38)); } } public static class StringBuilderPool { private static readonly Stack<StringBuilder> _builder = new Stack<StringBuilder>(); private static readonly object _lock = new object(); private static int _count = 4; private static int _limit = 85000; public static int MaxCount { get { return _count; } set { _count = Math.Max(1, value); } } public static int SizeLimit { get { return _limit; } set { _limit = Math.Max(1024, value); } } public static StringBuilder Obtain() { lock (_lock) { if (_builder.Count == 0) { return new StringBuilder(1024); } return _builder.Pop().Clear(); } } public static string ToPool(this StringBuilder sb) { string result = sb.ToString(); sb.ReturnToPool(); return result; } internal static void ReturnToPool(this StringBuilder sb) { lock (_lock) { int count = _builder.Count; if (sb.Capacity <= _limit) { if (count == _count) { DropMinimum(sb); } else if (count < Math.Min(2, _count) || _builder.Peek().Capacity < sb.Capacity) { _builder.Push(sb); } } } } private static void DropMinimum(StringBuilder sb) { int capacity = sb.Capacity; StringBuilder[] instances = _builder.ToArray(); int num = FindIndex(instances, capacity); if (num > -1) { RebuildPool(sb, instances, num); } } private static void RebuildPool(StringBuilder sb, StringBuilder[] instances, int index) { _builder.Clear(); int num = instances.Length - 1; while (num > index) { _builder.Push(instances[num--]); } while (num > 0) { _builder.Push(instances[--num]); } _builder.Push(sb); } private static int FindIndex(StringBuilder[] instances, int minimum) { int result = -1; for (int i = 0; i < instances.Length; i++) { int capacity = instances[i].Capacity; if (capacity < minimum) { minimum = capacity; result = i; } } return result; } } public static class StringExtensions { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Has([NotNullWhen(true)] this string? value, char chr, int index = 0) { if (value != null && value.Length > index) { return value[index] == chr; } return false; } internal static string GetCompatiblity(this QuirksMode mode) { string result = "CSS1Compat"; string text = mode.ToString(); if (text != null) { FieldInfo field = typeof(QuirksMode).GetField(text); if (field != null) { DomDescriptionAttribute customAttribute = field.GetCustomAttribute<DomDescriptionAttribute>(); if (customAttribute != null) { result = customAttribute.Description; } } } return result; } public static string HtmlLower(this string value) { int length = value.Length; for (int i = 0; i < length; i++) { char c = value[i]; if (!c.IsUppercaseAscii()) { continue; } char[] array = new char[length]; for (int j = 0; j < i; j++) { array[j] = value[j]; } array[i] = char.ToLowerInvariant(c); for (int k = i + 1; k < length; k++) { c = value[k]; if (c.IsUppercaseAscii()) { c = char.ToLowerInvariant(c); } array[k] = c; } return new string(array); } return value; } public static Sandboxes ParseSecuritySettings(this string value, bool allowFullscreen = false) { string[] list = value.SplitSpaces(); Sandboxes sandboxes = Sandboxes.Navigation | Sandboxes.Plugins | Sandboxes.DocumentDomain; if (!list.Contains("allow-popups", StringComparison.OrdinalIgnoreCase)) { sandboxes |= Sandboxes.AuxiliaryNavigation; } if (!list.Contains("allow-top-navigation", StringComparison.OrdinalIgnoreCase)) { sandboxes |= Sandboxes.TopLevelNavigation; } if (!list.Contains("allow-same-origin", StringComparison.OrdinalIgnoreCase)) { sandboxes |= Sandboxes.Origin; } if (!list.Contains("allow-forms", StringComparison.OrdinalIgnoreCase)) { sandboxes |= Sandboxes.Forms; } if (!list.Contains("allow-pointer-lock", StringComparison.OrdinalIgnoreCase)) { sandboxes |= Sandboxes.PointerLock; } if (!list.Contains("allow-scripts", StringComparison.OrdinalIgnoreCase)) { sandboxes |= Sandboxes.Scripts; sandboxes |= Sandboxes.AutomaticFeatures; } if (!list.Contains("allow-presentation", StringComparison.OrdinalIgnoreCase)) { sandboxes |= Sandboxes.Presentation; } if (!allowFullscreen) { sandboxes |= Sandboxes.Fullscreen; } return sandboxes; } public static T ToEnum<T>(this string? value, T defaultValue) where T : struct, Enum { if (!string.IsNullOrEmpty(value) && Enum.TryParse<T>(value, ignoreCase: true, out var result)) { return result; } return defaultValue; } public static double ToDouble(this string? value, double defaultValue = 0.0) { if (!string.IsNullOrEmpty(value) && double.TryParse(value, NumberStyles.Any, NumberFormatInfo.InvariantInfo, out var result)) { return result; } return defaultValue; } public static int ToInteger(this string? value, int defaultValue = 0) { if (!string.IsNullOrEmpty(value) && int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var result)) { return result; } return defaultValue; } public static uint ToInteger(this string? value, uint defaultValue = 0u) { if (!string.IsNullOrEmpty(value) && uint.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var result)) { return result; } return defaultValue; } public static bool ToBoolean(this string? value, bool defaultValue = false) { if (!string.IsNullOrEmpty(value) && bool.TryParse(value, out var result)) { return result; } return defaultValue; } public static string ReplaceFirst(this string text, string search, string replace) { int num = text.IndexOf(search); if (num < 0) { return text; } return text.Substring(0, num) + replace + text.Substring(num + search.Length); } public static string CollapseAndStrip(this string str) { if (str.Length == 0) { return str; } char[] array = ArrayPool<char>.Shared.Rent(str.Length); bool flag = true; int num = 0; int length = str.Length; for (int i = 0; i < length; i++) { if (str[i].IsSpaceCharacter()) { if (!flag) { flag = true; array[num++] = ' '; } } else { flag = false; array[num++] = str[i]; } } if (flag && num > 0) { num--; } string result = new string(array, 0, num); ArrayPool<char>.Shared.Return(array); return result; } public static string Collapse(this string str) { StringBuilder stringBuilder = StringBuilderPool.Obtain(); bool flag = false; int length = str.Length; for (int i = 0; i < length; i++) { if (str[i].IsSpaceCharacter()) { if (!flag) { stringBuilder.Append(' '); flag = true; } } else { flag = false; stringBuilder.Append(str[i]); } } return stringBuilder.ToPool(); } public static bool Contains(this string[] list, string element, StringComparison comparison = StringComparison.Ordinal) { int num = list.Length; for (int i = 0; i < num; i++) { if (list[i].Equals(element, comparison)) { return true; } } return false; } public static bool IsCustomElement(this string tag) { if (tag.IndexOf('-') != -1 && !TagNames.DisallowedCustomElementNames.Contains(tag)) { int length = tag.Length; for (int i = 0; i < length; i++) { if (!tag[i].IsCustomElementName()) { return false; } } return true; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Is(this string? current, string? other) { return string.Equals(current, other, StringComparison.Ordinal); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Isi(this string? current, string? other) { return string.Equals(current, other, StringComparison.OrdinalIgnoreCase); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsOneOf(this string? element, string item1, string item2) { if (!element.Is(item1)) { return element.Is(item2); } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsOneOf(this string element, string item1, string item2, string item3) { if (!element.Is(item1) && !element.Is(item2)) { return element.Is(item3); } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsOneOf(this string element, string item1, string item2, string item3, string item4) { if (!element.Is(item1) && !element.Is(item2) && !element.Is(item3)) { return element.Is(item4); } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsOneOf(this string element, string item1, string item2, string item3, string item4, string item5) { if (!element.Is(item1) && !element.Is(item2) && !element.Is(item3) && !element.Is(item4)) { return element.Is(item5); } return true; } public static string StripLineBreaks(this string str) { char[] array = str.ToCharArray(); int num = 0; int num2 = array.Length; int num3 = 0; while (num3 < num2) { array[num3] = array[num3 + num]; if (array[num3].IsLineBreak()) { num++; num2--; } else { num3++; } } return new string(array, 0, num2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static string StripLeadingTrailingSpaces(this string str) { int i = 0; int num = str.Length - 1; for (; i < str.Length && str[i].IsSpaceCharacter(); i++) { } while (num > i && str[num].IsSpaceCharacter()) { num--; } return str.Substring(i, 1 + num - i); } public static string[] SplitWithoutTrimming(this string str, char c) { List<string> list = new List<string>(); int num = 0; int length = str.Length; for (int i = 0; i < length; i++) { if (str[i] == c) { if (i > num) { list.Add(str.Substring(num, i - num)); } num = i + 1; } } if (length > num) { list.Add(str.Substring(num, length - num)); } return list.ToArray(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static string[] SplitCommas(this string str) { return str.SplitWithTrimming(','); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool HasHyphen(this string str, string value, StringComparison comparison = StringComparison.Ordinal) { if (!string.Equals(str, value, comparison)) { if (str.Length > value.Length && str.StartsWith(value, comparison)) { return str[value.Length] == '-'; } return false; } return true; } public static string[] SplitSpaces(this string str) { List<string> list = new List<string>(); char[] array = ArrayPool<char>.Shared.Rent(str.Length); int num = 0; for (int i = 0; i <= str.Length; i++) { if (i == str.Length || str[i].IsSpaceCharacter()) { if (num > 0) { string text = new string(array, 0, num).StripLeadingTrailingSpaces(); if (text.Length != 0) { list.Add(text); } num = 0; } } else { array[num] = str[i]; num++; } } ArrayPool<char>.Shared.Return(array); return list.ToArray(); } public static string[] SplitWithTrimming(this string str, char ch) { List<string> list = new List<string>(); char[] array = ArrayPool<char>.Shared.Rent(str.Length); int num = 0; for (int i = 0; i <= str.Length; i++) { if (i == str.Length || str[i] == ch) { if (num > 0) { string text = new string(array, 0, num).StripLeadingTrailingSpaces(); if (text.Length != 0) { list.Add(text); } num = 0; } } else { array[num] = str[i]; num++; } } ArrayPool<char>.Shared.Return(array); return list.ToArray(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromHex(this string s) { return int.Parse(s, NumberStyles.HexNumber, CultureInfo.InvariantCulture); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromDec(this string s) { return int.Parse(s, NumberStyles.Integer, CultureInfo.InvariantCulture); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static string HtmlEncode(this string value, Encoding encoding) { return value; } public static string CssString(this string value) { StringBuilder stringBuilder = StringBuilderPool.Obtain(); stringBuilder.Append('"'); if (!string.IsNullOrEmpty(value)) { int length = value.Length; for (int i = 0; i < length; i++) { char c = value[i]; switch (c) { case '\0': stringBuilder.ReturnToPool(); throw new DomException(DomError.InvalidCharacter); case '"': case '\\': stringBuilder.Append('\\').Append(c); continue; } if (c.IsInRange(1, 31) || c == '{') { stringBuilder.Append('\\').Append(c.ToHex()).Append((i + 1 != length) ? " " : ""); } else { stringBuilder.Append(c); } } } stringBuilder.Append('"'); return stringBuilder.ToPool(); } public static string CssFunction(this string value, string argument) { return value + "(" + argument + ")"; } public static string UrlEncode(this byte[] content) { StringBuilder stringBuilder = StringBuilderPool.Obtain(); int num = content.Length; for (int i = 0; i < num; i++) { char c = (char)content[i]; switch (c) { case ' ': stringBuilder.Append('+'); break; default: if (!c.IsAlphanumericAscii()) { stringBuilder.Append('%').Append(content[i].ToString("X2")); break; } goto case '*'; case '*': case '-': case '.': case '_': case '~': stringBuilder.Append(c); break; } } return stringBuilder.ToPool(); } public static byte[] UrlDecode(this string value) { MemoryStream memoryStream = new MemoryStream(); int length = value.Length; for (int i = 0; i < length; i++) { char c = value[i]; switch (c) { case '+': { byte value4 = 32; memoryStream.WriteByte(value4); break; } case '%': { if (i + 2 >= length) { throw new FormatException(); } byte value3 = (byte)(16 * value[++i].FromHex() + value[++i].FromHex()); memoryStream.WriteByte(value3); break; } default: { byte value2 = (byte)c; memoryStream.WriteByte(value2); break; } } } return memoryStream.ToArray(); } public static string NormalizeLineEndings(this string value) { if (!string.IsNullOrEmpty(value)) { StringBuilder stringBuilder = StringBuilderPool.Obtain(); bool flag = false; int length = value.Length; for (int i = 0; i < length; i++) { char c = value[i]; bool flag2 = c == '\n'; if (flag && !flag2) { stringBuilder.Append('\n'); } else if (!flag && flag2) { stringBuilder.Append('\r'); } flag = c == '\r'; stringBuilder.Append(c); } if (flag) { stringBuilder.Append('\n'); } return stringBuilder.ToPool(); } return value; } public static string? ToEncodingType(this string? encType) { if (!encType.Isi(MimeTypeNames.Plain) && !encType.Isi(MimeTypeNames.MultipartForm) && !encType.Isi(MimeTypeNames.ApplicationJson)) { return null; } return encType?.ToLowerInvariant(); } public static string? ToFormMethod(this string? method) { if (!method.Isi(FormMethodNames.Get) && !method.Isi(FormMethodNames.Post) && !method.Isi(FormMethodNames.Dialog)) { return null; } return method?.ToLowerInvariant(); } } public sealed class StringSource { private readonly string _content; private readonly int _last; private int _index; private char _current; public char Current => _current; public bool IsDone => _current == '\uffff'; public int Index => _index; public string Content => _content; public StringSource(string content) { _content = content ?? string.Empty; _last = _content.Length - 1; _index = 0; _current = ((_last == -1) ? '\uffff' : content[0]); } public char Next() { if (_index == _last) { _current = '\uffff'; _index = _content.Length; } else if (_index < _content.Length) { _current = _content[++_index]; } return _current; } public char Back() { if (_index > 0) { _current = _content[--_index]; } return _current; } } public static class StringSourceExtensions { public static char SkipSpaces(this StringSource source) { char c = source.Current; while (c.IsSpaceCharacter()) { c = source.Next(); } return c; } public static char Next(this StringSource source, int n) { for (int i = 0; i < n; i++) { source.Next(); } return source.Current; } public static char Back(this StringSource source, int n) { for (int i = 0; i < n; i++) { source.Back(); } return source.Current; } public static char Peek(this StringSource source) { char result = source.Next(); source.Back(); return result; } } public static class Symbols { public const char EndOfFile = '\uffff'; public const char Tilde = '~'; public const char Pipe = '|'; public const char Null = '\0'; public const char Ampersand = '&'; public const char Num = '#'; public const char Dollar = '$'; public const char Semicolon = ';'; public const char Asterisk = '*'; public const char Equality = '='; public const char Plus = '+'; public const char Minus = '-'; public const char Comma = ','; public const char Dot = '.'; public const char Accent = '^'; public const char At = '@'; public const char LessThan = '<'; public const char GreaterThan = '>'; public const char SingleQuote = '\''; public const char DoubleQuote = '"'; public const char CurvedQuote = '`'; public const char QuestionMark = '?'; public const char Tab = '\t'; public const char LineFeed = '\n'; public const char CarriageReturn = '\r'; public const char FormFeed = '\f'; public const char Space = ' '; public const char Solidus = '/'; public const char NoBreakSpace = '\u00a0'; public const char ReverseSolidus = '\\'; public const char Colon = ':'; public const char ExclamationMark = '!'; public const char Replacement = '\ufffd'; public const char Underscore = '_'; public const char RoundBracketOpen = '('; public const char RoundBracketClose = ')'; public const char SquareBracketOpen = '['; public const char SquareBracketClose = ']'; public const char CurlyBracketOpen = '{'; public const char CurlyBracketClose = '}'; public const char Percent = '%'; public const int MaximumCodepoint = 1114111; } public static class TextEncoding { public static readonly Encoding Utf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); public static readonly Encoding Utf16Be = new UnicodeEncoding(bigEndian: true, byteOrderMark: false); public static readonly Encoding Utf16Le = new UnicodeEncoding(bigEndian: false, byteOrderMark: false); public static readonly Encoding Utf32Le = GetEncoding("UTF-32LE"); public static readonly Encoding Utf32Be = GetEncoding("UTF-32BE"); public static readonly Encoding Gb18030 = GetEncoding("GB18030"); public static readonly Encoding Big5 = GetEncoding("big5"); public static readonly Encoding Windows874 = GetEncoding("windows-874"); public static readonly Encoding Windows1250 = GetEncoding("windows-1250"); public static readonly Encoding Windows1251 = GetEncoding("windows-1251"); public static readonly Encoding Windows1252 = GetEncoding("windows-1252"); public static readonly Encoding Windows1253 = GetEncoding("windows-1253"); public static readonly Encoding Windows1254 = GetEncoding("windows-1254"); public static readonly Encoding Windows1255 = GetEncoding("windows-1255"); public static readonly Encoding Windows1256 = GetEncoding("windows-1256"); public static readonly Encoding Windows1257 = GetEncoding("windows-1257"); public static readonly Encoding Windows1258 = GetEncoding("windows-1258"); public static readonly Encoding Latin2 = GetEncoding("iso-8859-2"); public static readonly Encoding Latin3 = GetEncoding("iso-8859-3"); public static readonly Encoding Latin4 = GetEncoding("iso-8859-4"); public static readonly Encoding Latin5 = GetEncoding("iso-8859-5"); public static readonly Encoding Latin13 = GetEncoding("iso-8859-13"); public static readonly Encoding UsAscii = GetEncoding("us-ascii"); public static readonly Encoding Korean = GetEncoding("ks_c_5601-1987"); private static readonly Dictionary<string, Encoding> encodings = CreateEncodings(); public static bool IsUnicode(this Encoding encoding) { if (encoding != Utf16Be) { return encoding == Utf16Le; } return true; } public static Encoding? Parse(string content) { string charset = string.Empty; int num = 0; for (int i = num; i < content.Length - 7; i++) { if (content.Substring(i).StartsWith(AttributeNames.Charset, StringComparison.OrdinalIgnoreCase)) { num = i + 7; break; } } if (num > 0 && num < content.Length) { for (int j = num; j < content.Length - 1 && content[j].IsSpaceCharacter(); j++) { num++; } if (content[num] != '=') { return Parse(content.Substring(num)); } num++; for (int k = num; k < content.Length && content[k].IsSpaceCharacter(); k++) { num++; } if (num < content.Length) { if (content[num] == '"') { content = content.Substring(num + 1); int num2 = content.IndexOf('"'); if (num2 != -1) { charset = content.Substring(0, num2); } } else if (content[num] == '\'') { content = content.Substring(num + 1); int num3 = content.IndexOf('\''); if (num3 != -1) { charset = content.Substring(0, num3); } } else { content = content.Substring(num); int num4 = 0; for (int l = 0; l < content.Length && !content[l].IsSpaceCharacter() && content[l] != ';'; l++) { num4++; } charset = content.Substring(0, num4); } } } if (!IsSupported(charset)) { return null; } return Resolve(charset); } public static bool IsSupported(string charset) { return encodings.ContainsKey(charset); } public static Encoding Resolve(string? charset) { if (charset != null && encodings.TryGetValue(charset, out Encoding value)) { return value; } return Utf8; } private static Encoding GetEncoding(string name, Encoding? fallback = null) { try { return Encoding.GetEncoding(name); } catch (Exception) { return fallback ?? Utf8; } } private static Dictionary<string, Encoding> CreateEncodings() { Dictionary<string, Encoding> obj = new Dictionary<string, Encoding>(StringComparer.OrdinalIgnoreCase) { { "unicode-1-1-utf-8", Utf8 }, { "utf-8", Utf8 }, { "utf8", Utf8 }, { "utf-16be", Utf16Be }, { "utf-16", Utf16Le }, { "utf-16le", Utf16Le }, { "dos-874", Windows874 }, { "iso-8859-11", Windows874 }, { "iso8859-11", Windows874 }, { "iso885911", Windows874 }, { "tis-620", Windows874 }, { "windows-874", Windows874 }, { "cp1250", Windows1250 }, { "windows-1250", Windows1250 }, { "x-cp1250", Windows1250 }, { "cp1251", Windows1251 }, { "windows-1251", Windows1251 }, { "x-cp1251", Windows1251 }, { "x-user-defined", Windows1252 }, { "ansi_x3.4-1968", Windows1252 }, { "ascii", Windows1252 }, { "cp1252", Windows1252 }, { "cp819", Windows1252 }, { "csisolatin1", Windows1252 }, { "ibm819", Windows1252 }, { "iso-8859-1", Windows1252 }, { "iso-ir-100", Windows1252 }, { "iso8859-1", Windows1252 }, { "iso88591", Windows1252 }, { "iso_8859-1", Windows1252 }, { "iso_8859-1:1987", Windows1252 }, { "l1", Windows1252 }, { "latin1", Windows1252 }, { "us-ascii", Windows1252 }, { "windows-1252", Windows1252 }, { "x-cp1252", Windows1252 }, { "cp1253", Windows1253 }, { "windows-1253", Windows1253 }, { "x-cp1253", Windows1253 }, { "cp1254", Windows1254 }, { "csisolatin5", Windows1254 }, { "iso-8859-9", Windows1254 }, { "iso-ir-148", Windows1254 }, { "iso8859-9", Windows1254 }, { "iso88599", Windows1254 }, { "iso_8859-9", Windows1254 }, { "iso_8859-9:1989", Windows1254 }, { "l5", Windows1254 }, { "latin5", Windows1254 }, { "windows-1254", Windows1254 }, { "x-cp1254", Windows1254 }, { "cp1255", Windows1255 }, { "windows-1255", Windows1255 }, { "x-cp1255", Windows1255 }, { "cp1256", Windows1256 }, { "windows-1256", Windows1256 }, { "x-cp1256", Windows1256 }, { "cp1257", Windows1257 }, { "windows-1257", Windows1257 }, { "x-cp1257", Windows1257 }, { "cp1258", Windows1258 }, { "windows-1258", Windows1258 }, { "x-cp1258", Windows1258 } }; Encoding encoding = GetEncoding("macintosh"); obj.Add("csmacintosh", encoding); obj.Add("mac", encoding); obj.Add("macintosh", encoding); obj.Add("x-mac-roman", encoding); Encoding encoding2 = GetEncoding("x-mac-cyrillic"); obj.Add("x-mac-cyrillic", encoding2); obj.Add("x-mac-ukrainian", encoding2); Encoding encoding3 = GetEncoding("cp866"); obj.Add("866", encoding3); obj.Add("cp866", encoding3); obj.Add("csibm866", encoding3); obj.Add("ibm866", encoding3); obj.Add("csisolatin2", Latin2); obj.Add("iso-8859-2", Latin2); obj.Add("iso-ir-101", Latin2); obj.Add("iso8859-2", Latin2); obj.Add("iso88592", Latin2); obj.Add("iso_8859-2", Latin2); obj.Add("iso_8859-2:1987", Latin2); obj.Add("l2", Latin2); obj.Add("latin2", Latin2); obj.Add("csisolatin3", Latin3); obj.Add("iso-8859-3", Latin3); obj.Add("iso-ir-109", Latin3); obj.Add("iso8859-3", Latin3); obj.Add("iso88593", Latin3); obj.Add("iso_8859-3", Latin3); obj.Add("iso_8859-3:1988", Latin3); obj.Add("l3", Latin3); obj.Add("latin3", Latin3); obj.Add("csisolatin4", Latin4); obj.Add("iso-8859-4", Latin4); obj.Add("iso-ir-110", Latin4); obj.Add("iso8859-4", Latin4); obj.Add("iso88594", Latin4); obj.Add("iso_8859-4", Latin4); obj.Add("iso_8859-4:1988", Latin4); obj.Add("l4", Latin4); obj.Add("latin4", Latin4); obj.Add("csisolatincyrillic", Latin5); obj.Add("cyrillic", Latin5); obj.Add("iso-8859-5", Latin5); obj.Add("iso-ir-144", Latin5); obj.Add("iso8859-5", Latin5); obj.Add("iso88595", Latin5); obj.Add("iso_8859-5", Latin5); obj.Add("iso_8859-5:1988", Latin5); Encoding encoding4 = GetEncoding("iso-8859-6"); obj.Add("arabic", encoding4); obj.Add("asmo-708", encoding4); obj.Add("csiso88596e", encoding4); obj.Add("csiso88596i", encoding4); obj.Add("csisolatinarabic", encoding4); obj.Add("ecma-114", encoding4); obj.Add("iso-8859-6", encoding4); obj.Add("iso-8859-6-e", encoding4); obj.Add("iso-8859-6-i", encoding4); obj.Add("iso-ir-127", encoding4); obj.Add("iso8859-6", encoding4); obj.Add("iso88596", encoding4); obj.Add("iso_8859-6", encoding4); obj.Add("iso_8859-6:1987", encoding4); Encoding encoding5 = GetEncoding("iso-8859-7"); obj.Add("csisolatingreek", encoding5); obj.Add("ecma-118", encoding5); obj.Add("elot_928", encoding5); obj.Add("greek", encoding5); obj.Add("greek8", encoding5); obj.Add("iso-8859-7", encoding5); obj.Add("iso-ir-126", encoding5); obj.Add("iso8859-7", encoding5); obj.Add("iso88597", encoding5); obj.Add("iso_8859-7", encoding5); obj.Add("iso_8859-7:1987", encoding5); obj.Add("sun_eu_greek", encoding5); Encoding encoding6 = GetEncoding("iso-8859-8"); obj.Add("csiso88598e", encoding6); obj.Add("csisolatinhebrew", encoding6); obj.Add("hebrew", encoding6); obj.Add("iso-8859-8", encoding6); obj.Add("iso-8859-8-e", encoding6); obj.Add("iso-ir-138", encoding6); obj.Add("iso8859-8", encoding6); obj.Add("iso88598", encoding6); obj.Add("iso_8859-8", encoding6); obj.Add("iso_8859-8:1988", encoding6); obj.Add("visual", encoding6); Encoding encoding7 = GetEncoding("iso-8859-8-i"); obj.Add("csiso88598i", encoding7); obj.Add("iso-8859-8-i", encoding7); obj.Add("logical", encoding7); Encoding encoding8 = GetEncoding("iso-8859-13"); obj.Add("iso-8859-13", encoding8); obj.Add("iso8859-13", encoding8); obj.Add("iso885913", encoding8); Encoding encoding9 = GetEncoding("iso-8859-15"); obj.Add("csisolatin9", encoding9); obj.Add("iso-8859-15", encoding9); obj.Add("iso8859-15", encoding9); obj.Add("iso885915", encoding9); obj.Add("iso_8859-15", encoding9); obj.Add("l9", encoding9); Encoding encoding10 = GetEncoding("koi8-r"); obj.Add("cskoi8r", encoding10); obj.Add("koi", encoding10); obj.Add("koi8", encoding10); obj.Add("koi8-r", encoding10); obj.Add("koi8_r", encoding10); obj.Add("koi8-u", GetEncoding("koi8-u")); Encoding encoding11 = GetEncoding("GB18030", GetEncoding("x-cp20936")); obj.Add("chinese", encoding11); obj.Add("csgb2312", encoding11); obj.Add("csiso58gb231280", encoding11); obj.Add("gb2312", encoding11); obj.Add("gb_2312", encoding11); obj.Add("gb_2312-80", encoding11); obj.Add("gbk", encoding11); obj.Add("iso-ir-58", encoding11); obj.Add("x-gbk", encoding11); obj.Add("hz-gb-2312", GetEncoding("hz-gb-2312")); obj.Add("gb18030", Gb18030); Encoding encoding12 = GetEncoding("x-cp50227"); obj.Add("x-cp50227", encoding12); obj.Add("iso-22-cn", encoding12); obj.Add("big5", Big5); obj.Add("big5-hkscs", Big5); obj.Add("cn-big5", Big5); obj.Add("csbig5", Big5); obj.Add("x-x-big5", Big5); Encoding encoding13 = GetEncoding("iso-2022-jp"); obj.Add("csiso2022jp", encoding13); obj.Add("iso-2022-jp", encoding13); Encoding encoding14 = GetEncoding("iso-2022-kr"); obj.Add("csiso2022kr", encoding14); obj.Add("iso-2022-kr", encoding14); Encoding encoding15 = GetEncoding("iso-2022-cn"); obj.Add("iso-2022-cn", encoding15); obj.Add("iso-2022-cn-ext", encoding15); obj.Add("shift_jis", GetEncoding("shift_jis")); Encoding encoding16 = GetEncoding("euc-jp"); obj.Add("euc-jp", encoding16); Encoding encoding17 = GetEncoding("euc-kr"); obj.Add("euc-kr", encoding17); return obj; } } public readonly struct TextPosition : IEquatable<TextPosition>, IComparable<TextPosition> { public static readonly TextPosition Empty; private readonly ushort _line; private readonly ushort _column; private readonly int _position; public int Line => _line; public int Column => _column; public int Position => _position; public int Index => _position - 1; public TextPosition(ushort line, ushort column, int position) { _line = line; _column = column; _position = position; } public TextPosition Shift(int columns) { return new TextPosition(_line, (ushort)(_column + columns), _position + columns); } public TextPosition After(char chr) { ushort num = _line; ushort num2 = _column; if (chr == '\n') { num++; num2 = 0; } return new TextPosition(num, ++num2, _position + 1); } public TextPosition After(string str) { ushort num = _line; ushort num2 = _column; for (int i = 0; i < str.Length; i++) { if (str[i] == '\n') { num++; num2 = 0; } num2++; } return new TextPosition(num, num2, _position + str.Length); } public override string ToString() { return $"Ln {_line}, Col {_column}, Pos {_position}"; } public override int GetHashCode() { return _position ^ ((_line | _column) + _line); } public override bool Equals(object? obj) { if (obj is TextPosition other) { return Equals(other); } return false; } public bool Equals(TextPosition other) { if (_position == other._position && _column == other._column) { return _line == other._line; } return false; } public static bool operator >(TextPosition a, TextPosition b) { return a._position > b._position; } public static bool operator <(TextPosition a, TextPosition b) { return a._position < b._position; } public int CompareTo(TextPosition other) { if (!Equals(other)) { if (!(this > other)) { return -1; } return 1; } return 0; } } [DebuggerStepThrough] public readonly struct TextRange : IEquatable<TextRange>, IComparable<TextRange> { private readonly TextPosition _start; private readonly TextPosition _end; public TextPosition Start => _start; public TextPosition End => _end; public TextRange(TextPosition start, TextPosition end) { _start = start; _end = end; } public override string ToString() { return $"({_start}) -- ({_end})"; } public override int GetHashCode() { return _end.GetHashCode() ^ _start.GetHashCode(); } public override bool Equals(object? obj) { if (obj is TextRange other) { return Equals(other); } return false; } public bool Equals(TextRange other) { if (_start.Equals(other._start)) { return _end.Equals(other._end); } return false; } public static bool operator >(TextRange a, TextRange b) { return a._start > b._end; } public static bool operator <(TextRange a, TextRange b) { return a._end < b._start; } public int CompareTo(TextRange other) { if (this > other) { return 1; } if (other > this) { return -1; } return 0; } } public sealed class TextSource : IDisposable { private enum EncodingConfidence : byte { Tentative, Certain, Irrelevant } private const int BufferSize = 4096; private readonly Stream _baseStream; private readonly MemoryStream _raw; private readonly byte[] _buffer; private readonly char[] _chars; private StringBuilder _content; private EncodingConfidence _confidence; private bool _finished; private Encoding _encoding; private Decoder _decoder; private int _index; [MemberNotNull("_content")] public string Text { [MemberNotNull("_content")] get { return _content.ToString(); } } public char this[int index] => Replace(_content[index]); public int Length => _content.Length; public Encoding CurrentEncoding { get { return _encoding; } set { if (_confidence != 0) { return; } if (_encoding.IsUnicode()) { _confidence = EncodingConfidence.Certain; return; } if (value.IsUnicode()) { value = TextEncoding.Utf8; } if (value == _encoding) { _confidence = EncodingConfidence.Certain; return; } _encoding = value; _decoder = value.GetDecoder(); byte[] array = _raw.ToArray(); char[] array2 = new char[_encoding.GetMaxCharCount(array.Length)]; int chars = _decoder.GetChars(array, 0, array.Length, array2, 0); string text = new string(array2, 0, chars); int num = Math.Min(_index, text.Length); if (text.Substring(0, num).Is(_content.ToString(0, num))) { _confidence = EncodingConfidence.Certain; _content.Remove(num, _content.Length - num); _content.Append(text.Substring(num)); return; } _index = 0; _content.Clear().Append(text); throw new NotSupportedException(); } } public int Index { get { return _index; } set { _index = value; } } private TextSource(Encoding encoding, bool allocateBuffers) { if (allocateBuffers) { _buffer = new byte[4096]; _chars = new char[4097]; } _raw = new MemoryStream(); _index = 0; _encoding = encoding ?? TextEncoding.Utf8; _decoder = _encoding.GetDecoder(); } public TextSource(string source) : this(null, TextEncoding.Utf8) { _finished = true; _content.Append(source); _confidence = EncodingConfidence.Irrelevant; } public TextSource(Stream baseStream, Encoding encoding = null) : this(encoding, baseStream != null) { _baseStream = baseStream; _content = StringBuilderPool.Obtain(); _confidence = EncodingConfidence.Tentative; } public void Dispose() { if (_content != null) { _raw.Dispose(); _content.Clear().ReturnToPool(); _content = null; } } public char ReadCharacter() { if (_index < _content.Length) { return Replace(_content[_index++]); } ExpandBuffer(4096L); int num = _index++; if (num >= _content.Length) { return '\uffff'; } return Replace(_content[num]); } public string ReadCharacters(int characters) { int index = _index; if (index + characters <= _content.Length) { _index += characters; return _content.ToString(index, characters); } ExpandBuffer(Math.Max(4096, characters)); _index += characters; characters = Math.Min(characters, _content.Length - index); return _content.ToString(index, characters); } public Task PrefetchAsync(int length, CancellationToken cancellationToken) { return ExpandBufferAsync(length, cancellationToken); } public async Task PrefetchAllAsync(CancellationToken cancellationToken) { if (_baseStream != null && _content.Length == 0) { await DetectByteOrderMarkAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } while (!_finished) { await ReadIntoBufferAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } } public void InsertText(string content) { if (_index >= 0 && _index < _content.Length) { _content.Insert(_index, content); } else { _content.Append(content); } _index += content.Length; } private static char Replace(char c) { if (c != '\uffff') { return c; } return '\ufffd'; } private async Task DetectByteOrderMarkAsync(CancellationToken cancellationToken) { int num = await _baseStream.ReadAsync(_buffer, 0, 4096).ConfigureAwait(continueOnCapturedContext: false); int num2 = 0; if (num > 2 && _buffer[0] == 239 && _buffer[1] == 187 && _buffer[2] == 191) { _encoding = TextEncoding.Utf8; num2 = 3; } else if (num > 3 && _buffer[0] == byte.MaxValue && _buffer[1] == 254 && _buffer[2] == 0 && _buffer[3] == 0) { _encoding = TextEncoding.Utf32Le; num2 = 4; } else if (num > 3 && _buffer[0] == 0 && _buffer[1] == 0 && _buffer[2] == 254 && _buffer[3] == byte.MaxValue) { _encoding = TextEncoding.Utf32Be; num2 = 4; } else if (num > 1 && _buffer[0] == 254 && _buffer[1] == byte.MaxValue) { _encoding = TextEncoding.Utf16Be; num2 = 2; } else if (num > 1 && _buffer[0] == byte.MaxValue && _buffer[1] == 254) { _encoding = TextEncoding.Utf16Le; num2 = 2; } else if (num > 3 && _buffer[0] == 132 && _buffer[1] == 49 && _buffer[2] == 149 && _buffer[3] == 51) { _encoding = TextEncoding.Gb18030; num2 = 4; } if (num2 > 0) { num -= num2; Array.Copy(_buffer, num2, _buffer, 0, num); _decoder = _encoding.GetDecoder(); _confidence = EncodingConfidence.Certain; } AppendContentFromBuffer(num); } private async Task ExpandBufferAsync(long size, CancellationToken cancellationToken) { if (!_finished && _content.Length == 0) { await DetectByteOrderMarkAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } while (!_finished && size + _index > _content.Length) { await ReadIntoBufferAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } } private async Task ReadIntoBufferAsync(CancellationToken cancellationToken) { AppendContentFromBuffer(await _baseStream.ReadAsync(_buffer, 0, 4096, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)); } private void ExpandBuffer(long size) { if (!_finished && _content.Length == 0) { DetectByteOrderMarkAsync(CancellationToken.None).Wait(); } while (!_finished && size + _index > _content.Length) { ReadIntoBuffer(); } } private void ReadIntoBuffer() { int size = _baseStream.Read(_buffer, 0, 4096); AppendContentFromBuffer(size); } private void AppendContentFromBuffer(int size) { _finished = size == 0; int chars = _decoder.GetChars(_buffer, 0, size, _chars, 0); if (_confidence != EncodingConfidence.Certain) { _raw.Write(_buffer, 0, size); } _content.Append(_chars, 0, chars); } } public class TextView { private readonly TextSource _source; private readonly TextRange _range; public TextRange Range => _range; public string Text { get { int num = Math.Max(_range.Start.Position - 1, 0); int num2 = _range.End.Position + 1 - _range.Start.Position; string text = _source.Text; if (num + num2 > text.Length) { num2 = text.Length - num; } return text.Substring(num, num2); } } public TextView(TextSource source, TextRange range) { _source = source; _range = range; } } public static class XmlExtensions { public static bool IsPubidChar(this char c) { if (!c.IsAlphanumericAscii() && c != '-' && c != '\'' && c != '+' && c != ',' && c != '.' && c != '/' && c != ':' && c != '?' && c != '=' && c != '!' && c != '*' && c != '#' && c != '@' && c != '$' && c != '_' && c != '(' && c != ')' && c != ';' && c != '%') { return c.IsSpaceCharacter(); } return true; } public static bool IsXmlNameStart(this char c) { if (!c.IsLetter() && c != ':' && c != '_' && !c.IsInRange(192, 214) && !c.IsInRange(216, 246) && !c.IsInRange(248, 767) && !c.IsInRange(880, 893) && !c.IsInRange(895, 8191) && !c.IsInRange(8204, 8205) && !c.IsInRange(8304, 8591) && !c.IsInRange(11264, 12271) && !c.IsInRange(12289, 55295) && !c.IsInRange(63744, 64975) && !c.IsInRange(65008, 65533)) { return c.IsInRange(65536, 983039); } return true; } public static bool IsXmlName(this char c) { if (!c.IsXmlNameStart() && !c.IsDigit() && c != '-' && c != '.' && c != '·' && !c.IsInRange(768, 879)) { return c.IsInRange(8255, 8256); } return true; } public static bool IsXmlName(this string str) { if (str.Length > 0 && str[0].IsXmlNameStart()) { for (int i = 1; i < str.Length; i++) { if (!str[i].IsXmlName()) { return false; } } return true; } return false; } public static bool IsQualifiedName(this string str) { int num = str.IndexOf(':'); if (num == -1) { return str.IsXmlName(); } if (num > 0 && str[0].IsXmlNameStart()) { for (int i = 1; i < num; i++) { if (!str[i].IsXmlName()) { return false; } } num++; } if (str.Length > num && str[num++].IsXmlNameStart()) { for (int j = num; j < str.Length; j++) { if (str[j] == ':' || !str[j].IsXmlName()) { return false; } } return true; } return false; } public static bool IsXmlChar(this char chr) { if (chr != '\t' && chr != '\n' && chr != '\r' && (chr < ' ' || chr > '\ud7ff')) { if (chr >= '\ue000') { return chr <= '\ufffd'; } return false; } return true; } public static bool IsValidAsCharRef(this int chr) { if (chr != 9 && chr != 10 && chr != 13 && (chr < 32 || chr > 55295) && (chr < 57344 || chr > 65533)) { if (chr >= 65536) { return chr <= 1114111; } return false; } return true; } } } namespace AngleSharp.Svg { internal sealed class SvgElementFactory : IElementFactory<Document, SvgElement> { private delegate SvgElement Creator(Document owner, string? prefix); private readonly Dictionary<string, Creator> creators = new Dictionary<string, Creator>(StringComparer.OrdinalIgnoreCase) { { TagNames.Svg, (Document document, string? prefix) => new SvgSvgElement(document, prefix) }, { TagNames.Circle, (Document document, string? prefix) => new SvgCircleElement(document, prefix) }, { TagNames.Desc, (Document document, string? prefix) => new SvgDescElement(document, prefix) }, { TagNames.ForeignObject, (Document document, string? prefix) => new SvgForeignObjectElement(document, prefix) }, { TagNames.Title, (Document document, string? prefix) => new SvgTitleElement(document, prefix) } }; public SvgElement Create(Document document, string localName, string? prefix = null, NodeFlags flags = NodeFlags.None) { if (creators.TryGetValue(localName, out Creator value)) { return value(document, prefix); } return new SvgElement(document, localName, prefix, flags); } } } namespace AngleSharp.Svg.Dom { internal sealed class SvgCircleElement : SvgElement, ISvgCircleElement, ISvgElement, IElement, INode, IEventTarget, IMarkupFormattable, IParentNode, IChildNode, INonDocumentTypeChildNode { public SvgCircleElement(Document owner, string? prefix = null) : base(owner, TagNames.Circle, prefix) { } } internal sealed class SvgDescElement : SvgElement, ISvgDescriptionElement, ISvgElement, IElement, INode, IEventTarget, IMarkupFormattable, IParentNode, IChildNode, INonDocumentTypeChildNode { public SvgDescElement(Document owner, string? prefix = null) : base(owner, TagNames.Desc, prefix, NodeFlags.Special | NodeFlags.Scoped | NodeFlags.HtmlTip) { } } public class SvgElement : Element, ISvgElement, IElement, INode, IEventTarget, IMarkupFormattable, IParentNode, IChildNode, INonDocumentTypeChildNode { public SvgElement(Document owner, string name, string? prefix = null, NodeFlags flags = NodeFlags.None) : base(owner, name, prefix, NamespaceNames.SvgUri, flags | NodeFlags.SvgMember) { } public override IElement ParseSubtree(string html) { return this.ParseHtmlSubtree(html); } public override Node Clone(Document owner, bool deep) { SvgElement svgElement = base.Context.GetFactory<IElementFactory<Document, SvgElement>>().Create(owner, base.LocalName, base.Prefix); CloneElement(svgElement, owner, deep); return svgElement; } } internal sealed class SvgForeignObjectElement : SvgElement, ISvgForeignObjectElement, ISvgElement, IElement, INode, IEventTarget, IMarkupFormattable, IParentNode, IChildNode, INonDocumentTypeChildNode { public SvgForeignObjectElement(Document owner, string? prefix = null) : base(owner, TagNames.ForeignObject, prefix, NodeFlags.Special | NodeFlags.Scoped | NodeFlags.HtmlTip) { } } internal sealed class SvgSvgElement : SvgElement, ISvgSvgElement, ISvgElement, IElement, INode, IEventTarget, IMarkupFormattable, IParentNode, IChildNode, INonDocumentTypeChildNode { public SvgSvgElement(Document owner, string? prefix = null) : base(owner, TagNames.Svg, prefix) { } } internal sealed class SvgTitleElement : SvgElement, ISvgTitleElement, ISvgElement, IElement, INode, IEventTarget, IMarkupFormattable, IParentNode, IChildNode, INonDocumentTypeChildNode { public SvgTitleElement(Document owner, string? prefix = null) : base(owner, TagNames.Title, prefix, NodeFlags.Special | NodeFlags.Scoped | NodeFlags.HtmlTip) { } } [DomName("SVGCircleElement")] public interface ISvgCircleElement : ISvgElement, IElement, INode, IEventTarget, IMarkupFormattable, IParentNode, IChildNode, INonDocumentTypeChildNode { } [DomName("SVGDescElement")] public interface ISvgDescriptionElement : ISvgElement, IElement, INode, IEventTarget, IMarkupFormattable, IParentNode, IChildNode, INonDocumentTypeChildNode { } [DomName("SVGElement")] public interface ISvgElement : IElement, INode, IEventTarget, IMarkupFormattable, IParentNode, IChildNode, INonDocumentTypeChildNode { } [DomName("SVGForeignObjectElement")] public interface ISvgForeignObjectElement : ISvgElement, IElement, INode, IEventTarget, IMarkupFormattable, IParentNode, IChildNode, INonDocumentTypeChildNode { } [DomName("SVGSVGElement")] public interface ISvgSvgElement : ISvgElement, IElement, INode, IEventTarget, IMarkupFormattable, IParentNode, IChildNode, INonDocumentTypeChildNode { } [DomName("SVGTitleElement")] public interface ISvgTitleElement : ISvgElement, IElement, INode, IEventTarget, IMarkupFormattable, IParentNode, IChildNode, INonDocumentTypeChildNode { } } namespace AngleSharp.Scripting { public interface IScriptingService { bool SupportsType(string mimeType); Task EvaluateScriptAsync(IResponse response, ScriptOptions options, CancellationToken cancel); } public sealed class ScriptOptions { public IEventLoop EventLoop { get; } public IDocument Document { get; } public IHtmlScriptElement? Element { get; set; } public Encoding? Encoding { get; set; } public ScriptOptions(IDocument document, IEventLoop loop) { Document = document; EventLoop = loop; } } } namespace AngleSharp.Media { public interface IAudioInfo : IMediaInfo, IResourceInfo { } public interface IImageInfo : IResourceInfo { int Width { get; } int Height { get; } } public interface IMediaInfo : IResourceInfo { IMediaController Controller { get; } } public interface IObjectInfo : IResourceInfo { int Width { get; } int Height { get; } } public interface IResourceInfo { Url Source { get; set; } } public interface IResourceService<TResource> where TResource : IResourceInfo { bool SupportsType(string mimeType); Task<TResource> CreateAsync(IResponse response, CancellationToken cancel); } public interface IVideoInfo : IMediaInfo, IResourceInfo { int Width { get; } int Height { get; } } } namespace AngleSharp.Media.Dom { [DomName("AudioTrack")] public interface IAudioTrack { [DomName("id")] string? Id { get; } [DomName("kind")] string? Kind { get; } [DomName("label")] string? Label { get; } [DomName("language")] string? Language { get; } [DomName("enabled")] bool IsEnabled { get; set; } } [DomName("AudioTrackList")] public interface IAudioTrackList : IEventTarget, IEnumerable<IAudioTrack>, IEnumerable { [DomName("length")] int Length { get; } [DomAccessor(Accessors.Getter)] IAudioTrack this[int index] { get; } [DomName("onchange")] event DomEventHandler Changed; [DomName("onaddtrack")] event DomEventHandler TrackAdded; [DomName("onremovetrack")] event DomEventHandler TrackRemoved; [DomName("getTrackById")] IAudioTrack GetTrackById(string id); } [DomName("CanvasRenderingContext2D")] public interface ICanvasRenderingContext2D : IRenderingContext { [DomName("canvas")] IHtmlCanvasElement Canvas { get; } [DomName("width")] int Width { get; set; } [DomName("height")] int Height { get; set; } [DomName("save")] void SaveState(); [DomName("restore")] void RestoreState(); } [DomName("MediaController")] public interface IMediaController { [DomName("buffered")] ITimeRanges? BufferedTime { get; } [DomName("seekable")] ITimeRanges? SeekableTime { get; } [DomName("played")] ITimeRanges? PlayedTime { get; } [DomName("duration")] double Duration { get; } [DomName("currentTime")] double CurrentTime { get; set; } [DomName("defaultPlaybackRate")] double DefaultPlaybackRate { get; set; } [DomName("playbackRate")] double PlaybackRate { get; set; } [DomName("volume")] double Volume { get; set; } [DomName("muted")] bool IsMuted { get; set; } [DomName("paused")] bool IsPaused { get; } [DomName("readyState")] MediaReadyState ReadyState { get; } [DomName("playbackState")] MediaControllerPlaybackState PlaybackState { get; } [DomName("onemptied")] event DomEventHandler Emptied; [DomName("onloadedmetadata")] event DomEventHandler LoadedMetadata; [DomName("onloadeddata")] event DomEventHandler LoadedData; [DomName("oncanplay")] event DomEventHandler CanPlay; [DomName("oncanplaythrough")] event DomEventHandler CanPlayThrough; [DomName("onended")] event DomEventHandler Ended; [DomName("onwaiting")] event DomEventHandler Waiting; [DomName("ondurationchange")] event DomEventHandler DurationChanged; [DomName("ontimeupdate")] event DomEventHandler TimeUpdated; [DomName("onpause")] event DomEventHandler Paused; [DomName("onplay")] event DomEventHandler Played; [DomName("onplaying")] event DomEventHandler Playing; [DomName("onratechange")] event DomEventHandler RateChanged; [DomName("onvolumechange")] event DomEventHandler VolumeChanged; [DomName("play")] void Play(); [DomName("pause")] void Pause(); } [DomName("MediaError")] public interface IMediaError { [DomName("code")] MediaErrorCode Code { get; } } [DomName("RenderingContext")] public interface IRenderingContext { string ContextId { get; } bool IsFixed { get; } IHtmlCanvasElement Host { get; } byte[] ToImage(string type); } public interface IRenderingService { bool IsSupportingContext(string contextId); IRenderingContext CreateContext(IHtmlCanvasElement host, string contextId); } [DomName("TextTrack")] public interface ITextTrack : IEventTarget { [DomName("kind")] string? Kind { get; } [DomName("label")] string? Label { get; } [DomName("language")] string? Language { get; } [DomName("mode")] TextTrackMode Mode { get; set; } [DomName("cues")] ITextTrackCueList Cues { get; } [DomName("activeCues")] ITextTrackCueList ActiveCues { get; } [DomName("oncuechange")] event DomEventHandler CueChanged; [DomName("addCue")] void Add(ITextTrackCue cue); [DomName("removeCue")] void Remove(ITextTrackCue cue); } [DomName("TextTrackCue")] public interface ITextTrackCue : IEventTarget { [DomName("id")] string Id { get; set; } [DomName("track")] ITextTrack Track { get; } [DomName("startTime")] double StartTime { get; set; } [DomName("endTime")] double EndTime { get; set; } [DomName("pauseOnExit")] bool IsPausedOnExit { get; set; } [DomName("vertical")] string Vertical { get; set; } [DomName("snapToLines")] bool IsSnappedToLines { get; set; } [DomName("line")] int Line { get; set; } [DomName("position")] int Position { get; set; } [DomName("size")] int Size { get; set; } [DomName("align")] string Alignment { get; set; } [DomName("text")] string Text { get; set; } [DomName("onenter")] DomEventHandler Entered { get; set; } [DomName("onexit")] DomEventHandler Exited { get; set; } [DomName("getCueAsHTML")] IDocumentFragment AsHtml(); } [DomName("TextTrackCueList")] public interface ITextTrackCueList : IEnumerable<ITextTrackCue>, IEnumerable { [DomName("length")] int Length { get; } ITextTrackCue this[int index] { get; } [DomName("getCueById")] IVideoTrack GetCueById(string id); } [DomName("TextTrackList")] public interface ITextTrackList : IEventTarget, IEnumerable<ITextTrack>, IEnumerable { [DomName("length")] int Length { get; } [DomAccessor(Accessors.Getter)] ITextTrack this[int index] { get; } [DomName("onaddtrack")] event DomEventHandler TrackAdded; [DomName("onremovetrack")] event DomEventHandler TrackRemoved; } [DomName("TimeRanges")] public interface ITimeRanges { [DomName("length")] int Length { get; } [DomName("start")] double Start(int index); [DomName("end")] double End(int index); } [DomName("VideoTrack")] public interface IVideoTrack { [DomName("id")] string? Id { get; } [DomName("kind")] string? Kind { get; } [DomName("label")] string? Label { get; } [DomName("language")] string? Language { get; } [DomName("selected")] bool IsSelected { get; set; } } [DomName("VideoTrackList")] public interface IVideoTrackList : IEventTarget, IEnumerable<IVideoTrack>, IEnumerable { [DomName("length")] int Length { get; } [DomName("selectedIndex")] int SelectedIndex { get; } [DomAccessor(Accessors.Getter)] IVideoTrack this[int index] { get; } [DomName("onchange")] event DomEventHandler Changed; [DomName("onaddtrack")] event DomEventHandler TrackAdded; [DomName("onremovetrack")] event DomEventHandler TrackRemoved; [DomName("getTrackById")] IVideoTrack GetTrackById(string id); } [DomName("MediaControllerPlaybackState")] public enum MediaControllerPlaybackState : byte { [DomName("waiting")] Waiting, [DomName("playing")] Playing, [DomName("ended")] Ended } [DomName("MediaError")] public enum MediaErrorCode : byte { [DomName("MEDIA_ERR_ABORTED")] Aborted = 1, [DomName("MEDIA_ERR_NETWORK")] Network, [DomName("MEDIA_ERR_DECODE")] Decode, [DomName("MEDIA_ERR_SRC_NOT_SUPPORTED")] SourceNotSupported } [DomName("HTMLMediaElement")] public enum MediaNetworkState : byte { [DomName("NETWORK_EMPTY")] Empty, [DomName("NETWORK_IDLE")] Idle, [DomName("NETWORK_LOADING")] Loading, [DomName("NETWORK_NO_SOURCE")] NoSource } [DomName("HTMLMediaElement")] public enum MediaReadyState : byte { [DomName("HAVE_NOTHING")] Nothing, [DomName("HAVE_METADATA")] Metadata, [DomName("HAVE_CURRENT_DATA")] CurrentData, [DomName("HAVE_FUTURE_DATA")] FutureData, [DomName("HAVE_ENOUGH_DATA")] EnoughData } [DomName("TextTrackMode")] public enum TextTrackMode : byte { [DomName("disabled")] Disabled, [DomName("hidden")] Hidden, [DomName("showing")] Showing } } namespace AngleSharp.Mathml { internal sealed class MathElementFactory : IElementFactory<Document, MathElement> { private delegate MathElement Creator(Document owner, string? prefix); private readonly Dictionary<string, Creator> creators = new Dictionary<string, Creator>(StringComparer.OrdinalIgnoreCase) { { TagNames.Mn, (Document document, string? prefix) => new MathNumberElement(document, prefix) }, { TagNames.Mo, (Document document, string? prefix) => new MathOperatorElement(document, prefix) }, { TagNames.Mi, (Document document, string? prefix) => new MathIdentifierElement(document, prefix) }, { TagNames.Ms, (Document document, string? prefix) => new MathStringElement(document, prefix) }, { TagNames.Mtext, (Document document, string? prefix) => new MathTextElement(document, prefix) }, { TagNames.AnnotationXml, (Document document, string? prefix) => new MathAnnotationXmlElement(document, prefix) } }; public MathElement Create(Document document, string localName, string? prefix = null, NodeFlags flags = NodeFlags.None) { if (creators.TryGetValue(localName, out Creator value)) { return value(document, prefix);
System.Buffers.dll
Decompiled 5 days agousing System; using System.Diagnostics; using System.Diagnostics.Tracing; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; using System.Threading; using FxResources.System.Buffers; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyTitle("System.Buffers")] [assembly: AssemblyDescription("System.Buffers")] [assembly: AssemblyDefaultAlias("System.Buffers")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyProduct("Microsoft® .NET Framework")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyFileVersion("4.6.28619.01")] [assembly: AssemblyInformationalVersion("4.6.28619.01 @BuiltBy: dlab14-DDVSOWINAGE069 @Branch: release/2.1 @SrcCode: https://github.com/dotnet/corefx/tree/7601f4f6225089ffb291dc7d58293c7bbf5c5d4f")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.0.3.0")] [module: UnverifiableCode] namespace FxResources.System.Buffers { internal static class SR { } } namespace System { internal static class SR { private static ResourceManager s_resourceManager; private static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(ResourceType)); internal static Type ResourceType { get; } = typeof(SR); internal static string ArgumentException_BufferNotFromPool => GetResourceString("ArgumentException_BufferNotFromPool", null); [MethodImpl(MethodImplOptions.NoInlining)] private static bool UsingResourceKeys() { return false; } internal static string GetResourceString(string resourceKey, string defaultString) { string text = null; try { text = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } if (defaultString != null && resourceKey.Equals(text, StringComparison.Ordinal)) { return defaultString; } return text; } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.All)] internal class __BlockReflectionAttribute : Attribute { } } namespace System.Buffers { public abstract class ArrayPool<T> { private static ArrayPool<T> s_sharedInstance; public static ArrayPool<T> Shared { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Volatile.Read(ref s_sharedInstance) ?? EnsureSharedCreated(); } } [MethodImpl(MethodImplOptions.NoInlining)] private static ArrayPool<T> EnsureSharedCreated() { Interlocked.CompareExchange(ref s_sharedInstance, Create(), null); return s_sharedInstance; } public static ArrayPool<T> Create() { return new DefaultArrayPool<T>(); } public static ArrayPool<T> Create(int maxArrayLength, int maxArraysPerBucket) { return new DefaultArrayPool<T>(maxArrayLength, maxArraysPerBucket); } public abstract T[] Rent(int minimumLength); public abstract void Return(T[] array, bool clearArray = false); } [EventSource(Name = "System.Buffers.ArrayPoolEventSource")] internal sealed class ArrayPoolEventSource : EventSource { internal enum BufferAllocatedReason { Pooled, OverMaximumSize, PoolExhausted } internal static readonly System.Buffers.ArrayPoolEventSource Log = new System.Buffers.ArrayPoolEventSource(); [Event(1, Level = EventLevel.Verbose)] internal unsafe void BufferRented(int bufferId, int bufferSize, int poolId, int bucketId) { EventData* ptr = stackalloc EventData[4]; *ptr = new EventData { Size = 4, DataPointer = (IntPtr)(&bufferId) }; ptr[1] = new EventData { Size = 4, DataPointer = (IntPtr)(&bufferSize) }; ptr[2] = new EventData { Size = 4, DataPointer = (IntPtr)(&poolId) }; ptr[3] = new EventData { Size = 4, DataPointer = (IntPtr)(&bucketId) }; WriteEventCore(1, 4, ptr); } [Event(2, Level = EventLevel.Informational)] internal unsafe void BufferAllocated(int bufferId, int bufferSize, int poolId, int bucketId, BufferAllocatedReason reason) { EventData* ptr = stackalloc EventData[5]; *ptr = new EventData { Size = 4, DataPointer = (IntPtr)(&bufferId) }; ptr[1] = new EventData { Size = 4, DataPointer = (IntPtr)(&bufferSize) }; ptr[2] = new EventData { Size = 4, DataPointer = (IntPtr)(&poolId) }; ptr[3] = new EventData { Size = 4, DataPointer = (IntPtr)(&bucketId) }; ptr[4] = new EventData { Size = 4, DataPointer = (IntPtr)(&reason) }; WriteEventCore(2, 5, ptr); } [Event(3, Level = EventLevel.Verbose)] internal void BufferReturned(int bufferId, int bufferSize, int poolId) { WriteEvent(3, bufferId, bufferSize, poolId); } } internal sealed class DefaultArrayPool<T> : ArrayPool<T> { private sealed class Bucket { internal readonly int _bufferLength; private readonly T[][] _buffers; private readonly int _poolId; private SpinLock _lock; private int _index; internal int Id => GetHashCode(); internal Bucket(int bufferLength, int numberOfBuffers, int poolId) { _lock = new SpinLock(Debugger.IsAttached); _buffers = new T[numberOfBuffers][]; _bufferLength = bufferLength; _poolId = poolId; } internal T[] Rent() { T[][] buffers = _buffers; T[] array = null; bool lockTaken = false; bool flag = false; try { _lock.Enter(ref lockTaken); if (_index < buffers.Length) { array = buffers[_index]; buffers[_index++] = null; flag = array == null; } } finally { if (lockTaken) { _lock.Exit(useMemoryBarrier: false); } } if (flag) { array = new T[_bufferLength]; System.Buffers.ArrayPoolEventSource log = System.Buffers.ArrayPoolEventSource.Log; if (log.IsEnabled()) { log.BufferAllocated(array.GetHashCode(), _bufferLength, _poolId, Id, System.Buffers.ArrayPoolEventSource.BufferAllocatedReason.Pooled); } } return array; } internal void Return(T[] array) { if (array.Length != _bufferLength) { throw new ArgumentException(System.SR.ArgumentException_BufferNotFromPool, "array"); } bool lockTaken = false; try { _lock.Enter(ref lockTaken); if (_index != 0) { _buffers[--_index] = array; } } finally { if (lockTaken) { _lock.Exit(useMemoryBarrier: false); } } } } private const int DefaultMaxArrayLength = 1048576; private const int DefaultMaxNumberOfArraysPerBucket = 50; private static T[] s_emptyArray; private readonly Bucket[] _buckets; private int Id => GetHashCode(); internal DefaultArrayPool() : this(1048576, 50) { } internal DefaultArrayPool(int maxArrayLength, int maxArraysPerBucket) { if (maxArrayLength <= 0) { throw new ArgumentOutOfRangeException("maxArrayLength"); } if (maxArraysPerBucket <= 0) { throw new ArgumentOutOfRangeException("maxArraysPerBucket"); } if (maxArrayLength > 1073741824) { maxArrayLength = 1073741824; } else if (maxArrayLength < 16) { maxArrayLength = 16; } int id = Id; int num = System.Buffers.Utilities.SelectBucketIndex(maxArrayLength); Bucket[] array = new Bucket[num + 1]; for (int i = 0; i < array.Length; i++) { array[i] = new Bucket(System.Buffers.Utilities.GetMaxSizeForBucket(i), maxArraysPerBucket, id); } _buckets = array; } public override T[] Rent(int minimumLength) { if (minimumLength < 0) { throw new ArgumentOutOfRangeException("minimumLength"); } if (minimumLength == 0) { return s_emptyArray ?? (s_emptyArray = new T[0]); } System.Buffers.ArrayPoolEventSource log = System.Buffers.ArrayPoolEventSource.Log; T[] array = null; int num = System.Buffers.Utilities.SelectBucketIndex(minimumLength); if (num < _buckets.Length) { int num2 = num; do { array = _buckets[num2].Rent(); if (array != null) { if (log.IsEnabled()) { log.BufferRented(array.GetHashCode(), array.Length, Id, _buckets[num2].Id); } return array; } } while (++num2 < _buckets.Length && num2 != num + 2); array = new T[_buckets[num]._bufferLength]; } else { array = new T[minimumLength]; } if (log.IsEnabled()) { int hashCode = array.GetHashCode(); int bucketId = -1; log.BufferRented(hashCode, array.Length, Id, bucketId); log.BufferAllocated(hashCode, array.Length, Id, bucketId, (num >= _buckets.Length) ? System.Buffers.ArrayPoolEventSource.BufferAllocatedReason.OverMaximumSize : System.Buffers.ArrayPoolEventSource.BufferAllocatedReason.PoolExhausted); } return array; } public override void Return(T[] array, bool clearArray = false) { if (array == null) { throw new ArgumentNullException("array"); } if (array.Length == 0) { return; } int num = System.Buffers.Utilities.SelectBucketIndex(array.Length); if (num < _buckets.Length) { if (clearArray) { Array.Clear(array, 0, array.Length); } _buckets[num].Return(array); } System.Buffers.ArrayPoolEventSource log = System.Buffers.ArrayPoolEventSource.Log; if (log.IsEnabled()) { log.BufferReturned(array.GetHashCode(), array.Length, Id); } } } internal static class Utilities { [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static int SelectBucketIndex(int bufferSize) { uint num = (uint)(bufferSize - 1) >> 4; int num2 = 0; if (num > 65535) { num >>= 16; num2 = 16; } if (num > 255) { num >>= 8; num2 += 8; } if (num > 15) { num >>= 4; num2 += 4; } if (num > 3) { num >>= 2; num2 += 2; } if (num > 1) { num >>= 1; num2++; } return num2 + (int)num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static int GetMaxSizeForBucket(int binIndex) { return 16 << binIndex; } } }
System.Collections.NonGeneric.dll
Decompiled 5 days ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Security; using System.Threading; using FxResources.System.Collections.NonGeneric; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyTitle("System.Collections.NonGeneric")] [assembly: AssemblyDescription("System.Collections.NonGeneric")] [assembly: AssemblyDefaultAlias("System.Collections.NonGeneric")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyProduct("Microsoft® .NET Framework")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyFileVersion("4.6.24705.01")] [assembly: AssemblyInformationalVersion("4.6.24705.01. Commit Hash: 4d1af962ca0fede10beb01d197367c2f90e92c97")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyVersion("4.0.2.0")] namespace FxResources.System.Collections.NonGeneric { internal static class SR { } } namespace System { internal static class SR { private static ResourceManager s_resourceManager; private const string s_resourcesName = "FxResources.System.Collections.NonGeneric.SR"; private static ResourceManager ResourceManager { get { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown if (s_resourceManager == null) { s_resourceManager = new ResourceManager(ResourceType); } return s_resourceManager; } } internal static string Argument_AddingDuplicate__ => GetResourceString("Argument_AddingDuplicate__", null); internal static string Argument_ImplementIComparable => GetResourceString("Argument_ImplementIComparable", null); internal static string Arg_ArrayPlusOffTooSmall => GetResourceString("Arg_ArrayPlusOffTooSmall", null); internal static string Arg_RankMultiDimNotSupported => GetResourceString("Arg_RankMultiDimNotSupported", null); internal static string Arg_HTCapacityOverflow => GetResourceString("Arg_HTCapacityOverflow", null); internal static string Arg_RemoveArgNotFound => GetResourceString("Arg_RemoveArgNotFound", null); internal static string Argument_InvalidOffLen => GetResourceString("Argument_InvalidOffLen", null); internal static string ArgumentNull_Array => GetResourceString("ArgumentNull_Array", null); internal static string ArgumentNull_Collection => GetResourceString("ArgumentNull_Collection", null); internal static string ArgumentNull_Dictionary => GetResourceString("ArgumentNull_Dictionary", null); internal static string ArgumentNull_Key => GetResourceString("ArgumentNull_Key", null); internal static string ArgumentOutOfRange_ArrayListInsert => GetResourceString("ArgumentOutOfRange_ArrayListInsert", null); internal static string ArgumentOutOfRange_BiggerThanCollection => GetResourceString("ArgumentOutOfRange_BiggerThanCollection", null); internal static string ArgumentOutOfRange_Count => GetResourceString("ArgumentOutOfRange_Count", null); internal static string ArgumentOutOfRange_HashtableLoadFactor => GetResourceString("ArgumentOutOfRange_HashtableLoadFactor", null); internal static string ArgumentOutOfRange_Index => GetResourceString("ArgumentOutOfRange_Index", null); internal static string ArgumentOutOfRange_NeedNonNegNum => GetResourceString("ArgumentOutOfRange_NeedNonNegNum", null); internal static string ArgumentOutOfRange_SmallCapacity => GetResourceString("ArgumentOutOfRange_SmallCapacity", null); internal static string ArgumentOutOfRange_QueueGrowFactor => GetResourceString("ArgumentOutOfRange_QueueGrowFactor", null); internal static string ArgumentOutOfRange_MustBeNonNegNum => GetResourceString("ArgumentOutOfRange_MustBeNonNegNum", null); internal static string InvalidOperation_EmptyQueue => GetResourceString("InvalidOperation_EmptyQueue", null); internal static string InvalidOperation_EmptyStack => GetResourceString("InvalidOperation_EmptyStack", null); internal static string InvalidOperation_EnumEnded => GetResourceString("InvalidOperation_EnumEnded", null); internal static string InvalidOperation_EnumFailedVersion => GetResourceString("InvalidOperation_EnumFailedVersion", null); internal static string InvalidOperation_EnumNotStarted => GetResourceString("InvalidOperation_EnumNotStarted", null); internal static string InvalidOperation_EnumOpCantHappen => GetResourceString("InvalidOperation_EnumOpCantHappen", null); internal static string InvalidOperation_UnderlyingArrayListChanged => GetResourceString("InvalidOperation_UnderlyingArrayListChanged", null); internal static string InvalidOperation_HashInsertFailed => GetResourceString("InvalidOperation_HashInsertFailed", null); internal static string NotSupported_FixedSizeCollection => GetResourceString("NotSupported_FixedSizeCollection", null); internal static string NotSupported_KeyCollectionSet => GetResourceString("NotSupported_KeyCollectionSet", null); internal static string NotSupported_ReadOnlyCollection => GetResourceString("NotSupported_ReadOnlyCollection", null); internal static string NotSupported_RangeCollection => GetResourceString("NotSupported_RangeCollection", null); internal static string NotSupported_SortedListNestedWrite => GetResourceString("NotSupported_SortedListNestedWrite", null); internal static System.Type ResourceType => typeof(FxResources.System.Collections.NonGeneric.SR); [MethodImpl(8)] private static bool UsingResourceKeys() { return false; } internal static string GetResourceString(string resourceKey, string defaultString) { string text = null; try { text = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } if (defaultString != null && resourceKey.Equals(text, (StringComparison)4)) { return defaultString; } return text; } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", new object[2] { resourceFormat, p1 }); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", new object[3] { resourceFormat, p1, p2 }); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", new object[4] { resourceFormat, p1, p2, p3 }); } return string.Format(resourceFormat, p1, p2, p3); } } } namespace System.Collections { [DefaultMember("Item")] [DebuggerTypeProxy(typeof(ArrayListDebugView))] [DebuggerDisplay("Count = {Count}")] public class ArrayList : System.Collections.IList, System.Collections.ICollection, System.Collections.IEnumerable { [DefaultMember("Item")] private class IListWrapper : ArrayList { private sealed class IListWrapperEnumWrapper : System.Collections.IEnumerator { private System.Collections.IEnumerator _en; private int _remaining; private int _initialStartIndex; private int _initialCount; private bool _firstCall; public object Current { get { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) if (_firstCall) { throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); } if (_remaining < 0) { throw new InvalidOperationException(SR.InvalidOperation_EnumEnded); } return _en.Current; } } internal IListWrapperEnumWrapper(IListWrapper listWrapper, int startIndex, int count) { _en = listWrapper.GetEnumerator(); _initialStartIndex = startIndex; _initialCount = count; while (startIndex-- > 0 && _en.MoveNext()) { } _remaining = count; _firstCall = true; } public bool MoveNext() { if (_firstCall) { _firstCall = false; if (_remaining-- > 0) { return _en.MoveNext(); } return false; } if (_remaining < 0) { return false; } if (_en.MoveNext()) { return _remaining-- > 0; } return false; } public void Reset() { _en.Reset(); int initialStartIndex = _initialStartIndex; while (initialStartIndex-- > 0 && _en.MoveNext()) { } _remaining = _initialCount; _firstCall = true; } } private System.Collections.IList _list; public override int Capacity { get { return ((System.Collections.ICollection)_list).Count; } set { //IL_0013: Unknown result type (might be due to invalid IL or missing references) if (value < Count) { throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_SmallCapacity); } } } public override int Count => ((System.Collections.ICollection)_list).Count; public override bool IsReadOnly => _list.IsReadOnly; public override bool IsFixedSize => _list.IsFixedSize; public override bool IsSynchronized => ((System.Collections.ICollection)_list).IsSynchronized; public override object this[int index] { get { return _list[index]; } set { _list[index] = value; _version++; } } public override object SyncRoot => ((System.Collections.ICollection)_list).SyncRoot; internal IListWrapper(System.Collections.IList list) { _list = list; _version = 0; } public override int Add(object obj) { int result = _list.Add(obj); _version++; return result; } public override void AddRange(System.Collections.ICollection c) { InsertRange(Count, c); } public override int BinarySearch(int index, int count, object value, IComparer comparer) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (Count - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } if (comparer == null) { comparer = (IComparer)(object)Comparer.Default; } int num = index; int num2 = index + count - 1; while (num <= num2) { int num3 = (num + num2) / 2; int num4 = comparer.Compare(value, _list[num3]); if (num4 == 0) { return num3; } if (num4 < 0) { num2 = num3 - 1; } else { num = num3 + 1; } } return ~num; } public override void Clear() { //IL_0012: Unknown result type (might be due to invalid IL or missing references) if (_list.IsFixedSize) { throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } _list.Clear(); _version++; } public override object Clone() { return new IListWrapper(_list); } public override bool Contains(object obj) { return _list.Contains(obj); } public override void CopyTo(System.Array array, int index) { ((System.Collections.ICollection)_list).CopyTo(array, index); } public override void CopyTo(int index, System.Array array, int arrayIndex, int count) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0070: 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) if (array == null) { throw new ArgumentNullException("array"); } if (index < 0 || arrayIndex < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "arrayIndex", SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - arrayIndex < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, "array"); } if (((System.Collections.ICollection)_list).Count - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } for (int i = index; i < index + count; i++) { array.SetValue(_list[i], arrayIndex++); } } public override System.Collections.IEnumerator GetEnumerator() { return ((System.Collections.IEnumerable)_list).GetEnumerator(); } public override System.Collections.IEnumerator GetEnumerator(int index, int count) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (((System.Collections.ICollection)_list).Count - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return new IListWrapperEnumWrapper(this, index, count); } public override int IndexOf(object value) { return _list.IndexOf(value); } public override int IndexOf(object value, int startIndex) { return IndexOf(value, startIndex, ((System.Collections.ICollection)_list).Count - startIndex); } public override int IndexOf(object value, int startIndex, int count) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) if (startIndex < 0 || startIndex > Count) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } if (count < 0 || startIndex > Count - count) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_Count); } int num = startIndex + count; if (value == null) { for (int i = startIndex; i < num; i++) { if (_list[i] == null) { return i; } } return -1; } for (int j = startIndex; j < num; j++) { if (_list[j] != null && _list[j].Equals(value)) { return j; } } return -1; } public override void Insert(int index, object obj) { _list.Insert(index, obj); _version++; } public override void InsertRange(int index, System.Collections.ICollection c) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) if (c == null) { throw new ArgumentNullException("c", SR.ArgumentNull_Collection); } if (index < 0 || index > Count) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } if (c.Count <= 0) { return; } if (_list is ArrayList arrayList) { arrayList.InsertRange(index, c); } else { System.Collections.IEnumerator enumerator = ((System.Collections.IEnumerable)c).GetEnumerator(); while (enumerator.MoveNext()) { _list.Insert(index++, enumerator.Current); } } _version++; } public override int LastIndexOf(object value) { return LastIndexOf(value, ((System.Collections.ICollection)_list).Count - 1, ((System.Collections.ICollection)_list).Count); } public override int LastIndexOf(object value, int startIndex) { return LastIndexOf(value, startIndex, startIndex + 1); } public override int LastIndexOf(object value, int startIndex, int count) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) if (((System.Collections.ICollection)_list).Count == 0) { return -1; } if (startIndex < 0 || startIndex >= ((System.Collections.ICollection)_list).Count) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } if (count < 0 || count > startIndex + 1) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_Count); } int num = startIndex - count + 1; if (value == null) { for (int num2 = startIndex; num2 >= num; num2--) { if (_list[num2] == null) { return num2; } } return -1; } for (int num3 = startIndex; num3 >= num; num3--) { if (_list[num3] != null && _list[num3].Equals(value)) { return num3; } } return -1; } public override void Remove(object value) { int num = IndexOf(value); if (num >= 0) { RemoveAt(num); } } public override void RemoveAt(int index) { _list.RemoveAt(index); _version++; } public override void RemoveRange(int index, int count) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (((System.Collections.ICollection)_list).Count - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } if (count > 0) { _version++; } while (count > 0) { _list.RemoveAt(index); count--; } } public override void Reverse(int index, int count) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (((System.Collections.ICollection)_list).Count - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } int num = index; int num2 = index + count - 1; while (num < num2) { object obj = _list[num]; _list[num++] = _list[num2]; _list[num2--] = obj; } _version++; } public override void SetRange(int index, System.Collections.ICollection c) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) if (c == null) { throw new ArgumentNullException("c", SR.ArgumentNull_Collection); } if (index < 0 || index > ((System.Collections.ICollection)_list).Count - c.Count) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } if (c.Count > 0) { System.Collections.IEnumerator enumerator = ((System.Collections.IEnumerable)c).GetEnumerator(); while (enumerator.MoveNext()) { _list[index++] = enumerator.Current; } _version++; } } public override ArrayList GetRange(int index, int count) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (((System.Collections.ICollection)_list).Count - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return new Range(this, index, count); } public override void Sort(int index, int count, IComparer comparer) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (((System.Collections.ICollection)_list).Count - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } object[] array = new object[count]; CopyTo(index, array, 0, count); System.Array.Sort((System.Array)array, 0, count, comparer); for (int i = 0; i < count; i++) { _list[i + index] = array[i]; } _version++; } public override object[] ToArray() { if (Count == 0) { return System.Array.Empty<object>(); } object[] array = new object[Count]; ((System.Collections.ICollection)_list).CopyTo((System.Array)array, 0); return array; } [SecuritySafeCritical] public override System.Array ToArray(System.Type type) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (type == null) { throw new ArgumentNullException("type"); } System.Array array = System.Array.CreateInstance(type, ((System.Collections.ICollection)_list).Count); ((System.Collections.ICollection)_list).CopyTo(array, 0); return array; } public override void TrimToSize() { } } [DefaultMember("Item")] private class SyncArrayList : ArrayList { private ArrayList _list; private object _root; public override int Capacity { get { lock (_root) { return _list.Capacity; } } set { lock (_root) { _list.Capacity = value; } } } public override int Count { get { lock (_root) { return _list.Count; } } } public override bool IsReadOnly => _list.IsReadOnly; public override bool IsFixedSize => _list.IsFixedSize; public override bool IsSynchronized => true; public override object this[int index] { get { lock (_root) { return _list[index]; } } set { lock (_root) { _list[index] = value; } } } public override object SyncRoot => _root; internal SyncArrayList(ArrayList list) : base(trash: false) { _list = list; _root = list.SyncRoot; } public override int Add(object value) { lock (_root) { return _list.Add(value); } } public override void AddRange(System.Collections.ICollection c) { lock (_root) { _list.AddRange(c); } } public override int BinarySearch(object value) { lock (_root) { return _list.BinarySearch(value); } } public override int BinarySearch(object value, IComparer comparer) { lock (_root) { return _list.BinarySearch(value, comparer); } } public override int BinarySearch(int index, int count, object value, IComparer comparer) { lock (_root) { return _list.BinarySearch(index, count, value, comparer); } } public override void Clear() { lock (_root) { _list.Clear(); } } public override object Clone() { lock (_root) { return new SyncArrayList((ArrayList)_list.Clone()); } } public override bool Contains(object item) { lock (_root) { return _list.Contains(item); } } public override void CopyTo(System.Array array) { lock (_root) { _list.CopyTo(array); } } public override void CopyTo(System.Array array, int index) { lock (_root) { _list.CopyTo(array, index); } } public override void CopyTo(int index, System.Array array, int arrayIndex, int count) { lock (_root) { _list.CopyTo(index, array, arrayIndex, count); } } public override System.Collections.IEnumerator GetEnumerator() { lock (_root) { return _list.GetEnumerator(); } } public override System.Collections.IEnumerator GetEnumerator(int index, int count) { lock (_root) { return _list.GetEnumerator(index, count); } } public override int IndexOf(object value) { lock (_root) { return _list.IndexOf(value); } } public override int IndexOf(object value, int startIndex) { lock (_root) { return _list.IndexOf(value, startIndex); } } public override int IndexOf(object value, int startIndex, int count) { lock (_root) { return _list.IndexOf(value, startIndex, count); } } public override void Insert(int index, object value) { lock (_root) { _list.Insert(index, value); } } public override void InsertRange(int index, System.Collections.ICollection c) { lock (_root) { _list.InsertRange(index, c); } } public override int LastIndexOf(object value) { lock (_root) { return _list.LastIndexOf(value); } } public override int LastIndexOf(object value, int startIndex) { lock (_root) { return _list.LastIndexOf(value, startIndex); } } public override int LastIndexOf(object value, int startIndex, int count) { lock (_root) { return _list.LastIndexOf(value, startIndex, count); } } public override void Remove(object value) { lock (_root) { _list.Remove(value); } } public override void RemoveAt(int index) { lock (_root) { _list.RemoveAt(index); } } public override void RemoveRange(int index, int count) { lock (_root) { _list.RemoveRange(index, count); } } public override void Reverse(int index, int count) { lock (_root) { _list.Reverse(index, count); } } public override void SetRange(int index, System.Collections.ICollection c) { lock (_root) { _list.SetRange(index, c); } } public override ArrayList GetRange(int index, int count) { lock (_root) { return _list.GetRange(index, count); } } public override void Sort() { lock (_root) { _list.Sort(); } } public override void Sort(IComparer comparer) { lock (_root) { _list.Sort(comparer); } } public override void Sort(int index, int count, IComparer comparer) { lock (_root) { _list.Sort(index, count, comparer); } } public override object[] ToArray() { lock (_root) { return _list.ToArray(); } } public override System.Array ToArray(System.Type type) { lock (_root) { return _list.ToArray(type); } } public override void TrimToSize() { lock (_root) { _list.TrimToSize(); } } } [DefaultMember("Item")] private class SyncIList : System.Collections.IList, System.Collections.ICollection, System.Collections.IEnumerable { private System.Collections.IList _list; private object _root; public virtual int Count { get { lock (_root) { return ((System.Collections.ICollection)_list).Count; } } } public virtual bool IsReadOnly => _list.IsReadOnly; public virtual bool IsFixedSize => _list.IsFixedSize; public virtual bool IsSynchronized => true; public virtual object this[int index] { get { lock (_root) { return _list[index]; } } set { lock (_root) { _list[index] = value; } } } public virtual object SyncRoot => _root; internal SyncIList(System.Collections.IList list) { _list = list; _root = ((System.Collections.ICollection)list).SyncRoot; } public virtual int Add(object value) { lock (_root) { return _list.Add(value); } } public virtual void Clear() { lock (_root) { _list.Clear(); } } public virtual bool Contains(object item) { lock (_root) { return _list.Contains(item); } } public virtual void CopyTo(System.Array array, int index) { lock (_root) { ((System.Collections.ICollection)_list).CopyTo(array, index); } } public virtual System.Collections.IEnumerator GetEnumerator() { lock (_root) { return ((System.Collections.IEnumerable)_list).GetEnumerator(); } } public virtual int IndexOf(object value) { lock (_root) { return _list.IndexOf(value); } } public virtual void Insert(int index, object value) { lock (_root) { _list.Insert(index, value); } } public virtual void Remove(object value) { lock (_root) { _list.Remove(value); } } public virtual void RemoveAt(int index) { lock (_root) { _list.RemoveAt(index); } } } [DefaultMember("Item")] private class FixedSizeList : System.Collections.IList, System.Collections.ICollection, System.Collections.IEnumerable { private System.Collections.IList _list; public virtual int Count => ((System.Collections.ICollection)_list).Count; public virtual bool IsReadOnly => _list.IsReadOnly; public virtual bool IsFixedSize => true; public virtual bool IsSynchronized => ((System.Collections.ICollection)_list).IsSynchronized; public virtual object this[int index] { get { return _list[index]; } set { _list[index] = value; } } public virtual object SyncRoot => ((System.Collections.ICollection)_list).SyncRoot; internal FixedSizeList(System.Collections.IList l) { _list = l; } public virtual int Add(object obj) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } public virtual void Clear() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } public virtual bool Contains(object obj) { return _list.Contains(obj); } public virtual void CopyTo(System.Array array, int index) { ((System.Collections.ICollection)_list).CopyTo(array, index); } public virtual System.Collections.IEnumerator GetEnumerator() { return ((System.Collections.IEnumerable)_list).GetEnumerator(); } public virtual int IndexOf(object value) { return _list.IndexOf(value); } public virtual void Insert(int index, object obj) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } public virtual void Remove(object value) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } public virtual void RemoveAt(int index) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } } [DefaultMember("Item")] private class FixedSizeArrayList : ArrayList { private ArrayList _list; public override int Count => _list.Count; public override bool IsReadOnly => _list.IsReadOnly; public override bool IsFixedSize => true; public override bool IsSynchronized => _list.IsSynchronized; public override object this[int index] { get { return _list[index]; } set { _list[index] = value; _version = _list._version; } } public override object SyncRoot => _list.SyncRoot; public override int Capacity { get { return _list.Capacity; } set { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } } internal FixedSizeArrayList(ArrayList l) { _list = l; _version = _list._version; } public override int Add(object obj) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } public override void AddRange(System.Collections.ICollection c) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } public override int BinarySearch(int index, int count, object value, IComparer comparer) { return _list.BinarySearch(index, count, value, comparer); } public override void Clear() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } public override object Clone() { FixedSizeArrayList fixedSizeArrayList = new FixedSizeArrayList(_list); fixedSizeArrayList._list = (ArrayList)_list.Clone(); return fixedSizeArrayList; } public override bool Contains(object obj) { return _list.Contains(obj); } public override void CopyTo(System.Array array, int index) { _list.CopyTo(array, index); } public override void CopyTo(int index, System.Array array, int arrayIndex, int count) { _list.CopyTo(index, array, arrayIndex, count); } public override System.Collections.IEnumerator GetEnumerator() { return _list.GetEnumerator(); } public override System.Collections.IEnumerator GetEnumerator(int index, int count) { return _list.GetEnumerator(index, count); } public override int IndexOf(object value) { return _list.IndexOf(value); } public override int IndexOf(object value, int startIndex) { return _list.IndexOf(value, startIndex); } public override int IndexOf(object value, int startIndex, int count) { return _list.IndexOf(value, startIndex, count); } public override void Insert(int index, object obj) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } public override void InsertRange(int index, System.Collections.ICollection c) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } public override int LastIndexOf(object value) { return _list.LastIndexOf(value); } public override int LastIndexOf(object value, int startIndex) { return _list.LastIndexOf(value, startIndex); } public override int LastIndexOf(object value, int startIndex, int count) { return _list.LastIndexOf(value, startIndex, count); } public override void Remove(object value) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } public override void RemoveAt(int index) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } public override void RemoveRange(int index, int count) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } public override void SetRange(int index, System.Collections.ICollection c) { _list.SetRange(index, c); _version = _list._version; } public override ArrayList GetRange(int index, int count) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (Count - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return new Range(this, index, count); } public override void Reverse(int index, int count) { _list.Reverse(index, count); _version = _list._version; } public override void Sort(int index, int count, IComparer comparer) { _list.Sort(index, count, comparer); _version = _list._version; } public override object[] ToArray() { return _list.ToArray(); } public override System.Array ToArray(System.Type type) { return _list.ToArray(type); } public override void TrimToSize() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } } [DefaultMember("Item")] private class ReadOnlyList : System.Collections.IList, System.Collections.ICollection, System.Collections.IEnumerable { private System.Collections.IList _list; public virtual int Count => ((System.Collections.ICollection)_list).Count; public virtual bool IsReadOnly => true; public virtual bool IsFixedSize => true; public virtual bool IsSynchronized => ((System.Collections.ICollection)_list).IsSynchronized; public virtual object this[int index] { get { return _list[index]; } set { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } } public virtual object SyncRoot => ((System.Collections.ICollection)_list).SyncRoot; internal ReadOnlyList(System.Collections.IList l) { _list = l; } public virtual int Add(object obj) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public virtual void Clear() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public virtual bool Contains(object obj) { return _list.Contains(obj); } public virtual void CopyTo(System.Array array, int index) { ((System.Collections.ICollection)_list).CopyTo(array, index); } public virtual System.Collections.IEnumerator GetEnumerator() { return ((System.Collections.IEnumerable)_list).GetEnumerator(); } public virtual int IndexOf(object value) { return _list.IndexOf(value); } public virtual void Insert(int index, object obj) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public virtual void Remove(object value) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public virtual void RemoveAt(int index) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } } [DefaultMember("Item")] private class ReadOnlyArrayList : ArrayList { private ArrayList _list; public override int Count => _list.Count; public override bool IsReadOnly => true; public override bool IsFixedSize => true; public override bool IsSynchronized => _list.IsSynchronized; public override object this[int index] { get { return _list[index]; } set { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } } public override object SyncRoot => _list.SyncRoot; public override int Capacity { get { return _list.Capacity; } set { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } } internal ReadOnlyArrayList(ArrayList l) { _list = l; } public override int Add(object obj) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public override void AddRange(System.Collections.ICollection c) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public override int BinarySearch(int index, int count, object value, IComparer comparer) { return _list.BinarySearch(index, count, value, comparer); } public override void Clear() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public override object Clone() { ReadOnlyArrayList readOnlyArrayList = new ReadOnlyArrayList(_list); readOnlyArrayList._list = (ArrayList)_list.Clone(); return readOnlyArrayList; } public override bool Contains(object obj) { return _list.Contains(obj); } public override void CopyTo(System.Array array, int index) { _list.CopyTo(array, index); } public override void CopyTo(int index, System.Array array, int arrayIndex, int count) { _list.CopyTo(index, array, arrayIndex, count); } public override System.Collections.IEnumerator GetEnumerator() { return _list.GetEnumerator(); } public override System.Collections.IEnumerator GetEnumerator(int index, int count) { return _list.GetEnumerator(index, count); } public override int IndexOf(object value) { return _list.IndexOf(value); } public override int IndexOf(object value, int startIndex) { return _list.IndexOf(value, startIndex); } public override int IndexOf(object value, int startIndex, int count) { return _list.IndexOf(value, startIndex, count); } public override void Insert(int index, object obj) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public override void InsertRange(int index, System.Collections.ICollection c) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public override int LastIndexOf(object value) { return _list.LastIndexOf(value); } public override int LastIndexOf(object value, int startIndex) { return _list.LastIndexOf(value, startIndex); } public override int LastIndexOf(object value, int startIndex, int count) { return _list.LastIndexOf(value, startIndex, count); } public override void Remove(object value) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public override void RemoveAt(int index) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public override void RemoveRange(int index, int count) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public override void SetRange(int index, System.Collections.ICollection c) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public override ArrayList GetRange(int index, int count) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (Count - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return new Range(this, index, count); } public override void Reverse(int index, int count) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public override void Sort(int index, int count, IComparer comparer) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public override object[] ToArray() { return _list.ToArray(); } public override System.Array ToArray(System.Type type) { return _list.ToArray(type); } public override void TrimToSize() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } } private sealed class ArrayListEnumerator : System.Collections.IEnumerator { private ArrayList _list; private int _index; private int _endIndex; private int _version; private object _currentElement; private int _startIndex; public object Current { get { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) if (_index < _startIndex) { throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); } if (_index > _endIndex) { throw new InvalidOperationException(SR.InvalidOperation_EnumEnded); } return _currentElement; } } internal ArrayListEnumerator(ArrayList list, int index, int count) { _list = list; _startIndex = index; _index = index - 1; _endIndex = _index + count; _version = list._version; _currentElement = null; } public bool MoveNext() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) if (_version != _list._version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } if (_index < _endIndex) { _currentElement = _list[++_index]; return true; } _index = _endIndex + 1; return false; } public void Reset() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) if (_version != _list._version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } _index = _startIndex - 1; } } [DefaultMember("Item")] private class Range : ArrayList { private ArrayList _baseList; private int _baseIndex; private int _baseSize; private int _baseVersion; public override int Capacity { get { return _baseList.Capacity; } set { //IL_0013: Unknown result type (might be due to invalid IL or missing references) if (value < Count) { throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_SmallCapacity); } } } public override int Count { get { InternalUpdateRange(); return _baseSize; } } public override bool IsReadOnly => _baseList.IsReadOnly; public override bool IsFixedSize => _baseList.IsFixedSize; public override bool IsSynchronized => _baseList.IsSynchronized; public override object SyncRoot => _baseList.SyncRoot; public override object this[int index] { get { //IL_001d: Unknown result type (might be due to invalid IL or missing references) InternalUpdateRange(); if (index < 0 || index >= _baseSize) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } return _baseList[_baseIndex + index]; } set { //IL_001d: Unknown result type (might be due to invalid IL or missing references) InternalUpdateRange(); if (index < 0 || index >= _baseSize) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } _baseList[_baseIndex + index] = value; InternalUpdateVersion(); } } internal Range(ArrayList list, int index, int count) : base(trash: false) { _baseList = list; _baseIndex = index; _baseSize = count; _baseVersion = list._version; _version = list._version; } private void InternalUpdateRange() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) if (_baseVersion != _baseList._version) { throw new InvalidOperationException(SR.InvalidOperation_UnderlyingArrayListChanged); } } private void InternalUpdateVersion() { _baseVersion++; _version++; } public override int Add(object value) { InternalUpdateRange(); _baseList.Insert(_baseIndex + _baseSize, value); InternalUpdateVersion(); return _baseSize++; } public override void AddRange(System.Collections.ICollection c) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (c == null) { throw new ArgumentNullException("c"); } InternalUpdateRange(); int count = c.Count; if (count > 0) { _baseList.InsertRange(_baseIndex + _baseSize, c); InternalUpdateVersion(); _baseSize += count; } } public override int BinarySearch(int index, int count, object value, IComparer comparer) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (_baseSize - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } InternalUpdateRange(); int num = _baseList.BinarySearch(_baseIndex + index, count, value, comparer); if (num >= 0) { return num - _baseIndex; } return num + _baseIndex; } public override void Clear() { InternalUpdateRange(); if (_baseSize != 0) { _baseList.RemoveRange(_baseIndex, _baseSize); InternalUpdateVersion(); _baseSize = 0; } } public override object Clone() { InternalUpdateRange(); Range range = new Range(_baseList, _baseIndex, _baseSize); range._baseList = (ArrayList)_baseList.Clone(); return range; } public override bool Contains(object item) { InternalUpdateRange(); if (item == null) { for (int i = 0; i < _baseSize; i++) { if (_baseList[_baseIndex + i] == null) { return true; } } return false; } for (int j = 0; j < _baseSize; j++) { if (_baseList[_baseIndex + j] != null && _baseList[_baseIndex + j].Equals(item)) { return true; } } return false; } public override void CopyTo(System.Array array, int index) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) if (array == null) { throw new ArgumentNullException("array"); } if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, "array"); } if (index < 0) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < _baseSize) { throw new ArgumentException(SR.Argument_InvalidOffLen); } InternalUpdateRange(); _baseList.CopyTo(_baseIndex, array, index, _baseSize); } public override void CopyTo(int index, System.Array array, int arrayIndex, int count) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) if (array == null) { throw new ArgumentNullException("array"); } if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, "array"); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - arrayIndex < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } if (_baseSize - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } InternalUpdateRange(); _baseList.CopyTo(_baseIndex + index, array, arrayIndex, count); } public override System.Collections.IEnumerator GetEnumerator() { return GetEnumerator(0, _baseSize); } public override System.Collections.IEnumerator GetEnumerator(int index, int count) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (_baseSize - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } InternalUpdateRange(); return _baseList.GetEnumerator(_baseIndex + index, count); } public override ArrayList GetRange(int index, int count) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (_baseSize - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } InternalUpdateRange(); return new Range(this, index, count); } public override int IndexOf(object value) { InternalUpdateRange(); int num = _baseList.IndexOf(value, _baseIndex, _baseSize); if (num >= 0) { return num - _baseIndex; } return -1; } public override int IndexOf(object value, int startIndex) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) if (startIndex < 0) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_NeedNonNegNum); } if (startIndex > _baseSize) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } InternalUpdateRange(); int num = _baseList.IndexOf(value, _baseIndex + startIndex, _baseSize - startIndex); if (num >= 0) { return num - _baseIndex; } return -1; } public override int IndexOf(object value, int startIndex, int count) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) if (startIndex < 0 || startIndex > _baseSize) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } if (count < 0 || startIndex > _baseSize - count) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_Count); } InternalUpdateRange(); int num = _baseList.IndexOf(value, _baseIndex + startIndex, count); if (num >= 0) { return num - _baseIndex; } return -1; } public override void Insert(int index, object value) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || index > _baseSize) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } InternalUpdateRange(); _baseList.Insert(_baseIndex + index, value); InternalUpdateVersion(); _baseSize++; } public override void InsertRange(int index, System.Collections.ICollection c) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || index > _baseSize) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } if (c == null) { throw new ArgumentNullException("c"); } InternalUpdateRange(); int count = c.Count; if (count > 0) { _baseList.InsertRange(_baseIndex + index, c); _baseSize += count; InternalUpdateVersion(); } } public override int LastIndexOf(object value) { InternalUpdateRange(); int num = _baseList.LastIndexOf(value, _baseIndex + _baseSize - 1, _baseSize); if (num >= 0) { return num - _baseIndex; } return -1; } public override int LastIndexOf(object value, int startIndex) { return LastIndexOf(value, startIndex, startIndex + 1); } public override int LastIndexOf(object value, int startIndex, int count) { //IL_0023: 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) InternalUpdateRange(); if (_baseSize == 0) { return -1; } if (startIndex >= _baseSize) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } if (startIndex < 0) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_NeedNonNegNum); } int num = _baseList.LastIndexOf(value, _baseIndex + startIndex, count); if (num >= 0) { return num - _baseIndex; } return -1; } public override void RemoveAt(int index) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || index >= _baseSize) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } InternalUpdateRange(); _baseList.RemoveAt(_baseIndex + index); InternalUpdateVersion(); _baseSize--; } public override void RemoveRange(int index, int count) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (_baseSize - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } InternalUpdateRange(); if (count > 0) { _baseList.RemoveRange(_baseIndex + index, count); InternalUpdateVersion(); _baseSize -= count; } } public override void Reverse(int index, int count) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (_baseSize - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } InternalUpdateRange(); _baseList.Reverse(_baseIndex + index, count); InternalUpdateVersion(); } public override void SetRange(int index, System.Collections.ICollection c) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) InternalUpdateRange(); if (index < 0 || index >= _baseSize) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } _baseList.SetRange(_baseIndex + index, c); if (c.Count > 0) { InternalUpdateVersion(); } } public override void Sort(int index, int count, IComparer comparer) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (_baseSize - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } InternalUpdateRange(); _baseList.Sort(_baseIndex + index, count, comparer); InternalUpdateVersion(); } public override object[] ToArray() { InternalUpdateRange(); if (_baseSize == 0) { return System.Array.Empty<object>(); } object[] array = new object[_baseSize]; System.Array.Copy((System.Array)_baseList._items, _baseIndex, (System.Array)array, 0, _baseSize); return array; } [SecuritySafeCritical] public override System.Array ToArray(System.Type type) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (type == null) { throw new ArgumentNullException("type"); } InternalUpdateRange(); System.Array array = System.Array.CreateInstance(type, _baseSize); _baseList.CopyTo(_baseIndex, array, 0, _baseSize); return array; } public override void TrimToSize() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(SR.NotSupported_RangeCollection); } } private sealed class ArrayListEnumeratorSimple : System.Collections.IEnumerator { private ArrayList _list; private int _index; private int _version; private object _currentElement; private bool _isArrayList; private static object s_dummyObject = new object(); public object Current { get { //IL_0028: 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) object currentElement = _currentElement; if (s_dummyObject == currentElement) { if (_index == -1) { throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); } throw new InvalidOperationException(SR.InvalidOperation_EnumEnded); } return currentElement; } } internal ArrayListEnumeratorSimple(ArrayList list) { _list = list; _index = -1; _version = list._version; _isArrayList = ((object)list).GetType() == typeof(ArrayList); _currentElement = s_dummyObject; } public bool MoveNext() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) if (_version != _list._version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } if (_isArrayList) { if (_index < _list._size - 1) { _currentElement = _list._items[++_index]; return true; } _currentElement = s_dummyObject; _index = _list._size; return false; } if (_index < _list.Count - 1) { _currentElement = _list[++_index]; return true; } _index = _list.Count; _currentElement = s_dummyObject; return false; } public void Reset() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) if (_version != _list._version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } _currentElement = s_dummyObject; _index = -1; } } internal class ArrayListDebugView { private ArrayList _arrayList; [DebuggerBrowsable(/*Could not decode attribute arguments.*/)] public object[] Items => _arrayList.ToArray(); public ArrayListDebugView(ArrayList arrayList) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) if (arrayList == null) { throw new ArgumentNullException("arrayList"); } _arrayList = arrayList; } } private object[] _items; private int _size; private int _version; private object _syncRoot; private const int _defaultCapacity = 4; internal const int MaxArrayLength = 2146435071; public virtual int Capacity { get { return _items.Length; } set { //IL_0013: Unknown result type (might be due to invalid IL or missing references) if (value < _size) { throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_SmallCapacity); } if (value == _items.Length) { return; } if (value > 0) { object[] array = new object[value]; if (_size > 0) { System.Array.Copy((System.Array)_items, 0, (System.Array)array, 0, _size); } _items = array; } else { _items = new object[4]; } } } public virtual int Count => _size; public virtual bool IsFixedSize => false; public virtual bool IsReadOnly => false; public virtual bool IsSynchronized => false; public virtual object SyncRoot { get { if (_syncRoot == null) { Interlocked.CompareExchange<object>(ref _syncRoot, new object(), (object)null); } return _syncRoot; } } public virtual object this[int index] { get { //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || index >= _size) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } return _items[index]; } set { //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || index >= _size) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } _items[index] = value; _version++; } } internal ArrayList(bool trash) { } public ArrayList() { _items = System.Array.Empty<object>(); } public ArrayList(int capacity) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) if (capacity < 0) { throw new ArgumentOutOfRangeException("capacity", SR.Format(SR.ArgumentOutOfRange_MustBeNonNegNum, "capacity")); } if (capacity == 0) { _items = System.Array.Empty<object>(); } else { _items = new object[capacity]; } } public ArrayList(System.Collections.ICollection c) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) if (c == null) { throw new ArgumentNullException("c", SR.ArgumentNull_Collection); } int count = c.Count; if (count == 0) { _items = System.Array.Empty<object>(); return; } _items = new object[count]; AddRange(c); } public static ArrayList Adapter(System.Collections.IList list) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (list == null) { throw new ArgumentNullException("list"); } return new IListWrapper(list); } public virtual int Add(object value) { if (_size == _items.Length) { EnsureCapacity(_size + 1); } _items[_size] = value; _version++; return _size++; } public virtual void AddRange(System.Collections.ICollection c) { InsertRange(_size, c); } public virtual int BinarySearch(int index, int count, object value, IComparer comparer) { //IL_000e: 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_0038: Unknown result type (might be due to invalid IL or missing references) if (index < 0) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return System.Array.BinarySearch((System.Array)_items, index, count, value, comparer); } public virtual int BinarySearch(object value) { return BinarySearch(0, Count, value, null); } public virtual int BinarySearch(object value, IComparer comparer) { return BinarySearch(0, Count, value, comparer); } public virtual void Clear() { if (_size > 0) { System.Array.Clear((System.Array)_items, 0, _size); _size = 0; } _version++; } public virtual object Clone() { ArrayList arrayList = new ArrayList(_size); arrayList._size = _size; arrayList._version = _version; System.Array.Copy((System.Array)_items, 0, (System.Array)arrayList._items, 0, _size); return arrayList; } public virtual bool Contains(object item) { if (item == null) { for (int i = 0; i < _size; i++) { if (_items[i] == null) { return true; } } return false; } for (int j = 0; j < _size; j++) { if (_items[j] != null && _items[j].Equals(item)) { return true; } } return false; } public virtual void CopyTo(System.Array array) { CopyTo(array, 0); } public virtual void CopyTo(System.Array array, int arrayIndex) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) if (array != null && array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, "array"); } System.Array.Copy((System.Array)_items, 0, array, arrayIndex, _size); } public virtual void CopyTo(int index, System.Array array, int arrayIndex, int count) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) if (_size - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } if (array != null && array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, "array"); } System.Array.Copy((System.Array)_items, index, array, arrayIndex, count); } private void EnsureCapacity(int min) { if (_items.Length < min) { int num = ((_items.Length == 0) ? 4 : (_items.Length * 2)); if ((uint)num > 2146435071u) { num = 2146435071; } if (num < min) { num = min; } Capacity = num; } } public static System.Collections.IList FixedSize(System.Collections.IList list) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (list == null) { throw new ArgumentNullException("list"); } return new FixedSizeList(list); } public static ArrayList FixedSize(ArrayList list) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (list == null) { throw new ArgumentNullException("list"); } return new FixedSizeArrayList(list); } public virtual System.Collections.IEnumerator GetEnumerator() { return new ArrayListEnumeratorSimple(this); } public virtual System.Collections.IEnumerator GetEnumerator(int index, int count) { //IL_000e: 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_0038: Unknown result type (might be due to invalid IL or missing references) if (index < 0) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return new ArrayListEnumerator(this, index, count); } public virtual int IndexOf(object value) { return System.Array.IndexOf((System.Array)_items, value, 0, _size); } public virtual int IndexOf(object value, int startIndex) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) if (startIndex > _size) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } return System.Array.IndexOf((System.Array)_items, value, startIndex, _size - startIndex); } public virtual int IndexOf(object value, int startIndex, int count) { //IL_0013: 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) if (startIndex > _size) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } if (count < 0 || startIndex > _size - count) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_Count); } return System.Array.IndexOf((System.Array)_items, value, startIndex, count); } public virtual void Insert(int index, object value) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || index > _size) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_ArrayListInsert); } if (_size == _items.Length) { EnsureCapacity(_size + 1); } if (index < _size) { System.Array.Copy((System.Array)_items, index, (System.Array)_items, index + 1, _size - index); } _items[index] = value; _size++; _version++; } public virtual void InsertRange(int index, System.Collections.ICollection c) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) if (c == null) { throw new ArgumentNullException("c", SR.ArgumentNull_Collection); } if (index < 0 || index > _size) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } int count = c.Count; if (count > 0) { EnsureCapacity(_size + count); if (index < _size) { System.Array.Copy((System.Array)_items, index, (System.Array)_items, index + count, _size - index); } object[] array = new object[count]; c.CopyTo((System.Array)array, 0); ((System.Array)array).CopyTo((System.Array)_items, index); _size += count; _version++; } } public virtual int LastIndexOf(object value) { return LastIndexOf(value, _size - 1, _size); } public virtual int LastIndexOf(object value, int startIndex) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) if (startIndex >= _size) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } return LastIndexOf(value, startIndex, startIndex + 1); } public virtual int LastIndexOf(object value, int startIndex, int count) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) if (Count != 0 && (startIndex < 0 || count < 0)) { throw new ArgumentOutOfRangeException((startIndex < 0) ? "startIndex" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (_size == 0) { return -1; } if (startIndex >= _size || count > startIndex + 1) { throw new ArgumentOutOfRangeException((startIndex >= _size) ? "startIndex" : "count", SR.ArgumentOutOfRange_BiggerThanCollection); } return System.Array.LastIndexOf((System.Array)_items, value, startIndex, count); } public static System.Collections.IList ReadOnly(System.Collections.IList list) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (list == null) { throw new ArgumentNullException("list"); } return new ReadOnlyList(list); } public static ArrayList ReadOnly(ArrayList list) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (list == null) { throw new ArgumentNullException("list"); } return new ReadOnlyArrayList(list); } public virtual void Remove(object obj) { int num = IndexOf(obj); if (num >= 0) { RemoveAt(num); } } public virtual void RemoveAt(int index) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || index >= _size) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } _size--; if (index < _size) { System.Array.Copy((System.Array)_items, index + 1, (System.Array)_items, index, _size - index); } _items[_size] = null; _version++; } public virtual void RemoveRange(int index, int count) { //IL_000e: 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_0038: Unknown result type (might be due to invalid IL or missing references) if (index < 0) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } if (count > 0) { int num = _size; _size -= count; if (index < _size) { System.Array.Copy((System.Array)_items, index + count, (System.Array)_items, index, _size - index); } while (num > _size) { _items[--num] = null; } _version++; } } public static ArrayList Repeat(object value, int count) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } ArrayList arrayList = new ArrayList((count > 4) ? count : 4); for (int i = 0; i < count; i++) { arrayList.Add(value); } return arrayList; } public virtual void Reverse() { Reverse(0, Count); } public virtual void Reverse(int index, int count) { //IL_000e: 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_0038: Unknown result type (might be due to invalid IL or missing references) if (index < 0) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } System.Array.Reverse((System.Array)_items, index, count); _version++; } public virtual void SetRange(int index, System.Collections.ICollection c) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) if (c == null) { throw new ArgumentNullException("c", SR.ArgumentNull_Collection); } int count = c.Count; if (index < 0 || index > _size - count) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } if (count > 0) { c.CopyTo((System.Array)_items, index); _version++; } } public virtual ArrayList GetRange(int index, int count) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return new Range(this, index, count); } public virtual void Sort() { Sort(0, Count, (IComparer)(object)Comparer.Default); } public virtual void Sort(IComparer comparer) { Sort(0, Count, comparer); } public virtual void Sort(int index, int count, IComparer comparer) { //IL_000e: 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_0038: Unknown result type (might be due to invalid IL or missing references) if (index < 0) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } System.Array.Sort((System.Array)_items, index, count, comparer); _version++; } public static System.Collections.IList Synchronized(System.Collections.IList list) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (list == null) { throw new ArgumentNullException("list"); } return new SyncIList(list); } public static ArrayList Synchronized(ArrayList list) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (list == null) { throw new ArgumentNullException("list"); } return new SyncArrayList(list); } public virtual object[] ToArray() { if (_size == 0) { return System.Array.Empty<object>(); } object[] array = new object[_size]; System.Array.Copy((System.Array)_items, 0, (System.Array)array, 0, _size); return array; } [SecuritySafeCritical] public virtual System.Array ToArray(System.Type type) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (type == null) { throw new ArgumentNullException("type"); } System.Array array = System.Array.CreateInstance(type, _size); System.Array.Copy((System.Array)_items, 0, array, 0, _size); return array; } public virtual void TrimToSize() { Capacity = _size; } } public class CaseInsensitiveComparer : IComparer { private CompareInfo _compareInfo; private static volatile CaseInsensitiveComparer s_InvariantCaseInsensitiveComparer; public static CaseInsensitiveComparer Default => new CaseInsensitiveComparer(CultureInfo.CurrentCulture); public static CaseInsensitiveComparer DefaultInvariant { get { if (s_InvariantCaseInsensitiveComparer == null) { s_InvariantCaseInsensitiveComparer = new CaseInsensitiveComparer(CultureInfo.InvariantCulture); } return s_InvariantCaseInsensitiveComparer; } } public CaseInsensitiveComparer() { _compareInfo = CultureInfo.CurrentCulture.CompareInfo; } public CaseInsensitiveComparer(CultureInfo culture) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) if (culture == null) { throw new ArgumentNullException("culture"); } _compareInfo = culture.CompareInfo; } public int Compare(object a, object b) { string text = a as string; string text2 = b as string; if (text != null && text2 != null) { return _compareInfo.Compare(text, text2, (CompareOptions)1); } return Comparer.Default.Compare(a, b); } } public abstract class CollectionBase : System.Collections.IList, System.Collections.ICollection, System.Collections.IEnumerable { private ArrayList _list; protected ArrayList InnerList => _list; protected System.Collections.IList List => this; public int Capacity { get { return InnerList.Capacity; } set { InnerList.Capacity = value; } } public int Count => _list.Count; bool System.Collections.IList.IsReadOnly => InnerList.IsReadOnly; bool System.Collections.IList.IsFixedSize => InnerList.IsFixedSize; bool System.Collections.ICollection.IsSynchronized => InnerList.IsSynchronized; object System.Collections.ICollection.SyncRoot => InnerList.SyncRoot; object System.Collections.IList.this[int index] { get { //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || index >= Count) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } return InnerList[index]; } set { //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || index >= Count) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } OnValidate(value); object obj = InnerList[index]; OnSet(index, obj, value); InnerList[index] = value; try { OnSetComplete(index, obj, value); } catch { InnerList[index] = obj; throw; } } } protected CollectionBase() { _list = new ArrayList(); } protected CollectionBase(int capacity) { _list = new ArrayList(capacity); } public void Clear() { OnClear(); InnerList.Clear(); OnClearComplete(); } public void RemoveAt(int index) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || index >= Count) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } object value = InnerList[index]; OnValidate(value); OnRemove(index, value); InnerList.RemoveAt(index); try { OnRemoveComplete(index, value); } catch { InnerList.Insert(index, value); throw; } } void System.Collections.ICollection.CopyTo(System.Array array, int index) { InnerList.CopyTo(array, index); } bool System.Collections.IList.Contains(object value) { return InnerList.Contains(value); } int System.Collections.IList.Add(object value) { OnValidate(value); OnInsert(InnerList.Count, value); int num = InnerList.Add(value); try { OnInsertComplete(num, value); return num; } catch { InnerList.RemoveAt(num); throw; } } void System.Collections.IList.Remove(object value) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) OnValidate(value); int num = InnerList.IndexOf(value); if (num < 0) { throw new ArgumentException(SR.Arg_RemoveArgNotFound); } OnRemove(num, value); InnerList.RemoveAt(num); try { OnRemoveComplete(num, value); } catch { InnerList.Insert(num, value); throw; } } int System.Collections.IList.IndexOf(object value) { return InnerList.IndexOf(value); } void System.Collections.IList.Insert(int index, object value) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || index > Count) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } OnValidate(value); OnInsert(index, value); InnerList.Insert(index, value); try { OnInsertComplete(index, value); } catch { InnerList.RemoveAt(index); throw; } } public System.Collections.IEnumerator GetEnumerator() { return InnerList.GetEnumerator(); } protected virtual void OnSet(int index, object oldValue, object newValue) { } protected virtual void OnInsert(int index, object value) { } protected virtual void OnClear() { } protected virtual void OnRemove(int index, object value) { } protected virtual void OnValidate(object value) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (value == null) { throw new ArgumentNullException("value"); } } protected virtual void OnSetComplete(int index, object oldValue, object newValue) { } protected virtual void OnInsertComplete(int index, object value) { } protected virtual void OnClearComplete() { } protected virtual void OnRemoveComplete(int index, object value) { } } public sealed class Comparer : IComparer { private CompareInfo _compareInfo; public static readonly Comparer Default = new Comparer(CultureInfo.CurrentCulture); public static readonly Comparer DefaultInvariant = new Comparer(CultureInfo.InvariantCulture); private const string CompareInfoName = "CompareInfo"; public Comparer(CultureInfo culture) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) if (culture == null) { throw new ArgumentNullException("culture"); } _compareInfo = culture.CompareInfo; } public int Compare(object a, object b) { //IL_005c: Unknown result type (might be due to invalid IL or missing references) if (a == b) { return 0; } if (a == null) { return -1; } if (b == null) { return 1; } string text = a as string; string text2 = b as string; if (text != null && text2 != null) { return _compareInfo.Compare(text, text2); } IComparable val = (IComparable)((a is IComparable) ? a : null); if (val != null) { return val.CompareTo(b); } IComparable val2 = (IComparable)((b is IComparable) ? b : null); if (val2 != null) { return -val2.CompareTo(a); } throw new ArgumentException(SR.Argument_ImplementIComparable); } } public abstract class DictionaryBase : IDictionary, System.Collections.ICollection, System.Collections.IEnumerable { private Hashtable _hashtable; protected Hashtable InnerHashtable { get { if (_hashtable == null) { _hashtable = new Hashtable(); } return _hashtable; } } protected IDictionary Dictionary => (IDictionary)(object)this; public int Count { get { if (_hashtable != null) { return _hashtable.Count; } return 0; } } bool IDictionary.IsReadOnly => InnerHashtable.IsReadOnly; bool IDictionary.IsFixedSize => InnerHashtable.IsFixedSize; bool System.Collections.ICollection.IsSynchronized => InnerHashtable.IsSynchronized; System.Collections.ICollection IDictionary.Keys => InnerHashtable.Keys; object System.Collections.ICollection.SyncRoot => InnerHashtable.SyncRoot; System.Collections.ICollection IDictionary.Values => InnerHashtable.Values; object IDictionary.this[object key] { get { object obj = InnerHashtable[key]; OnGet(key, obj); return obj; } set { OnValidate(key, value); bool flag = true; object obj = InnerHashtable[key]; if (obj == null) { flag = InnerHashtable.Contains(key); } OnSet(key, obj, value); InnerHashtable[key] = value; try { OnSetComplete(key, obj, value); } catch { if (flag) { InnerHashtable[key] = obj; } else { InnerHashtable.Remove(key); } throw; } } } public void CopyTo(System.Array array, int index) { InnerHashtable.CopyTo(array, index); } bool IDictionary.Contains(object key) { return InnerHashtable.Contains(key); } void IDictionary.Add(object key, object value) { OnValidate(key, value); OnInsert(key, value); InnerHashtable.Add(key, value); try { OnInsertComplete(key, value); } catch { InnerHashtable.Remove(key); throw; } } public void Clear() { OnClear(); InnerHashtable.Clear(); OnClearComplete(); } void IDictionary.Remove(object key) { if (InnerHashtable.Contains(key)) { object value = InnerHashtable[key]; OnValidate(key, value); OnRemove(key, value); InnerHashtable.Remove(key); try { OnRemoveComplete(key, value); } catch { InnerHashtable.Add(key, value); throw; } } } public IDictionaryEnumerator GetEnumerator() { return InnerHashtable.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)InnerHashtable.GetEnumerator(); } protected virtual object OnGet(object key, object currentValue) { return currentValue; } protected virtual void OnSet(object key, object oldValue, object newValue) { } protected virtual void OnInsert(object key, object value) { } protected virtual void OnClear() { } protected virtual void OnRemove(object key, object value) { } protected virtual void OnValidate(object key, object value) { } protected virtual void OnSetComplete(object key, object oldValue, object newValue) { } protected virtual void OnInsertComplete(object key, object value) { } protected virtual void OnClearComplete() { } protected virtual void OnRemoveComplete(object key, object value) { } } [DefaultMember("Item")] [DebuggerTypeProxy(typeof(HashtableDebugView))] [DebuggerDisplay("Count = {Count}")] public class Hashtable : IDictionary, System.Collections.ICollection, System.Collections.IEnumerable { private struct bucket { public object key; public object val; public int hash_coll; } private class KeyCollection : System.Collections.ICollection, System.Collections.IEnumerable { private Hashtable _hashtable; public virtual bool IsSynchronized => _hashtable.IsSynchronized; public virtual object SyncRoot => _hashtable.SyncRoot; public virtual int Count => _hashtable._count; internal KeyCollection(Hashtable hashtable) { _hashtable = hashtable; } public virtual void CopyTo(System.Array array, int arrayIndex) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) if (array == null) { throw new ArgumentNullException("array"); } if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, "array"); } if (arrayIndex < 0) { throw new ArgumentOutOfRangeException("arrayIndex", SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - arrayIndex < _hashtable._count) { throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); } _hashtable.CopyKeys(array, arrayIndex); } public virtual System.Collections.IEnumerator GetEnumerator() { return new HashtableEnumerator(_hashtable, 1); } } private class ValueCollection : System.Collections.ICollection, System.Collections.IEnumerable { private Hashtable _hashtable; public virtual bool IsSynchronized => _hashtable.IsSynchronized; public virtual object SyncRoot => _hashtable.SyncRoot; public virtual int Count => _hashtable._count; internal ValueCollection(Hashtable hashtable) { _hashtable = hashtable; } public virtual void CopyTo(System.Array array, int arrayIndex) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) if (array == null) { throw new ArgumentNullException("array"); } if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, "array"); } if (arrayIndex < 0) { throw new ArgumentOutOfRangeException("arrayIndex", SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - arrayIndex < _hashtable._count) { throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); } _hashtable.CopyValues(array, arrayIndex); } public virtual System.Collections.IEnumerator GetEnumerator() { return new HashtableEnumerator(_hashtable, 2); } } [DefaultMember("Item")] private class SyncHashtable : Hashtable, System.Collections.IEnumerable { protected Hashtable _table; public override int Count => _table.Count; public override bool IsReadOnly => _table.IsReadOnly; public override bool IsFixedSize => _table.IsFixedSize; public override bool IsSynchronized => true; public override object this[object key] { get { return _table[key]; } set { lock (_table.SyncRoot) { _table[key] = value; } } } public override object SyncRoot => _table.SyncRoot; public override System.Collections.ICollection Keys { get { lock (_table.SyncRoot) { return _table.Keys; } } } public override System.Collections.ICollection Values { get { lock (_table.SyncRoot) { return _table.Values; } } } internal SyncHashtable(Hashtable table) : base(trash: false) { _table = table; } public override void Add(object key, object value) { lock (_table.SyncRoot) { _table.Add(key, value); } } public override void Clear() { lock (_table.SyncRoot) { _table.Clear(); } } public override bool Contains(object key) { return _table.Contains(key); } public override bool ContainsKey(object key) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (key == null) { throw new ArgumentNullException("key", SR.ArgumentNull_Key); } return _table.ContainsKey(key); } public override bool ContainsValue(object key) { lock (_table.SyncRoot) { return _table.ContainsValue(key); } } public override void CopyTo(System.Array array, int arrayIndex) { lock (_table.SyncRoot) { _table.CopyTo(array, arrayIndex); } } public override object Clone() { lock (_table.SyncRoot) { return Synchronized((Hashtable)_table.Clone()); } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)_table.GetEnumerator(); } public override IDictionaryEnumerator GetEnumerator() { return _table.GetEnumerator(); } public override void Remove(object key) { lock (_table.SyncRoot) { _table.Remove(key); } } internal override KeyValuePairs[] ToKeyValuePairsArray() { return _table.ToKeyValuePairsArray(); } } private class HashtableEnumerator : IDictionaryEnumerator, System.Collections.IEnumerator { private Hashtable _hashtable; private int _bucket; private int _version; private bool _current; private int _getObjectRetType; private object _currentKey; private object _currentValue; internal const int Keys = 1; internal const int Values = 2; internal const int DictEntry = 3; public virtual object Key { get { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (!_current) { throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); } return _currentKey; } } public virtual DictionaryEntry Entry { get { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (!_current) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return new DictionaryEntry(_currentKey, _currentValue); } } public virtual object Current { get { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) if (!_current) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } if (_getObjectRetType == 1) { return _currentKey; } if (_getObjectRetType == 2) { return _currentValue; } return (object)new DictionaryEntry(_currentKey, _currentValue); } } public virtual object Value { get { //IL_000d: Unknown result type (might be due to invalid IL or missing references) i
System.Collections.Specialized.dll
Decompiled 5 days agousing System; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using FxResources.System.Collections.Specialized; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyTitle("System.Collections.Specialized")] [assembly: AssemblyDescription("System.Collections.Specialized")] [assembly: AssemblyDefaultAlias("System.Collections.Specialized")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyProduct("Microsoft® .NET Framework")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyFileVersion("4.6.24705.01")] [assembly: AssemblyInformationalVersion("4.6.24705.01. Commit Hash: 4d1af962ca0fede10beb01d197367c2f90e92c97")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyVersion("4.0.2.0")] namespace FxResources.System.Collections.Specialized { internal static class SR { } } namespace System { internal static class SR { private static ResourceManager s_resourceManager; private const string s_resourcesName = "FxResources.System.Collections.Specialized.SR"; private static ResourceManager ResourceManager { get { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown if (s_resourceManager == null) { s_resourceManager = new ResourceManager(ResourceType); } return s_resourceManager; } } internal static string Argument_AddingDuplicate => GetResourceString("Argument_AddingDuplicate", null); internal static string Argument_InvalidValue => GetResourceString("Argument_InvalidValue", null); internal static string ArgumentOutOfRange_NeedNonNegNum => GetResourceString("ArgumentOutOfRange_NeedNonNegNum", null); internal static string InvalidOperation_EnumFailedVersion => GetResourceString("InvalidOperation_EnumFailedVersion", null); internal static string InvalidOperation_EnumOpCantHappen => GetResourceString("InvalidOperation_EnumOpCantHappen", null); internal static string Arg_MultiRank => GetResourceString("Arg_MultiRank", null); internal static string Arg_NonZeroLowerBound => GetResourceString("Arg_NonZeroLowerBound", null); internal static string Arg_InsufficientSpace => GetResourceString("Arg_InsufficientSpace", null); internal static string CollectionReadOnly => GetResourceString("CollectionReadOnly", null); internal static string BitVectorFull => GetResourceString("BitVectorFull", null); internal static string OrderedDictionary_ReadOnly => GetResourceString("OrderedDictionary_ReadOnly", null); internal static System.Type ResourceType => typeof(SR); [MethodImpl(8)] private static bool UsingResourceKeys() { return false; } internal static string GetResourceString(string resourceKey, string defaultString) { string text = null; try { text = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } if (defaultString != null && resourceKey.Equals(text, (StringComparison)4)) { return defaultString; } return text; } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", new object[2] { resourceFormat, p1 }); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", new object[3] { resourceFormat, p1, p2 }); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", new object[4] { resourceFormat, p1, p2, p3 }); } return string.Format(resourceFormat, p1, p2, p3); } } } namespace System.Collections.Specialized { [DefaultMember("Item")] public struct BitVector32 { public struct Section { private readonly short _mask; private readonly short _offset; public short Mask => _mask; public short Offset => _offset; internal Section(short mask, short offset) { _mask = mask; _offset = offset; } public bool Equals(object o) { if (o is Section) { return Equals((Section)o); } return false; } public bool Equals(Section obj) { if (obj._mask == _mask) { return obj._offset == _offset; } return false; } public static bool operator ==(Section a, Section b) { return a.Equals(b); } public static bool operator !=(Section a, Section b) { return !(a == b); } public int GetHashCode() { return base.GetHashCode(); } public static string ToString(Section value) { return string.Concat(new string[5] { "Section{0x", Convert.ToString(value.Mask, 16), ", 0x", Convert.ToString(value.Offset, 16), "}" }); } public string ToString() { return ToString(this); } } private uint _data; public bool this[int bit] { get { return (_data & bit) == (uint)bit; } set { if (value) { _data |= (uint)bit; } else { _data &= (uint)(~bit); } } } public int this[Section section] { get { return (int)((_data & (uint)(section.Mask << (int)section.Offset)) >> (int)section.Offset); } set { value <<= (int)section.Offset; int num = (0xFFFF & section.Mask) << (int)section.Offset; _data = (_data & (uint)(~num)) | (uint)(value & num); } } public int Data => (int)_data; public BitVector32(int data) { _data = (uint)data; } public BitVector32(BitVector32 value) { _data = value._data; } private static short CountBitsSet(short mask) { short num = 0; while (((uint)mask & (true ? 1u : 0u)) != 0) { num++; mask >>= 1; } return num; } public static int CreateMask() { return CreateMask(0); } public static int CreateMask(int previous) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) return previous switch { 0 => 1, -2147483648 => throw new InvalidOperationException(System.SR.BitVectorFull), _ => previous << 1, }; } private static short CreateMaskFromHighValue(short highValue) { short num = 16; while ((highValue & 0x8000) == 0) { num--; highValue <<= 1; } ushort num2 = 0; while (num > 0) { num--; num2 <<= 1; num2 = (ushort)(num2 | 1u); } return (short)num2; } public static Section CreateSection(short maxValue) { return CreateSectionHelper(maxValue, 0, 0); } public static Section CreateSection(short maxValue, Section previous) { return CreateSectionHelper(maxValue, previous.Mask, previous.Offset); } private static Section CreateSectionHelper(short maxValue, short priorMask, short priorOffset) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) if (maxValue < 1) { throw new ArgumentException(System.SR.Format(System.SR.Argument_InvalidValue, "maxValue", 1), "maxValue"); } short num = (short)(priorOffset + CountBitsSet(priorMask)); if (num >= 32) { throw new InvalidOperationException(System.SR.BitVectorFull); } return new Section(CreateMaskFromHighValue(maxValue), num); } public bool Equals(object o) { if (!(o is BitVector32)) { return false; } return _data == ((BitVector32)o)._data; } public int GetHashCode() { return base.GetHashCode(); } public static string ToString(BitVector32 value) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown StringBuilder val = new StringBuilder(45); val.Append("BitVector32{"); int num = (int)value._data; for (int i = 0; i < 32; i++) { if ((num & 0x80000000u) != 0L) { val.Append('1'); } else { val.Append('0'); } num <<= 1; } val.Append('}'); return ((object)val).ToString(); } public string ToString() { return ToString(this); } } [DefaultMember("Item")] public class HybridDictionary : IDictionary, System.Collections.ICollection, System.Collections.IEnumerable { private const int CutoverPoint = 9; private const int InitialHashtableSize = 13; private const int FixedSizeCutoverPoint = 6; private ListDictionary _list; private Hashtable _hashtable; private readonly bool _caseInsensitive; public object this[object key] { get { //IL_002f: Unknown result type (might be due to invalid IL or missing references) ListDictionary list = _list; if (_hashtable != null) { return _hashtable[key]; } if (list != null) { return list[key]; } if (key == null) { throw new ArgumentNullException("key"); } return null; } set { if (_hashtable != null) { _hashtable[key] = value; } else if (_list != null) { if (_list.Count >= 8) { ChangeOver(); _hashtable[key] = value; } else { _list[key] = value; } } else { _list = new ListDictionary((IComparer)(object)(_caseInsensitive ? StringComparer.OrdinalIgnoreCase : null)); _list[key] = value; } } } private ListDictionary List { get { if (_list == null) { _list = new ListDictionary((IComparer)(object)(_caseInsensitive ? StringComparer.OrdinalIgnoreCase : null)); } return _list; } } public int Count { get { ListDictionary list = _list; if (_hashtable != null) { return _hashtable.Count; } return list?.Count ?? 0; } } public System.Collections.ICollection Keys { get { if (_hashtable != null) { return _hashtable.Keys; } return List.Keys; } } public bool IsReadOnly => false; public bool IsFixedSize => false; public bool IsSynchronized => false; public object SyncRoot => this; public System.Collections.ICollection Values { get { if (_hashtable != null) { return _hashtable.Values; } return List.Values; } } public HybridDictionary() { } public HybridDictionary(int initialSize) : this(initialSize, caseInsensitive: false) { } public HybridDictionary(bool caseInsensitive) { _caseInsensitive = caseInsensitive; } public HybridDictionary(int initialSize, bool caseInsensitive) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Expected O, but got Unknown //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Expected O, but got Unknown _caseInsensitive = caseInsensitive; if (initialSize >= 6) { if (caseInsensitive) { _hashtable = new Hashtable(initialSize, (IEqualityComparer)(object)StringComparer.OrdinalIgnoreCase); } else { _hashtable = new Hashtable(initialSize); } } } private void ChangeOver() { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected O, but got Unknown //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown IDictionaryEnumerator enumerator = _list.GetEnumerator(); Hashtable val = ((!_caseInsensitive) ? new Hashtable(13) : new Hashtable(13, (IEqualityComparer)(object)StringComparer.OrdinalIgnoreCase)); while (((System.Collections.IEnumerator)enumerator).MoveNext()) { val.Add(enumerator.Key, enumerator.Value); } _hashtable = val; _list = null; } public void Add(object key, object value) { if (_hashtable != null) { _hashtable.Add(key, value); } else if (_list == null) { _list = new ListDictionary((IComparer)(object)(_caseInsensitive ? StringComparer.OrdinalIgnoreCase : null)); _list.Add(key, value); } else if (_list.Count + 1 >= 9) { ChangeOver(); _hashtable.Add(key, value); } else { _list.Add(key, value); } } public void Clear() { if (_hashtable != null) { Hashtable hashtable = _hashtable; _hashtable = null; hashtable.Clear(); } if (_list != null) { ListDictionary list = _list; _list = null; list.Clear(); } } public bool Contains(object key) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) ListDictionary list = _list; if (_hashtable != null) { return _hashtable.Contains(key); } if (list != null) { return list.Contains(key); } if (key == null) { throw new ArgumentNullException("key"); } return false; } public void CopyTo(System.Array array, int index) { if (_hashtable != null) { _hashtable.CopyTo(array, index); } else { List.CopyTo(array, index); } } public IDictionaryEnumerator GetEnumerator() { if (_hashtable != null) { return _hashtable.GetEnumerator(); } if (_list == null) { _list = new ListDictionary((IComparer)(object)(_caseInsensitive ? StringComparer.OrdinalIgnoreCase : null)); } return _list.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { if (_hashtable != null) { return (System.Collections.IEnumerator)_hashtable.GetEnumerator(); } if (_list == null) { _list = new ListDictionary((IComparer)(object)(_caseInsensitive ? StringComparer.OrdinalIgnoreCase : null)); } return (System.Collections.IEnumerator)_list.GetEnumerator(); } public void Remove(object key) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) if (_hashtable != null) { _hashtable.Remove(key); } else if (_list != null) { _list.Remove(key); } else if (key == null) { throw new ArgumentNullException("key"); } } } [DefaultMember("Item")] public interface IOrderedDictionary : IDictionary, System.Collections.ICollection, System.Collections.IEnumerable { object this[int index] { get; set; } IDictionaryEnumerator GetEnumerator(); void Insert(int index, object key, object value); void RemoveAt(int index); } [DefaultMember("Item")] public class ListDictionary : IDictionary, System.Collections.ICollection, System.Collections.IEnumerable { private class NodeEnumerator : IDictionaryEnumerator, System.Collections.IEnumerator { private ListDictionary _list; private DictionaryNode _current; private int _version; private bool _start; public object Current => Entry; public DictionaryEntry Entry { get { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (_current == null) { throw new InvalidOperationException(System.SR.InvalidOperation_EnumOpCantHappen); } return new DictionaryEntry(_current.key, _current.value); } } public object Key { get { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (_current == null) { throw new InvalidOperationException(System.SR.InvalidOperation_EnumOpCantHappen); } return _current.key; } } public object Value { get { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (_current == null) { throw new InvalidOperationException(System.SR.InvalidOperation_EnumOpCantHappen); } return _current.value; } } public NodeEnumerator(ListDictionary list) { _list = list; _version = list._version; _start = true; _current = null; } public bool MoveNext() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) if (_version != _list._version) { throw new InvalidOperationException(System.SR.InvalidOperation_EnumFailedVersion); } if (_start) { _current = _list._head; _start = false; } else if (_current != null) { _current = _current.next; } return _current != null; } public void Reset() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) if (_version != _list._version) { throw new InvalidOperationException(System.SR.InvalidOperation_EnumFailedVersion); } _start = true; _current = null; } } private class NodeKeyValueCollection : System.Collections.ICollection, System.Collections.IEnumerable { private class NodeKeyValueEnumerator : System.Collections.IEnumerator { private ListDictionary _list; private DictionaryNode _current; private int _version; private bool _isKeys; private bool _start; public object Current { get { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (_current == null) { throw new InvalidOperationException(System.SR.InvalidOperation_EnumOpCantHappen); } if (!_isKeys) { return _current.value; } return _current.key; } } public NodeKeyValueEnumerator(ListDictionary list, bool isKeys) { _list = list; _isKeys = isKeys; _version = list._version; _start = true; _current = null; } public bool MoveNext() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) if (_version != _list._version) { throw new InvalidOperationException(System.SR.InvalidOperation_EnumFailedVersion); } if (_start) { _current = _list._head; _start = false; } else if (_current != null) { _current = _current.next; } return _current != null; } public void Reset() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) if (_version != _list._version) { throw new InvalidOperationException(System.SR.InvalidOperation_EnumFailedVersion); } _start = true; _current = null; } } private ListDictionary _list; private bool _isKeys; int System.Collections.ICollection.Count { get { int num = 0; for (DictionaryNode dictionaryNode = _list._head; dictionaryNode != null; dictionaryNode = dictionaryNode.next) { num++; } return num; } } bool System.Collections.ICollection.IsSynchronized => false; object System.Collections.ICollection.SyncRoot => _list.SyncRoot; public NodeKeyValueCollection(ListDictionary list, bool isKeys) { _list = list; _isKeys = isKeys; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) if (array == null) { throw new ArgumentNullException("array"); } if (index < 0) { throw new ArgumentOutOfRangeException("index", (object)index, System.SR.ArgumentOutOfRange_NeedNonNegNum); } for (DictionaryNode dictionaryNode = _list._head; dictionaryNode != null; dictionaryNode = dictionaryNode.next) { array.SetValue(_isKeys ? dictionaryNode.key : dictionaryNode.value, index); index++; } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new NodeKeyValueEnumerator(_list, _isKeys); } } private class DictionaryNode { public object key; public object value; public DictionaryNode next; } private DictionaryNode _head; private int _version; private int _count; private readonly IComparer _comparer; private object _syncRoot; public object this[object key] { get { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (key == null) { throw new ArgumentNullException("key"); } DictionaryNode dictionaryNode = _head; if (_comparer == null) { while (dictionaryNode != null) { object key2 = dictionaryNode.key; if (key2.Equals(key)) { return dictionaryNode.value; } dictionaryNode = dictionaryNode.next; } } else { while (dictionaryNode != null) { object key3 = dictionaryNode.key; if (_comparer.Compare(key3, key) == 0) { return dictionaryNode.value; } dictionaryNode = dictionaryNode.next; } } return null; } set { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (key == null) { throw new ArgumentNullException("key"); } _version++; DictionaryNode dictionaryNode = null; DictionaryNode dictionaryNode2; for (dictionaryNode2 = _head; dictionaryNode2 != null; dictionaryNode2 = dictionaryNode2.next) { object key2 = dictionaryNode2.key; if ((_comparer == null) ? key2.Equals(key) : (_comparer.Compare(key2, key) == 0)) { break; } dictionaryNode = dictionaryNode2; } if (dictionaryNode2 != null) { dictionaryNode2.value = value; return; } DictionaryNode dictionaryNode3 = new DictionaryNode(); dictionaryNode3.key = key; dictionaryNode3.value = value; if (dictionaryNode != null) { dictionaryNode.next = dictionaryNode3; } else { _head = dictionaryNode3; } _count++; } } public int Count => _count; public System.Collections.ICollection Keys => new NodeKeyValueCollection(this, isKeys: true); public bool IsReadOnly => false; public bool IsFixedSize => false; public bool IsSynchronized => false; public object SyncRoot { get { if (_syncRoot == null) { Interlocked.CompareExchange(ref _syncRoot, new object(), (object)null); } return _syncRoot; } } public System.Collections.ICollection Values => new NodeKeyValueCollection(this, isKeys: false); public ListDictionary() { } public ListDictionary(IComparer comparer) { _comparer = comparer; } public void Add(object key, object value) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) if (key == null) { throw new ArgumentNullException("key"); } _version++; DictionaryNode dictionaryNode = null; for (DictionaryNode dictionaryNode2 = _head; dictionaryNode2 != null; dictionaryNode2 = dictionaryNode2.next) { object key2 = dictionaryNode2.key; if ((_comparer == null) ? key2.Equals(key) : (_comparer.Compare(key2, key) == 0)) { throw new ArgumentException(System.SR.Format(System.SR.Argument_AddingDuplicate, key)); } dictionaryNode = dictionaryNode2; } DictionaryNode dictionaryNode3 = new DictionaryNode(); dictionaryNode3.key = key; dictionaryNode3.value = value; if (dictionaryNode != null) { dictionaryNode.next = dictionaryNode3; } else { _head = dictionaryNode3; } _count++; } public void Clear() { _count = 0; _head = null; _version++; } public bool Contains(object key) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (key == null) { throw new ArgumentNullException("key"); } for (DictionaryNode dictionaryNode = _head; dictionaryNode != null; dictionaryNode = dictionaryNode.next) { object key2 = dictionaryNode.key; if ((_comparer == null) ? key2.Equals(key) : (_comparer.Compare(key2, key) == 0)) { return true; } } return false; } public void CopyTo(System.Array array, int index) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) if (array == null) { throw new ArgumentNullException("array"); } if (index < 0) { throw new ArgumentOutOfRangeException("index", (object)index, System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < _count) { throw new ArgumentException(System.SR.Arg_InsufficientSpace); } for (DictionaryNode dictionaryNode = _head; dictionaryNode != null; dictionaryNode = dictionaryNode.next) { array.SetValue((object)new DictionaryEntry(dictionaryNode.key, dictionaryNode.value), index); index++; } } public IDictionaryEnumerator GetEnumerator() { return (IDictionaryEnumerator)(object)new NodeEnumerator(this); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new NodeEnumerator(this); } public void Remove(object key) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (key == null) { throw new ArgumentNullException("key"); } _version++; DictionaryNode dictionaryNode = null; DictionaryNode dictionaryNode2; for (dictionaryNode2 = _head; dictionaryNode2 != null; dictionaryNode2 = dictionaryNode2.next) { object key2 = dictionaryNode2.key; if ((_comparer == null) ? key2.Equals(key) : (_comparer.Compare(key2, key) == 0)) { break; } dictionaryNode = dictionaryNode2; } if (dictionaryNode2 != null) { if (dictionaryNode2 == _head) { _head = dictionaryNode2.next; } else { dictionaryNode.next = dictionaryNode2.next; } _count--; } } } public abstract class NameObjectCollectionBase : System.Collections.ICollection, System.Collections.IEnumerable { internal class NameObjectEntry { internal string Key; internal object Value; internal NameObjectEntry(string name, object value) { Key = name; Value = value; } } internal class NameObjectKeysEnumerator : System.Collections.IEnumerator { private int _pos; private NameObjectCollectionBase _coll; private int _version; public object Current { get { //IL_0033: Unknown result type (might be due to invalid IL or missing references) if (_pos >= 0 && _pos < _coll.Count) { return _coll.BaseGetKey(_pos); } throw new InvalidOperationException(System.SR.InvalidOperation_EnumOpCantHappen); } } internal NameObjectKeysEnumerator(NameObjectCollectionBase coll) { _coll = coll; _version = _coll._version; _pos = -1; } public bool MoveNext() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) if (_version != _coll._version) { throw new InvalidOperationException(System.SR.InvalidOperation_EnumFailedVersion); } if (_pos < _coll.Count - 1) { _pos++; return true; } _pos = _coll.Count; return false; } public void Reset() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) if (_version != _coll._version) { throw new InvalidOperationException(System.SR.InvalidOperation_EnumFailedVersion); } _pos = -1; } } [DefaultMember("Item")] public class KeysCollection : System.Collections.ICollection, System.Collections.IEnumerable { private NameObjectCollectionBase _coll; public string this[int index] => Get(index); public int Count => _coll.Count; object System.Collections.ICollection.SyncRoot => ((System.Collections.ICollection)_coll).SyncRoot; bool System.Collections.ICollection.IsSynchronized => false; internal KeysCollection(NameObjectCollectionBase coll) { _coll = coll; } public virtual string Get(int index) { return _coll.BaseGetKey(index); } public System.Collections.IEnumerator GetEnumerator() { return new NameObjectKeysEnumerator(_coll); } void System.Collections.ICollection.CopyTo(System.Array array, int index) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0021: 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_005b: Unknown result type (might be due to invalid IL or missing references) if (array == null) { throw new ArgumentNullException("array"); } if (array.Rank != 1) { throw new ArgumentException(System.SR.Arg_MultiRank, "array"); } if (index < 0) { throw new ArgumentOutOfRangeException("index", (object)index, System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < _coll.Count) { throw new ArgumentException(System.SR.Arg_InsufficientSpace); } System.Collections.IEnumerator enumerator = GetEnumerator(); while (enumerator.MoveNext()) { array.SetValue(enumerator.Current, index++); } } } private bool _readOnly; private ArrayList _entriesArray; private IEqualityComparer _keyComparer; private volatile Hashtable _entriesTable; private volatile NameObjectEntry _nullKeyEntry; private KeysCollection _keys; private int _version; private object _syncRoot; private static readonly StringComparer s_defaultComparer = GlobalizationExtensions.GetStringComparer(CultureInfo.InvariantCulture.CompareInfo, (CompareOptions)1); internal IEqualityComparer Comparer { get { return _keyComparer; } set { _keyComparer = value; } } protected bool IsReadOnly { get { return _readOnly; } set { _readOnly = value; } } public virtual int Count => _entriesArray.Count; object System.Collections.ICollection.SyncRoot { get { if (_syncRoot == null) { Interlocked.CompareExchange(ref _syncRoot, new object(), (object)null); } return _syncRoot; } } bool System.Collections.ICollection.IsSynchronized => false; public virtual KeysCollection Keys { get { if (_keys == null) { _keys = new KeysCollection(this); } return _keys; } } protected NameObjectCollectionBase() : this((IEqualityComparer)(object)s_defaultComparer) { } protected NameObjectCollectionBase(IEqualityComparer equalityComparer) { IEqualityComparer keyComparer; if (equalityComparer != null) { keyComparer = equalityComparer; } else { IEqualityComparer val = (IEqualityComparer)(object)s_defaultComparer; keyComparer = val; } _keyComparer = keyComparer; Reset(); } protected NameObjectCollectionBase(int capacity, IEqualityComparer equalityComparer) : this(equalityComparer) { Reset(capacity); } protected NameObjectCollectionBase(int capacity) { _keyComparer = (IEqualityComparer)(object)s_defaultComparer; Reset(capacity); } private void Reset() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown _entriesArray = new ArrayList(); _entriesTable = new Hashtable(_keyComparer); _nullKeyEntry = null; _version++; } private void Reset(int capacity) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Expected O, but got Unknown _entriesArray = new ArrayList(capacity); _entriesTable = new Hashtable(capacity, _keyComparer); _nullKeyEntry = null; _version++; } private NameObjectEntry FindEntry(string key) { if (key != null) { return (NameObjectEntry)_entriesTable[(object)key]; } return _nullKeyEntry; } protected bool BaseHasKeys() { return _entriesTable.Count > 0; } protected void BaseAdd(string name, object value) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(System.SR.CollectionReadOnly); } NameObjectEntry nameObjectEntry = new NameObjectEntry(name, value); if (name != null) { if (_entriesTable[(object)name] == null) { _entriesTable.Add((object)name, (object)nameObjectEntry); } } else if (_nullKeyEntry == null) { _nullKeyEntry = nameObjectEntry; } _entriesArray.Add((object)nameObjectEntry); _version++; } protected void BaseRemove(string name) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(System.SR.CollectionReadOnly); } if (name != null) { _entriesTable.Remove((object)name); for (int num = _entriesArray.Count - 1; num >= 0; num--) { if (_keyComparer.Equals((object)name, (object)BaseGetKey(num))) { _entriesArray.RemoveAt(num); } } } else { _nullKeyEntry = null; for (int num2 = _entriesArray.Count - 1; num2 >= 0; num2--) { if (BaseGetKey(num2) == null) { _entriesArray.RemoveAt(num2); } } } _version++; } protected void BaseRemoveAt(int index) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(System.SR.CollectionReadOnly); } string text = BaseGetKey(index); if (text != null) { _entriesTable.Remove((object)text); } else { _nullKeyEntry = null; } _entriesArray.RemoveAt(index); _version++; } protected void BaseClear() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(System.SR.CollectionReadOnly); } Reset(); } protected object BaseGet(string name) { return FindEntry(name)?.Value; } protected void BaseSet(string name, object value) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(System.SR.CollectionReadOnly); } NameObjectEntry nameObjectEntry = FindEntry(name); if (nameObjectEntry != null) { nameObjectEntry.Value = value; _version++; } else { BaseAdd(name, value); } } protected object BaseGet(int index) { NameObjectEntry nameObjectEntry = (NameObjectEntry)_entriesArray[index]; return nameObjectEntry.Value; } protected string BaseGetKey(int index) { NameObjectEntry nameObjectEntry = (NameObjectEntry)_entriesArray[index]; return nameObjectEntry.Key; } protected void BaseSet(int index, object value) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(System.SR.CollectionReadOnly); } NameObjectEntry nameObjectEntry = (NameObjectEntry)_entriesArray[index]; nameObjectEntry.Value = value; _version++; } public virtual System.Collections.IEnumerator GetEnumerator() { return new NameObjectKeysEnumerator(this); } void System.Collections.ICollection.CopyTo(System.Array array, int index) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0021: 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_005b: Unknown result type (might be due to invalid IL or missing references) if (array == null) { throw new ArgumentNullException("array"); } if (array.Rank != 1) { throw new ArgumentException(System.SR.Arg_MultiRank, "array"); } if (index < 0) { throw new ArgumentOutOfRangeException("index", (object)index, System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < _entriesArray.Count) { throw new ArgumentException(System.SR.Arg_InsufficientSpace); } System.Collections.IEnumerator enumerator = GetEnumerator(); while (enumerator.MoveNext()) { array.SetValue(enumerator.Current, index++); } } protected string[] BaseGetAllKeys() { int count = _entriesArray.Count; string[] array = new string[count]; for (int i = 0; i < count; i++) { array[i] = BaseGetKey(i); } return array; } protected object[] BaseGetAllValues() { int count = _entriesArray.Count; object[] array = new object[count]; for (int i = 0; i < count; i++) { array[i] = BaseGet(i); } return array; } protected object[] BaseGetAllValues(System.Type type) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) int count = _entriesArray.Count; if (type == null) { throw new ArgumentNullException("type"); } object[] array = (object[])System.Array.CreateInstance(type, count); for (int i = 0; i < count; i++) { array[i] = BaseGet(i); } return array; } } [DefaultMember("Item")] public class NameValueCollection : NameObjectCollectionBase { private string[] _all; private string[] _allKeys; public string this[string name] { get { return Get(name); } set { Set(name, value); } } public string this[int index] => Get(index); public virtual string[] AllKeys { get { if (_allKeys == null) { _allKeys = BaseGetAllKeys(); } return _allKeys; } } public NameValueCollection() { } public NameValueCollection(NameValueCollection col) : base(col?.Comparer) { Add(col); } public NameValueCollection(int capacity) : base(capacity) { } public NameValueCollection(IEqualityComparer equalityComparer) : base(equalityComparer) { } public NameValueCollection(int capacity, IEqualityComparer equalityComparer) : base(capacity, equalityComparer) { } public NameValueCollection(int capacity, NameValueCollection col) : base(capacity, col?.Comparer) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) if (col == null) { throw new ArgumentNullException("col"); } base.Comparer = col.Comparer; Add(col); } protected void InvalidateCachedArrays() { _all = null; _allKeys = null; } private static string GetAsOneString(ArrayList list) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown int num = ((list != null) ? list.Count : 0); if (num == 1) { return (string)list[0]; } if (num > 1) { StringBuilder val = new StringBuilder((string)list[0]); for (int i = 1; i < num; i++) { val.Append(','); val.Append((string)list[i]); } return ((object)val).ToString(); } return null; } private static string[] GetAsStringArray(ArrayList list) { int num = ((list != null) ? list.Count : 0); if (num == 0) { return null; } string[] array = new string[num]; list.CopyTo(0, (System.Array)array, 0, num); return array; } public void Add(NameValueCollection c) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (c == null) { throw new ArgumentNullException("c"); } InvalidateCachedArrays(); int count = c.Count; for (int i = 0; i < count; i++) { string key = c.GetKey(i); string[] values = c.GetValues(i); if (values != null) { for (int j = 0; j < values.Length; j++) { Add(key, values[j]); } } else { Add(key, null); } } } public virtual void Clear() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (base.IsReadOnly) { throw new NotSupportedException(System.SR.CollectionReadOnly); } InvalidateCachedArrays(); BaseClear(); } public void CopyTo(System.Array dest, int index) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) if (dest == null) { throw new ArgumentNullException("dest"); } if (dest.Rank != 1) { throw new ArgumentException(System.SR.Arg_MultiRank, "dest"); } if (index < 0) { throw new ArgumentOutOfRangeException("index", (object)index, System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (dest.Length - index < Count) { throw new ArgumentException(System.SR.Arg_InsufficientSpace); } int count = Count; if (_all == null) { string[] array = new string[count]; for (int i = 0; i < count; i++) { array[i] = Get(i); dest.SetValue((object)array[i], i + index); } _all = array; } else { for (int j = 0; j < count; j++) { dest.SetValue((object)_all[j], j + index); } } } public bool HasKeys() { return InternalHasKeys(); } internal virtual bool InternalHasKeys() { return BaseHasKeys(); } public virtual void Add(string name, string value) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown if (base.IsReadOnly) { throw new NotSupportedException(System.SR.CollectionReadOnly); } InvalidateCachedArrays(); ArrayList val = (ArrayList)BaseGet(name); if (val == null) { val = new ArrayList(1); if (value != null) { val.Add((object)value); } BaseAdd(name, val); } else if (value != null) { val.Add((object)value); } } public virtual string Get(string name) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown ArrayList list = (ArrayList)BaseGet(name); return GetAsOneString(list); } public virtual string[] GetValues(string name) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown ArrayList list = (ArrayList)BaseGet(name); return GetAsStringArray(list); } public virtual void Set(string name, string value) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Expected O, but got Unknown //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (base.IsReadOnly) { throw new NotSupportedException(System.SR.CollectionReadOnly); } InvalidateCachedArrays(); ArrayList val = new ArrayList(1); val.Add((object)value); BaseSet(name, val); } public virtual void Remove(string name) { InvalidateCachedArrays(); BaseRemove(name); } public virtual string Get(int index) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown ArrayList list = (ArrayList)BaseGet(index); return GetAsOneString(list); } public virtual string[] GetValues(int index) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown ArrayList list = (ArrayList)BaseGet(index); return GetAsStringArray(list); } public virtual string GetKey(int index) { return BaseGetKey(index); } } [DefaultMember("Item")] public class OrderedDictionary : IOrderedDictionary, IDictionary, System.Collections.ICollection, System.Collections.IEnumerable { private class OrderedDictionaryEnumerator : IDictionaryEnumerator, System.Collections.IEnumerator { private int _objectReturnType; internal const int Keys = 1; internal const int Values = 2; internal const int DictionaryEntry = 3; private System.Collections.IEnumerator _arrayEnumerator; public object Current { get { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) DictionaryEntry val; if (_objectReturnType == 1) { val = (DictionaryEntry)_arrayEnumerator.Current; return ((DictionaryEntry)(ref val)).Key; } if (_objectReturnType == 2) { val = (DictionaryEntry)_arrayEnumerator.Current; return ((DictionaryEntry)(ref val)).Value; } return Entry; } } public DictionaryEntry Entry { get { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0023: 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) DictionaryEntry val = (DictionaryEntry)_arrayEnumerator.Current; object key = ((DictionaryEntry)(ref val)).Key; val = (DictionaryEntry)_arrayEnumerator.Current; return new DictionaryEntry(key, ((DictionaryEntry)(ref val)).Value); } } public object Key { get { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) DictionaryEntry val = (DictionaryEntry)_arrayEnumerator.Current; return ((DictionaryEntry)(ref val)).Key; } } public object Value { get { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) DictionaryEntry val = (DictionaryEntry)_arrayEnumerator.Current; return ((DictionaryEntry)(ref val)).Value; } } internal OrderedDictionaryEnumerator(ArrayList array, int objectReturnType) { _arrayEnumerator = array.GetEnumerator(); _objectReturnType = objectReturnType; } public bool MoveNext() { return _arrayEnumerator.MoveNext(); } public void Reset() { _arrayEnumerator.Reset(); } } private class OrderedDictionaryKeyValueCollection : System.Collections.ICollection, System.Collections.IEnumerable { private ArrayList _objects; private bool _isKeys; int System.Collections.ICollection.Count => _objects.Count; bool System.Collections.ICollection.IsSynchronized => false; object System.Collections.ICollection.SyncRoot => _objects.SyncRoot; public OrderedDictionaryKeyValueCollection(ArrayList array, bool isKeys) { _objects = array; _isKeys = isKeys; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) if (array == null) { throw new ArgumentNullException("array"); } if (index < 0) { throw new ArgumentOutOfRangeException("index", (object)index, System.SR.ArgumentOutOfRange_NeedNonNegNum); } foreach (object @object in _objects) { DictionaryEntry val; object obj; if (!_isKeys) { val = (DictionaryEntry)@object; obj = ((DictionaryEntry)(ref val)).Value; } else { val = (DictionaryEntry)@object; obj = ((DictionaryEntry)(ref val)).Key; } array.SetValue(obj, index); index++; } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new OrderedDictionaryEnumerator(_objects, _isKeys ? 1 : 2); } } private ArrayList _objectsArray; private Hashtable _objectsTable; private readonly int _initialCapacity; private readonly IEqualityComparer _comparer; private readonly bool _readOnly; private object _syncRoot; public int Count => objectsArray.Count; bool IDictionary.IsFixedSize => _readOnly; public bool IsReadOnly => _readOnly; bool System.Collections.ICollection.IsSynchronized => false; public System.Collections.ICollection Keys => new OrderedDictionaryKeyValueCollection(objectsArray, isKeys: true); private ArrayList objectsArray { get { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Expected O, but got Unknown if (_objectsArray == null) { _objectsArray = new ArrayList(_initialCapacity); } return _objectsArray; } } private Hashtable objectsTable { get { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected O, but got Unknown if (_objectsTable == null) { _objectsTable = new Hashtable(_initialCapacity, _comparer); } return _objectsTable; } } object System.Collections.ICollection.SyncRoot { get { if (_syncRoot == null) { Interlocked.CompareExchange(ref _syncRoot, new object(), (object)null); } return _syncRoot; } } public object this[int index] { get { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) DictionaryEntry val = (DictionaryEntry)objectsArray[index]; return ((DictionaryEntry)(ref val)).Value; } set { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(System.SR.OrderedDictionary_ReadOnly); } if (index < 0 || index >= objectsArray.Count) { throw new ArgumentOutOfRangeException("index"); } DictionaryEntry val = (DictionaryEntry)objectsArray[index]; object key = ((DictionaryEntry)(ref val)).Key; objectsArray[index] = (object)new DictionaryEntry(key, value); objectsTable[key] = value; } } public object this[object key] { get { return objectsTable[key]; } set { //IL_000d: 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) if (_readOnly) { throw new NotSupportedException(System.SR.OrderedDictionary_ReadOnly); } if (objectsTable.Contains(key)) { objectsTable[key] = value; objectsArray[IndexOfKey(key)] = (object)new DictionaryEntry(key, value); } else { Add(key, value); } } } public System.Collections.ICollection Values => new OrderedDictionaryKeyValueCollection(objectsArray, isKeys: false); public OrderedDictionary() : this(0) { } public OrderedDictionary(int capacity) : this(capacity, null) { } public OrderedDictionary(IEqualityComparer comparer) : this(0, comparer) { } public OrderedDictionary(int capacity, IEqualityComparer comparer) { _initialCapacity = capacity; _comparer = comparer; } private OrderedDictionary(OrderedDictionary dictionary) { _readOnly = true; _objectsArray = dictionary._objectsArray; _objectsTable = dictionary._objectsTable; _comparer = dictionary._comparer; _initialCapacity = dictionary._initialCapacity; } public void Add(object key, object value) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(System.SR.OrderedDictionary_ReadOnly); } objectsTable.Add(key, value); objectsArray.Add((object)new DictionaryEntry(key, value)); } public void Clear() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(System.SR.OrderedDictionary_ReadOnly); } objectsTable.Clear(); objectsArray.Clear(); } public OrderedDictionary AsReadOnly() { return new OrderedDictionary(this); } public bool Contains(object key) { return objectsTable.Contains(key); } public void CopyTo(System.Array array, int index) { objectsTable.CopyTo(array, index); } private int IndexOfKey(object key) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < objectsArray.Count; i++) { DictionaryEntry val = (DictionaryEntry)objectsArray[i]; object key2 = ((DictionaryEntry)(ref val)).Key; if (_comparer != null) { if (_comparer.Equals(key2, key)) { return i; } } else if (key2.Equals(key)) { return i; } } return -1; } public void Insert(int index, object key, object value) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(System.SR.OrderedDictionary_ReadOnly); } if (index > Count || index < 0) { throw new ArgumentOutOfRangeException("index"); } objectsTable.Add(key, value); objectsArray.Insert(index, (object)new DictionaryEntry(key, value)); } public void RemoveAt(int index) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(System.SR.OrderedDictionary_ReadOnly); } if (index >= Count || index < 0) { throw new ArgumentOutOfRangeException("index"); } DictionaryEntry val = (DictionaryEntry)objectsArray[index]; object key = ((DictionaryEntry)(ref val)).Key; objectsArray.RemoveAt(index); objectsTable.Remove(key); } public void Remove(object key) { //IL_000d: 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) if (_readOnly) { throw new NotSupportedException(System.SR.OrderedDictionary_ReadOnly); } if (key == null) { throw new ArgumentNullException("key"); } int num = IndexOfKey(key); if (num >= 0) { objectsTable.Remove(key); objectsArray.RemoveAt(num); } } public virtual IDictionaryEnumerator GetEnumerator() { return (IDictionaryEnumerator)(object)new OrderedDictionaryEnumerator(objectsArray, 3); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new OrderedDictionaryEnumerator(objectsArray, 3); } } [DefaultMember("Item")] public class StringCollection : System.Collections.IList, System.Collections.ICollection, System.Collections.IEnumerable { private readonly ArrayList _data = new ArrayList(); public string this[int index] { get { return (string)_data[index]; } set { _data[index] = value; } } public int Count => _data.Count; bool System.Collections.IList.IsReadOnly => false; bool System.Collections.IList.IsFixedSize => false; public bool IsReadOnly => false; public bool IsSynchronized => false; public object SyncRoot => _data.SyncRoot; object System.Collections.IList.this[int index] { get { return this[index]; } set { this[index] = (string)value; } } public int Add(string value) { return _data.Add((object)value); } public void AddRange(string[] value) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (value == null) { throw new ArgumentNullException("value"); } _data.AddRange((System.Collections.ICollection)(object)value); } public void Clear() { _data.Clear(); } public bool Contains(string value) { return _data.Contains((object)value); } public void CopyTo(string[] array, int index) { _data.CopyTo((System.Array)array, index); } public StringEnumerator GetEnumerator() { return new StringEnumerator(this); } public int IndexOf(string value) { return _data.IndexOf((object)value); } public void Insert(int index, string value) { _data.Insert(index, (object)value); } public void Remove(string value) { _data.Remove((object)value); } public void RemoveAt(int index) { _data.RemoveAt(index); } int System.Collections.IList.Add(object value) { return Add((string)value); } bool System.Collections.IList.Contains(object value) { return Contains((string)value); } int System.Collections.IList.IndexOf(object value) { return IndexOf((string)value); } void System.Collections.IList.Insert(int index, object value) { Insert(index, (string)value); } void System.Collections.IList.Remove(object value) { Remove((string)value); } void System.Collections.ICollection.CopyTo(System.Array array, int index) { _data.CopyTo(array, index); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return _data.GetEnumerator(); } } public class StringEnumerator { private System.Collections.IEnumerator _baseEnumerator; private System.Collections.IEnumerable _temp; public string Current => (string)_baseEnumerator.Current; internal StringEnumerator(StringCollection mappings) { _temp = mappings; _baseEnumerator = _temp.GetEnumerator(); } public bool MoveNext() { return _baseEnumerator.MoveNext(); } public void Reset() { _baseEnumerator.Reset(); } } [DefaultMember("Item")] public class StringDictionary : System.Collections.IEnumerable { private readonly Hashtable _contents = new Hashtable(); public virtual int Count => _contents.Count; public virtual bool IsSynchronized => _contents.IsSynchronized; public virtual string this[string key] { get { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (key == null) { throw new ArgumentNullException("key"); } return (string)_contents[(object)key.ToLowerInvariant()]; } set { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (key == null) { throw new ArgumentNullException("key"); } _contents[(object)key.ToLowerInvariant()] = value; } } public virtual System.Collections.ICollection Keys => _contents.Keys; public virtual object SyncRoot => _contents.SyncRoot; public virtual System.Collections.ICollection Values => _contents.Values; public virtual void Add(string key, string value) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (key == null) { throw new ArgumentNullException("key"); } _contents.Add((object)key.ToLowerInvariant(), (object)value); } public virtual void Clear() { _contents.Clear(); } public virtual bool ContainsKey(string key) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (key == null) { throw new ArgumentNullException("key"); } return _contents.ContainsKey((object)key.ToLowerInvariant()); } public virtual bool ContainsValue(string value) { return _contents.ContainsValue((object)value); } public virtual void CopyTo(System.Array array, int index) { _contents.CopyTo(array, index); } public virtual System.Collections.IEnumerator GetEnumerator() { return (System.Collections.IEnumerator)_contents.GetEnumerator(); } public virtual void Remove(string key) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (key == null) { throw new ArgumentNullException("key"); } _contents.Remove((object)key.ToLowerInvariant()); } } }
System.ComponentModel.dll
Decompiled 5 days agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: AssemblyTitle("System.ComponentModel")] [assembly: AssemblyDescription("System.ComponentModel")] [assembly: AssemblyDefaultAlias("System.ComponentModel")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyProduct("Microsoft® .NET Framework")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyFileVersion("4.6.24705.01")] [assembly: AssemblyInformationalVersion("4.6.24705.01. Commit Hash: 4d1af962ca0fede10beb01d197367c2f90e92c97")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyVersion("4.0.2.0")] namespace System { public interface IServiceProvider { object GetService(System.Type serviceType); } } namespace System.ComponentModel { public class CancelEventArgs : EventArgs { [field: CompilerGenerated] public bool Cancel { [CompilerGenerated] get; [CompilerGenerated] set; } public CancelEventArgs() { } public CancelEventArgs(bool cancel) { Cancel = cancel; } } public interface IChangeTracking { bool IsChanged { get; } void AcceptChanges(); } public interface IEditableObject { void BeginEdit(); void EndEdit(); void CancelEdit(); } public interface IRevertibleChangeTracking : IChangeTracking { void RejectChanges(); } }
System.ComponentModel.Primitives.dll
Decompiled 5 days agousing System; using System.Diagnostics; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using FxResources.System.ComponentModel.Primitives; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyTitle("System.ComponentModel.Primitives")] [assembly: AssemblyDescription("System.ComponentModel.Primitives")] [assembly: AssemblyDefaultAlias("System.ComponentModel.Primitives")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyProduct("Microsoft® .NET Framework")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyFileVersion("4.6.24705.01")] [assembly: AssemblyInformationalVersion("4.6.24705.01. Commit Hash: 4d1af962ca0fede10beb01d197367c2f90e92c97")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyVersion("4.1.1.0")] namespace FxResources.System.ComponentModel.Primitives { internal static class SR : Object { } } namespace System { internal static class SR : Object { private static ResourceManager s_resourceManager; private const string s_resourcesName = "FxResources.System.ComponentModel.Primitives.SR"; private static ResourceManager ResourceManager { get { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown if (s_resourceManager == null) { s_resourceManager = new ResourceManager(ResourceType); } return s_resourceManager; } } internal static string PropertyCategoryAction => GetResourceString("PropertyCategoryAction", null); internal static string PropertyCategoryAppearance => GetResourceString("PropertyCategoryAppearance", null); internal static string PropertyCategoryAsynchronous => GetResourceString("PropertyCategoryAsynchronous", null); internal static string PropertyCategoryBehavior => GetResourceString("PropertyCategoryBehavior", null); internal static string PropertyCategoryConfig => GetResourceString("PropertyCategoryConfig", null); internal static string PropertyCategoryData => GetResourceString("PropertyCategoryData", null); internal static string PropertyCategoryDDE => GetResourceString("PropertyCategoryDDE", null); internal static string PropertyCategoryDefault => GetResourceString("PropertyCategoryDefault", null); internal static string PropertyCategoryDesign => GetResourceString("PropertyCategoryDesign", null); internal static string PropertyCategoryDragDrop => GetResourceString("PropertyCategoryDragDrop", null); internal static string PropertyCategoryFocus => GetResourceString("PropertyCategoryFocus", null); internal static string PropertyCategoryFont => GetResourceString("PropertyCategoryFont", null); internal static string PropertyCategoryFormat => GetResourceString("PropertyCategoryFormat", null); internal static string PropertyCategoryKey => GetResourceString("PropertyCategoryKey", null); internal static string PropertyCategoryLayout => GetResourceString("PropertyCategoryLayout", null); internal static string PropertyCategoryList => GetResourceString("PropertyCategoryList", null); internal static string PropertyCategoryMouse => GetResourceString("PropertyCategoryMouse", null); internal static string PropertyCategoryPosition => GetResourceString("PropertyCategoryPosition", null); internal static string PropertyCategoryScale => GetResourceString("PropertyCategoryScale", null); internal static string PropertyCategoryText => GetResourceString("PropertyCategoryText", null); internal static string PropertyCategoryWindowStyle => GetResourceString("PropertyCategoryWindowStyle", null); internal static Type ResourceType => typeof(FxResources.System.ComponentModel.Primitives.SR); [MethodImpl(8)] private static bool UsingResourceKeys() { return false; } internal static string GetResourceString(string resourceKey, string defaultString) { string text = null; try { text = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } if (defaultString != null && resourceKey.Equals(text, (StringComparison)4)) { return defaultString; } return text; } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return String.Concat(resourceFormat, String.Join(", ", args)); } return String.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return String.Join(", ", (object[])(object)new Object[2] { (Object)resourceFormat, p1 }); } return String.Format(resourceFormat, (object[])(object)new Object[1] { p1 }); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return String.Join(", ", (object[])(object)new Object[3] { (Object)resourceFormat, p1, p2 }); } return String.Format(resourceFormat, (object[])(object)new Object[2] { p1, p2 }); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return String.Join(", ", (object[])(object)new Object[4] { (Object)resourceFormat, p1, p2, p3 }); } return String.Format(resourceFormat, (object[])(object)new Object[3] { p1, p2, p3 }); } } } namespace System.ComponentModel { [AttributeUsage(/*Could not decode attribute arguments.*/)] public sealed class BrowsableAttribute : Attribute { public static readonly BrowsableAttribute Yes = new BrowsableAttribute(browsable: true); public static readonly BrowsableAttribute No = new BrowsableAttribute(browsable: false); public static readonly BrowsableAttribute Default = Yes; private bool _browsable; public bool Browsable => _browsable; public BrowsableAttribute(bool browsable) { _browsable = browsable; } public override bool Equals(object obj) { if (obj == this) { return true; } if (obj is BrowsableAttribute browsableAttribute) { return browsableAttribute.Browsable == _browsable; } return false; } public override int GetHashCode() { return ((Boolean)(ref _browsable)).GetHashCode(); } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public class CategoryAttribute : Attribute { private static volatile CategoryAttribute s_action; private static volatile CategoryAttribute s_appearance; private static volatile CategoryAttribute s_asynchronous; private static volatile CategoryAttribute s_behavior; private static volatile CategoryAttribute s_data; private static volatile CategoryAttribute s_design; private static volatile CategoryAttribute s_dragDrop; private static volatile CategoryAttribute s_defAttr; private static volatile CategoryAttribute s_focus; private static volatile CategoryAttribute s_format; private static volatile CategoryAttribute s_key; private static volatile CategoryAttribute s_layout; private static volatile CategoryAttribute s_mouse; private static volatile CategoryAttribute s_windowStyle; private bool _localized; private string _categoryValue; public static CategoryAttribute Action { get { if (s_action == null) { s_action = new CategoryAttribute("Action"); } return s_action; } } public static CategoryAttribute Appearance { get { if (s_appearance == null) { s_appearance = new CategoryAttribute("Appearance"); } return s_appearance; } } public static CategoryAttribute Asynchronous { get { if (s_asynchronous == null) { s_asynchronous = new CategoryAttribute("Asynchronous"); } return s_asynchronous; } } public static CategoryAttribute Behavior { get { if (s_behavior == null) { s_behavior = new CategoryAttribute("Behavior"); } return s_behavior; } } public static CategoryAttribute Data { get { if (s_data == null) { s_data = new CategoryAttribute("Data"); } return s_data; } } public static CategoryAttribute Default { get { if (s_defAttr == null) { s_defAttr = new CategoryAttribute(); } return s_defAttr; } } public static CategoryAttribute Design { get { if (s_design == null) { s_design = new CategoryAttribute("Design"); } return s_design; } } public static CategoryAttribute DragDrop { get { if (s_dragDrop == null) { s_dragDrop = new CategoryAttribute("DragDrop"); } return s_dragDrop; } } public static CategoryAttribute Focus { get { if (s_focus == null) { s_focus = new CategoryAttribute("Focus"); } return s_focus; } } public static CategoryAttribute Format { get { if (s_format == null) { s_format = new CategoryAttribute("Format"); } return s_format; } } public static CategoryAttribute Key { get { if (s_key == null) { s_key = new CategoryAttribute("Key"); } return s_key; } } public static CategoryAttribute Layout { get { if (s_layout == null) { s_layout = new CategoryAttribute("Layout"); } return s_layout; } } public static CategoryAttribute Mouse { get { if (s_mouse == null) { s_mouse = new CategoryAttribute("Mouse"); } return s_mouse; } } public static CategoryAttribute WindowStyle { get { if (s_windowStyle == null) { s_windowStyle = new CategoryAttribute("WindowStyle"); } return s_windowStyle; } } public string Category { get { if (!_localized) { _localized = true; string localizedString = GetLocalizedString(_categoryValue); if (localizedString != null) { _categoryValue = localizedString; } } return _categoryValue; } } public CategoryAttribute() : this("Default") { } public CategoryAttribute(string category) { _categoryValue = category; _localized = false; } public override bool Equals(object obj) { if (obj == this) { return true; } if (obj is CategoryAttribute categoryAttribute) { return Category.Equals(categoryAttribute.Category); } return false; } public override int GetHashCode() { return ((Object)Category).GetHashCode(); } protected virtual string GetLocalizedString(string value) { return SR.GetResourceString(String.Concat("PropertyCategory", value), null); } } public class ComponentCollection : Object { private ComponentCollection() { } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public class DescriptionAttribute : Attribute { public static readonly DescriptionAttribute Default = new DescriptionAttribute(); public virtual string Description => DescriptionValue; [field: CompilerGenerated] protected string DescriptionValue { [CompilerGenerated] get; [CompilerGenerated] set; } public DescriptionAttribute() : this(String.Empty) { } public DescriptionAttribute(string description) { DescriptionValue = description; } public override bool Equals(object obj) { if (obj == this) { return true; } if (obj is DescriptionAttribute descriptionAttribute) { return descriptionAttribute.Description == Description; } return false; } public override int GetHashCode() { return ((Object)Description).GetHashCode(); } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public sealed class DesignerCategoryAttribute : Attribute { public static readonly DesignerCategoryAttribute Component = new DesignerCategoryAttribute("Component"); public static readonly DesignerCategoryAttribute Default = new DesignerCategoryAttribute(); public static readonly DesignerCategoryAttribute Form = new DesignerCategoryAttribute("Form"); public static readonly DesignerCategoryAttribute Generic = new DesignerCategoryAttribute("Designer"); [field: CompilerGenerated] public string Category { [CompilerGenerated] get; } public DesignerCategoryAttribute() { Category = String.Empty; } public DesignerCategoryAttribute(string category) { Category = category; } public override bool Equals(object obj) { if (obj == this) { return true; } if (obj is DesignerCategoryAttribute designerCategoryAttribute) { return designerCategoryAttribute.Category == Category; } return false; } public override int GetHashCode() { return ((Object)Category).GetHashCode(); } } public enum DesignerSerializationVisibility : Enum { Hidden, Visible, Content } [AttributeUsage(/*Could not decode attribute arguments.*/)] public sealed class DesignerSerializationVisibilityAttribute : Attribute { public static readonly DesignerSerializationVisibilityAttribute Content = new DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Content); public static readonly DesignerSerializationVisibilityAttribute Hidden = new DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden); public static readonly DesignerSerializationVisibilityAttribute Visible = new DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible); public static readonly DesignerSerializationVisibilityAttribute Default = Visible; private readonly DesignerSerializationVisibility _visibility; public DesignerSerializationVisibility Visibility => _visibility; public DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility visibility) { _visibility = visibility; } public override bool Equals(object obj) { if (obj == this) { return true; } if (obj is DesignerSerializationVisibilityAttribute designerSerializationVisibilityAttribute) { return designerSerializationVisibilityAttribute.Visibility == _visibility; } return false; } public override int GetHashCode() { return ((Attribute)this).GetHashCode(); } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public sealed class DesignOnlyAttribute : Attribute { public static readonly DesignOnlyAttribute Yes = new DesignOnlyAttribute(isDesignOnly: true); public static readonly DesignOnlyAttribute No = new DesignOnlyAttribute(isDesignOnly: false); public static readonly DesignOnlyAttribute Default = No; [field: CompilerGenerated] public bool IsDesignOnly { [CompilerGenerated] get; } public DesignOnlyAttribute(bool isDesignOnly) { IsDesignOnly = isDesignOnly; } public override bool Equals(object obj) { if (obj == this) { return true; } if (obj is DesignOnlyAttribute designOnlyAttribute) { return designOnlyAttribute.IsDesignOnly == IsDesignOnly; } return false; } public override int GetHashCode() { bool isDesignOnly = IsDesignOnly; return ((Boolean)(ref isDesignOnly)).GetHashCode(); } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public class DisplayNameAttribute : Attribute { public static readonly DisplayNameAttribute Default = new DisplayNameAttribute(); public virtual string DisplayName => DisplayNameValue; [field: CompilerGenerated] protected string DisplayNameValue { [CompilerGenerated] get; [CompilerGenerated] set; } public DisplayNameAttribute() : this(String.Empty) { } public DisplayNameAttribute(string displayName) { DisplayNameValue = displayName; } public override bool Equals(object obj) { if (obj == this) { return true; } if (obj is DisplayNameAttribute displayNameAttribute) { return displayNameAttribute.DisplayName == DisplayName; } return false; } public override int GetHashCode() { return ((Object)DisplayName).GetHashCode(); } } [DefaultMember("Item")] public sealed class EventHandlerList : Object, IDisposable { private sealed class ListEntry : Object { internal ListEntry next; internal object key; internal Delegate handler; public ListEntry(object key, Delegate handler, ListEntry next) { this.next = next; this.key = key; this.handler = handler; } } private ListEntry _head; public Delegate this[object key] { get { return Find(key)?.handler; } set { ListEntry listEntry = Find(key); if (listEntry != null) { listEntry.handler = value; } else { _head = new ListEntry(key, value, _head); } } } public void AddHandler(object key, Delegate value) { ListEntry listEntry = Find(key); if (listEntry != null) { listEntry.handler = Delegate.Combine(listEntry.handler, value); } else { _head = new ListEntry(key, value, _head); } } public void AddHandlers(EventHandlerList listToAddFrom) { for (ListEntry listEntry = listToAddFrom._head; listEntry != null; listEntry = listEntry.next) { AddHandler(listEntry.key, listEntry.handler); } } public void Dispose() { _head = null; } private ListEntry Find(object key) { ListEntry listEntry = _head; while (listEntry != null && listEntry.key != key) { listEntry = listEntry.next; } return listEntry; } public void RemoveHandler(object key, Delegate value) { ListEntry listEntry = Find(key); if (listEntry != null) { listEntry.handler = Delegate.Remove(listEntry.handler, value); } } } public interface IComponent : IDisposable { ISite Site { get; set; } event EventHandler Disposed; } public interface IContainer : IDisposable { ComponentCollection Components { get; } void Add(IComponent component); void Add(IComponent component, string name); void Remove(IComponent component); } [AttributeUsage(/*Could not decode attribute arguments.*/)] public sealed class ImmutableObjectAttribute : Attribute { public static readonly ImmutableObjectAttribute Yes = new ImmutableObjectAttribute(immutable: true); public static readonly ImmutableObjectAttribute No = new ImmutableObjectAttribute(immutable: false); public static readonly ImmutableObjectAttribute Default = No; [field: CompilerGenerated] public bool Immutable { [CompilerGenerated] get; } public ImmutableObjectAttribute(bool immutable) { Immutable = immutable; } public override bool Equals(object obj) { if (obj == this) { return true; } if (obj is ImmutableObjectAttribute immutableObjectAttribute) { return immutableObjectAttribute.Immutable == Immutable; } return false; } public override int GetHashCode() { return ((Attribute)this).GetHashCode(); } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public sealed class InitializationEventAttribute : Attribute { [field: CompilerGenerated] public string EventName { [CompilerGenerated] get; } public InitializationEventAttribute(string eventName) { EventName = eventName; } } public interface ISite : IServiceProvider { IComponent Component { get; } IContainer Container { get; } bool DesignMode { get; } string Name { get; set; } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public sealed class LocalizableAttribute : Attribute { public static readonly LocalizableAttribute Yes = new LocalizableAttribute(isLocalizable: true); public static readonly LocalizableAttribute No = new LocalizableAttribute(isLocalizable: false); public static readonly LocalizableAttribute Default = No; [field: CompilerGenerated] public bool IsLocalizable { [CompilerGenerated] get; } public LocalizableAttribute(bool isLocalizable) { IsLocalizable = isLocalizable; } public override bool Equals(object obj) { if (obj == this) { return true; } if (obj is LocalizableAttribute localizableAttribute) { return localizableAttribute.IsLocalizable == IsLocalizable; } return false; } public override int GetHashCode() { return ((Attribute)this).GetHashCode(); } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public sealed class MergablePropertyAttribute : Attribute { public static readonly MergablePropertyAttribute Yes = new MergablePropertyAttribute(allowMerge: true); public static readonly MergablePropertyAttribute No = new MergablePropertyAttribute(allowMerge: false); public static readonly MergablePropertyAttribute Default = Yes; [field: CompilerGenerated] public bool AllowMerge { [CompilerGenerated] get; } public MergablePropertyAttribute(bool allowMerge) { AllowMerge = allowMerge; } public override bool Equals(object obj) { if (obj == this) { return true; } if (obj is MergablePropertyAttribute mergablePropertyAttribute) { return mergablePropertyAttribute.AllowMerge == AllowMerge; } return false; } public override int GetHashCode() { return ((Attribute)this).GetHashCode(); } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public sealed class NotifyParentPropertyAttribute : Attribute { public static readonly NotifyParentPropertyAttribute Yes = new NotifyParentPropertyAttribute(notifyParent: true); public static readonly NotifyParentPropertyAttribute No = new NotifyParentPropertyAttribute(notifyParent: false); public static readonly NotifyParentPropertyAttribute Default = No; [field: CompilerGenerated] public bool NotifyParent { [CompilerGenerated] get; } public NotifyParentPropertyAttribute(bool notifyParent) { NotifyParent = notifyParent; } public override bool Equals(object obj) { if (obj == this) { return true; } if (obj is NotifyParentPropertyAttribute notifyParentPropertyAttribute) { return notifyParentPropertyAttribute.NotifyParent == NotifyParent; } return false; } public override int GetHashCode() { return ((Attribute)this).GetHashCode(); } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public sealed class ParenthesizePropertyNameAttribute : Attribute { public static readonly ParenthesizePropertyNameAttribute Default = new ParenthesizePropertyNameAttribute(); [field: CompilerGenerated] public bool NeedParenthesis { [CompilerGenerated] get; } public ParenthesizePropertyNameAttribute() : this(needParenthesis: false) { } public ParenthesizePropertyNameAttribute(bool needParenthesis) { NeedParenthesis = needParenthesis; } public override bool Equals(object obj) { if (obj == this) { return true; } if (obj is ParenthesizePropertyNameAttribute parenthesizePropertyNameAttribute) { return parenthesizePropertyNameAttribute.NeedParenthesis == NeedParenthesis; } return false; } public override int GetHashCode() { return ((Attribute)this).GetHashCode(); } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public sealed class ReadOnlyAttribute : Attribute { public static readonly ReadOnlyAttribute Yes = new ReadOnlyAttribute(isReadOnly: true); public static readonly ReadOnlyAttribute No = new ReadOnlyAttribute(isReadOnly: false); public static readonly ReadOnlyAttribute Default = No; [field: CompilerGenerated] public bool IsReadOnly { [CompilerGenerated] get; } public ReadOnlyAttribute(bool isReadOnly) { IsReadOnly = isReadOnly; } public override bool Equals(object value) { if (this == value) { return true; } if (value is ReadOnlyAttribute readOnlyAttribute) { return readOnlyAttribute.IsReadOnly == IsReadOnly; } return false; } public override int GetHashCode() { return ((Attribute)this).GetHashCode(); } } public enum RefreshProperties : Enum { None, All, Repaint } [AttributeUsage(/*Could not decode attribute arguments.*/)] public sealed class RefreshPropertiesAttribute : Attribute { public static readonly RefreshPropertiesAttribute All = new RefreshPropertiesAttribute(RefreshProperties.All); public static readonly RefreshPropertiesAttribute Repaint = new RefreshPropertiesAttribute(RefreshProperties.Repaint); public static readonly RefreshPropertiesAttribute Default = new RefreshPropertiesAttribute(RefreshProperties.None); [field: CompilerGenerated] public RefreshProperties RefreshProperties { [CompilerGenerated] get; } public RefreshPropertiesAttribute(RefreshProperties refresh) { RefreshProperties = refresh; } public override bool Equals(object obj) { if (obj == this) { return true; } if (obj is RefreshPropertiesAttribute refreshPropertiesAttribute) { return refreshPropertiesAttribute.RefreshProperties == RefreshProperties; } return false; } public override int GetHashCode() { return ((Attribute)this).GetHashCode(); } } }
System.ComponentModel.TypeConverter.dll
Decompiled 5 days ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.ComponentModel.Design; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using FxResources.System.ComponentModel.TypeConverter; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyTitle("System.ComponentModel.TypeConverter")] [assembly: AssemblyDescription("System.ComponentModel.TypeConverter")] [assembly: AssemblyDefaultAlias("System.ComponentModel.TypeConverter")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyProduct("Microsoft® .NET Framework")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyFileVersion("4.6.24705.01")] [assembly: AssemblyInformationalVersion("4.6.24705.01. Commit Hash: 4d1af962ca0fede10beb01d197367c2f90e92c97")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyVersion("4.1.1.0")] namespace FxResources.System.ComponentModel.TypeConverter { internal static class SR { } } namespace System { public class UriTypeConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (sourceType == null) { throw new ArgumentNullException("sourceType"); } if (sourceType != typeof(string)) { return sourceType == typeof(Uri); } return true; } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { if (destinationType != typeof(string)) { return destinationType == typeof(Uri); } return true; } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Expected O, but got Unknown //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown if (value is string text) { if (string.IsNullOrEmpty(text)) { return null; } return (object)new Uri(text, (UriKind)0); } Uri val = (Uri)((value is Uri) ? value : null); if (val != (Uri)null) { return (object)new Uri(val.OriginalString); } throw GetConvertFromException(value); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Expected O, but got Unknown if (destinationType == null) { throw new ArgumentNullException("destinationType"); } Uri val = (Uri)((value is Uri) ? value : null); if (val != (Uri)null) { if (destinationType == typeof(string)) { return val.OriginalString; } if (destinationType == typeof(Uri)) { return (object)new Uri(val.OriginalString, (UriKind)0); } } throw GetConvertToException(value, destinationType); } } internal class InvariantComparer : IComparer { private readonly CompareInfo _compareInfo; internal static readonly InvariantComparer Default = new InvariantComparer(); internal InvariantComparer() { _compareInfo = CultureInfo.InvariantCulture.CompareInfo; } public int Compare(object a, object b) { string text = a as string; string text2 = b as string; if (text != null && text2 != null) { return _compareInfo.Compare(text, text2); } return Comparer.Default.Compare(a, b); } } internal static class SR { private static ResourceManager s_resourceManager; private const string s_resourcesName = "FxResources.System.ComponentModel.TypeConverter.SR"; private static ResourceManager ResourceManager { get { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown if (s_resourceManager == null) { s_resourceManager = new ResourceManager(ResourceType); } return s_resourceManager; } } internal static string Array => GetResourceString("Array", null); internal static string Collection => GetResourceString("Collection", null); internal static string ConvertFromException => GetResourceString("ConvertFromException", null); internal static string ConvertInvalidPrimitive => GetResourceString("ConvertInvalidPrimitive", null); internal static string ConvertToException => GetResourceString("ConvertToException", null); internal static string EnumConverterInvalidValue => GetResourceString("EnumConverterInvalidValue", null); internal static string ErrorInvalidEventHandler => GetResourceString("ErrorInvalidEventHandler", null); internal static string ErrorInvalidEventType => GetResourceString("ErrorInvalidEventType", null); internal static string ErrorInvalidPropertyType => GetResourceString("ErrorInvalidPropertyType", null); internal static string ErrorMissingEventAccessors => GetResourceString("ErrorMissingEventAccessors", null); internal static string ErrorMissingPropertyAccessors => GetResourceString("ErrorMissingPropertyAccessors", null); internal static string ErrorPropertyAccessorException => GetResourceString("ErrorPropertyAccessorException", null); internal static string InvalidMemberName => GetResourceString("InvalidMemberName", null); internal static string InvalidNullArgument => GetResourceString("InvalidNullArgument", null); internal static string MetaExtenderName => GetResourceString("MetaExtenderName", null); internal static string none => GetResourceString("none", null); internal static string Null => GetResourceString("Null", null); internal static string NullableConverterBadCtorArg => GetResourceString("NullableConverterBadCtorArg", null); internal static string Text => GetResourceString("Text", null); internal static string TypeDescriptorAlreadyAssociated => GetResourceString("TypeDescriptorAlreadyAssociated", null); internal static string TypeDescriptorArgsCountMismatch => GetResourceString("TypeDescriptorArgsCountMismatch", null); internal static string TypeDescriptorProviderError => GetResourceString("TypeDescriptorProviderError", null); internal static string TypeDescriptorUnsupportedRemoteObject => GetResourceString("TypeDescriptorUnsupportedRemoteObject", null); internal static string TypeDescriptorExpectedElementType => GetResourceString("TypeDescriptorExpectedElementType", null); internal static string TypeDescriptorSameAssociation => GetResourceString("TypeDescriptorSameAssociation", null); internal static System.Type ResourceType => typeof(SR); [MethodImpl(8)] private static bool UsingResourceKeys() { return false; } internal static string GetResourceString(string resourceKey, string defaultString) { string text = null; try { text = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } if (defaultString != null && resourceKey.Equals(text, (StringComparison)4)) { return defaultString; } return text; } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", new object[2] { resourceFormat, p1 }); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", new object[3] { resourceFormat, p1, p2 }); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", new object[4] { resourceFormat, p1, p2, p3 }); } return string.Format(resourceFormat, p1, p2, p3); } } } namespace System.ComponentModel { public class ArrayConverter : CollectionConverter { private class ArrayPropertyDescriptor : SimplePropertyDescriptor { private readonly int _index; public ArrayPropertyDescriptor(System.Type arrayType, System.Type elementType, int index) : base(arrayType, string.Concat((object)"[", (object)index, (object)"]"), elementType, null) { _index = index; } public override object GetValue(object instance) { if (instance is System.Array array && array.GetLength(0) > _index) { return array.GetValue(_index); } return null; } public override void SetValue(object instance, object value) { if (instance is System.Array) { System.Array array = (System.Array)instance; if (array.GetLength(0) > _index) { array.SetValue(value, _index); } OnValueChanged(instance, EventArgs.Empty); } } } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) if (destinationType == null) { throw new ArgumentNullException("destinationType"); } if (destinationType == typeof(string) && value is System.Array) { return System.SR.Format(System.SR.Array, value.GetType().Name); } return base.ConvertTo(context, culture, value, destinationType); } public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, System.Attribute[] attributes) { if (value == null) { return null; } PropertyDescriptor[] array = null; if (value.GetType().IsArray) { System.Array array2 = (System.Array)value; int length = array2.GetLength(0); array = new PropertyDescriptor[length]; System.Type type = value.GetType(); System.Type elementType = type.GetElementType(); for (int i = 0; i < length; i++) { array[i] = new ArrayPropertyDescriptor(type, elementType, i); } } return new PropertyDescriptorCollection(array); } public override bool GetPropertiesSupported(ITypeDescriptorContext context) { return true; } } public abstract class BaseNumberConverter : TypeConverter { internal virtual bool AllowHex => true; internal abstract System.Type TargetType { get; } internal abstract object FromString(string value, int radix); internal abstract object FromString(string value, NumberFormatInfo formatInfo); internal abstract object FromString(string value, CultureInfo culture); internal virtual System.Exception FromStringError(string failedText, System.Exception innerException) { return new System.Exception(System.SR.Format(System.SR.ConvertInvalidPrimitive, failedText, TargetType.Name), innerException); } internal abstract string ToString(object value, NumberFormatInfo formatInfo); public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType) { if (sourceType != typeof(string)) { return base.CanConvertFrom(context, sourceType); } return true; } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Expected O, but got Unknown if (value is string text) { string text2 = text.Trim(); try { if (AllowHex && text2[0] == '#') { return FromString(text2.Substring(1), 16); } if ((AllowHex && text2.StartsWith("0x", (StringComparison)5)) || text2.StartsWith("&h", (StringComparison)5)) { return FromString(text2.Substring(2), 16); } if (culture == null) { culture = CultureInfo.CurrentCulture; } NumberFormatInfo formatInfo = (NumberFormatInfo)culture.GetFormat(typeof(NumberFormatInfo)); return FromString(text2, formatInfo); } catch (System.Exception innerException) { throw FromStringError(text2, innerException); } } return base.ConvertFrom(context, culture, value); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Expected O, but got Unknown if (destinationType == null) { throw new ArgumentNullException("destinationType"); } if (destinationType == typeof(string) && value != null && IntrospectionExtensions.GetTypeInfo(TargetType).IsAssignableFrom(IntrospectionExtensions.GetTypeInfo(value.GetType()))) { if (culture == null) { culture = CultureInfo.CurrentCulture; } NumberFormatInfo val = (NumberFormatInfo)culture.GetFormat(typeof(NumberFormatInfo)); return ToString(value, val); } if (IntrospectionExtensions.GetTypeInfo(destinationType).IsPrimitive) { return Convert.ChangeType(value, destinationType, (IFormatProvider)(object)culture); } return base.ConvertTo(context, culture, value, destinationType); } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { if (!base.CanConvertTo(context, destinationType)) { return IntrospectionExtensions.GetTypeInfo(destinationType).IsPrimitive; } return true; } } public class BooleanConverter : TypeConverter { private static volatile StandardValuesCollection s_values; public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType) { if (sourceType != typeof(string)) { return base.CanConvertFrom(context, sourceType); } return true; } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { //IL_0020: Expected O, but got Unknown //IL_0036: Unknown result type (might be due to invalid IL or missing references) if (value is string text) { string text2 = text.Trim(); try { return bool.Parse(text2); } catch (FormatException val) { FormatException val2 = val; throw new FormatException(System.SR.Format(System.SR.ConvertInvalidPrimitive, (string)value, "Boolean"), (System.Exception)(object)val2); } } return base.ConvertFrom(context, culture, value); } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { if (s_values == null) { s_values = new StandardValuesCollection((System.Collections.ICollection)(object)new object[2] { true, false }); } return s_values; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } } public class ByteConverter : BaseNumberConverter { internal override System.Type TargetType => typeof(byte); internal override object FromString(string value, int radix) { return Convert.ToByte(value, radix); } internal override object FromString(string value, NumberFormatInfo formatInfo) { return byte.Parse(value, (NumberStyles)7, (IFormatProvider)(object)formatInfo); } internal override object FromString(string value, CultureInfo culture) { return byte.Parse(value, (IFormatProvider)(object)culture); } internal override string ToString(object value, NumberFormatInfo formatInfo) { return ((byte)value).ToString("G", (IFormatProvider)(object)formatInfo); } } public class CharConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType) { if (sourceType != typeof(string)) { return base.CanConvertFrom(context, sourceType); } return true; } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { if (destinationType == typeof(string) && value is char && (char)value == '\0') { return ""; } return base.ConvertTo(context, culture, value, destinationType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { //IL_003c: Unknown result type (might be due to invalid IL or missing references) string text = value as string; if (text != null) { if (text.Length > 1) { text = text.Trim(); } if (text.Length > 0) { if (text.Length != 1) { throw new FormatException(System.SR.Format(System.SR.ConvertInvalidPrimitive, text, "Char")); } return text[0]; } return '\0'; } return base.ConvertFrom(context, culture, value); } } public class CollectionConverter : TypeConverter { public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) if (destinationType == null) { throw new ArgumentNullException("destinationType"); } if (destinationType == typeof(string) && value is System.Collections.ICollection) { return System.SR.Collection; } return base.ConvertTo(context, culture, value, destinationType); } public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, System.Attribute[] attributes) { return new PropertyDescriptorCollection(null); } public override bool GetPropertiesSupported(ITypeDescriptorContext context) { return false; } } public class DateTimeConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType) { if (sourceType != typeof(string)) { return base.CanConvertFrom(context, sourceType); } return true; } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { return base.CanConvertTo(context, destinationType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { //IL_0062: Expected O, but got Unknown //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Expected O, but got Unknown if (value is string text) { string text2 = text.Trim(); if (text2.Length == 0) { return System.DateTime.MinValue; } try { DateTimeFormatInfo val = null; if (culture != null) { val = (DateTimeFormatInfo)culture.GetFormat(typeof(DateTimeFormatInfo)); } if (val != null) { return System.DateTime.Parse(text2, (IFormatProvider)(object)val); } return System.DateTime.Parse(text2, (IFormatProvider)(object)culture); } catch (FormatException val2) { FormatException val3 = val2; throw new FormatException(System.SR.Format(System.SR.ConvertInvalidPrimitive, (string)value, "DateTime"), (System.Exception)(object)val3); } } return base.ConvertFrom(context, culture, value); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Expected O, but got Unknown //IL_0093: 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) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) if (destinationType == typeof(string) && value is System.DateTime dateTime) { if (dateTime == System.DateTime.MinValue) { return string.Empty; } if (culture == null) { culture = CultureInfo.CurrentCulture; } DateTimeFormatInfo val = null; val = (DateTimeFormatInfo)culture.GetFormat(typeof(DateTimeFormatInfo)); TimeSpan timeOfDay; if (culture == CultureInfo.InvariantCulture) { timeOfDay = dateTime.TimeOfDay; if (((TimeSpan)(ref timeOfDay)).TotalSeconds == 0.0) { return dateTime.ToString("yyyy-MM-dd", (IFormatProvider)(object)culture); } return dateTime.ToString((IFormatProvider)(object)culture); } timeOfDay = dateTime.TimeOfDay; string text = ((((TimeSpan)(ref timeOfDay)).TotalSeconds != 0.0) ? (val.ShortDatePattern + " " + val.ShortTimePattern) : val.ShortDatePattern); return dateTime.ToString(text, (IFormatProvider)(object)CultureInfo.CurrentCulture); } return base.ConvertTo(context, culture, value, destinationType); } } public class DateTimeOffsetConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType) { if (sourceType != typeof(string)) { return base.CanConvertFrom(context, sourceType); } return true; } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { return base.CanConvertTo(context, destinationType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { //IL_0062: Expected O, but got Unknown //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Expected O, but got Unknown //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) if (value is string text) { string text2 = text.Trim(); if (text2.Length == 0) { return DateTimeOffset.MinValue; } try { DateTimeFormatInfo val = null; if (culture != null) { val = (DateTimeFormatInfo)culture.GetFormat(typeof(DateTimeFormatInfo)); } if (val != null) { return DateTimeOffset.Parse(text2, (IFormatProvider)(object)val); } return DateTimeOffset.Parse(text2, (IFormatProvider)(object)culture); } catch (FormatException val2) { FormatException val3 = val2; throw new FormatException(System.SR.Format(System.SR.ConvertInvalidPrimitive, (string)value, "DateTimeOffset"), (System.Exception)(object)val3); } } return base.ConvertFrom(context, culture, value); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Expected O, but got Unknown //IL_0093: 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) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) if (destinationType == typeof(string) && value is DateTimeOffset val) { if (val == DateTimeOffset.MinValue) { return string.Empty; } if (culture == null) { culture = CultureInfo.CurrentCulture; } DateTimeFormatInfo val2 = null; val2 = (DateTimeFormatInfo)culture.GetFormat(typeof(DateTimeFormatInfo)); TimeSpan timeOfDay; if (culture == CultureInfo.InvariantCulture) { timeOfDay = ((DateTimeOffset)(ref val)).TimeOfDay; if (((TimeSpan)(ref timeOfDay)).TotalSeconds == 0.0) { return ((DateTimeOffset)(ref val)).ToString("yyyy-MM-dd zzz", (IFormatProvider)(object)culture); } return ((DateTimeOffset)(ref val)).ToString((IFormatProvider)(object)culture); } timeOfDay = ((DateTimeOffset)(ref val)).TimeOfDay; string text = ((((TimeSpan)(ref timeOfDay)).TotalSeconds != 0.0) ? (val2.ShortDatePattern + " " + val2.ShortTimePattern + " zzz") : (val2.ShortDatePattern + " zzz")); return ((DateTimeOffset)(ref val)).ToString(text, (IFormatProvider)(object)CultureInfo.CurrentCulture); } return base.ConvertTo(context, culture, value, destinationType); } } public class DecimalConverter : BaseNumberConverter { internal override bool AllowHex => false; internal override System.Type TargetType => typeof(decimal); public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) if (destinationType == null) { throw new ArgumentNullException("destinationType"); } return base.ConvertTo(context, culture, value, destinationType); } internal override object FromString(string value, int radix) { return Convert.ToDecimal(value, (IFormatProvider)(object)CultureInfo.CurrentCulture); } internal override object FromString(string value, NumberFormatInfo formatInfo) { return decimal.Parse(value, (NumberStyles)167, (IFormatProvider)(object)formatInfo); } internal override object FromString(string value, CultureInfo culture) { return decimal.Parse(value, (IFormatProvider)(object)culture); } internal override string ToString(object value, NumberFormatInfo formatInfo) { return ((decimal)value).ToString("G", (IFormatProvider)(object)formatInfo); } } public class DoubleConverter : BaseNumberConverter { internal override bool AllowHex => false; internal override System.Type TargetType => typeof(double); internal override object FromString(string value, int radix) { return Convert.ToDouble(value, (IFormatProvider)(object)CultureInfo.CurrentCulture); } internal override object FromString(string value, NumberFormatInfo formatInfo) { return double.Parse(value, (NumberStyles)167, (IFormatProvider)(object)formatInfo); } internal override object FromString(string value, CultureInfo culture) { return double.Parse(value, (IFormatProvider)(object)culture); } internal override string ToString(object value, NumberFormatInfo formatInfo) { return ((double)value).ToString("R", (IFormatProvider)(object)formatInfo); } } public class EnumConverter : TypeConverter { private StandardValuesCollection _values; private readonly System.Type _type; protected System.Type EnumType => _type; protected StandardValuesCollection Values { get { return _values; } set { _values = value; } } protected virtual IComparer Comparer => (IComparer)(object)InvariantComparer.Default; public EnumConverter(System.Type type) { _type = type; } public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType) { if (sourceType == typeof(string) || sourceType == typeof(System.Enum[])) { return true; } return base.CanConvertFrom(context, sourceType); } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { if (destinationType == typeof(System.Enum[])) { return true; } return base.CanConvertTo(context, destinationType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { //IL_00ab: Unknown result type (might be due to invalid IL or missing references) if (value is string text) { try { if (text.IndexOf(',') != -1) { long num = 0L; string[] array = text.Split(new char[1] { ',' }); string[] array2 = array; foreach (string text2 in array2) { num |= Convert.ToInt64((object)(System.Enum)System.Enum.Parse(_type, text2, true), (IFormatProvider)(object)culture); } return System.Enum.ToObject(_type, (object)num); } return System.Enum.Parse(_type, text, true); } catch (System.Exception ex) { throw new FormatException(System.SR.Format(System.SR.ConvertInvalidPrimitive, (string)value, _type.Name), ex); } } if (value is System.Enum[]) { long num2 = 0L; System.Enum[] array3 = (System.Enum[])value; foreach (System.Enum @enum in array3) { num2 |= Convert.ToInt64((object)@enum, (IFormatProvider)(object)culture); } return System.Enum.ToObject(_type, (object)num2); } return base.ConvertFrom(context, culture, value); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) if (destinationType == null) { throw new ArgumentNullException("destinationType"); } if (destinationType == typeof(string) && value != null) { if (!CustomAttributeExtensions.IsDefined((MemberInfo)(object)IntrospectionExtensions.GetTypeInfo(_type), typeof(FlagsAttribute), false) && !System.Enum.IsDefined(_type, value)) { throw new ArgumentException(System.SR.Format(System.SR.EnumConverterInvalidValue, value.ToString(), _type.Name)); } return System.Enum.Format(_type, value, "G"); } if (destinationType == typeof(System.Enum[]) && value != null) { if (CustomAttributeExtensions.IsDefined((MemberInfo)(object)IntrospectionExtensions.GetTypeInfo(_type), typeof(FlagsAttribute), false)) { List<System.Enum> val = new List<System.Enum>(); System.Array values = System.Enum.GetValues(_type); long[] array = new long[values.Length]; for (int i = 0; i < values.Length; i++) { array[i] = Convert.ToInt64((object)(System.Enum)values.GetValue(i), (IFormatProvider)(object)culture); } long num = Convert.ToInt64((object)(System.Enum)value, (IFormatProvider)(object)culture); bool flag = true; while (flag) { flag = false; long[] array2 = array; foreach (long num2 in array2) { if ((num2 != 0L && (num2 & num) == num2) || num2 == num) { val.Add((System.Enum)System.Enum.ToObject(_type, (object)num2)); flag = true; num &= ~num2; break; } } if (num == 0L) { break; } } if (!flag && num != 0L) { val.Add((System.Enum)System.Enum.ToObject(_type, (object)num)); } return val.ToArray(); } return new System.Enum[1] { (System.Enum)System.Enum.ToObject(_type, value) }; } return base.ConvertTo(context, culture, value, destinationType); } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Expected O, but got Unknown if (_values == null) { System.Type type = TypeDescriptor.GetReflectionType(_type); if (type == null) { type = _type; } FieldInfo[] fields = TypeExtensions.GetFields(type, (BindingFlags)24); ArrayList val = null; if (fields != null && fields.Length != 0) { val = new ArrayList(fields.Length); } if (val != null) { FieldInfo[] array = fields; foreach (FieldInfo val2 in array) { BrowsableAttribute val3 = null; System.Collections.Generic.IEnumerator<System.Attribute> enumerator = CustomAttributeExtensions.GetCustomAttributes((MemberInfo)(object)val2, typeof(BrowsableAttribute), false).GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { System.Attribute current = enumerator.Current; val3 = (BrowsableAttribute)(object)((current is BrowsableAttribute) ? current : null); } } finally { ((System.IDisposable)enumerator)?.Dispose(); } if (val3 != null && !val3.Browsable) { continue; } object obj = null; try { if (((MemberInfo)val2).Name != null) { obj = System.Enum.Parse(_type, ((MemberInfo)val2).Name); } } catch (ArgumentException) { } if (obj != null) { val.Add(obj); } } IComparer comparer = Comparer; if (comparer != null) { val.Sort(comparer); } } System.Array values = ((val != null) ? val.ToArray() : null); _values = new StandardValuesCollection((System.Collections.ICollection)values); } return _values; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return !CustomAttributeExtensions.IsDefined((MemberInfo)(object)IntrospectionExtensions.GetTypeInfo(_type), typeof(FlagsAttribute), false); } public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool IsValid(ITypeDescriptorContext context, object value) { return System.Enum.IsDefined(_type, value); } } public class GuidConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType) { if (sourceType != typeof(string)) { return base.CanConvertFrom(context, sourceType); } return true; } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { return base.CanConvertTo(context, destinationType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) if (value is string text) { string text2 = text.Trim(); return (object)new Guid(text2); } return base.ConvertFrom(context, culture, value); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) if (destinationType == null) { throw new ArgumentNullException("destinationType"); } return base.ConvertTo(context, culture, value, destinationType); } } public class Int16Converter : BaseNumberConverter { internal override System.Type TargetType => typeof(short); internal override object FromString(string value, int radix) { return Convert.ToInt16(value, radix); } internal override object FromString(string value, CultureInfo culture) { return short.Parse(value, (IFormatProvider)(object)culture); } internal override object FromString(string value, NumberFormatInfo formatInfo) { return short.Parse(value, (NumberStyles)7, (IFormatProvider)(object)formatInfo); } internal override string ToString(object value, NumberFormatInfo formatInfo) { return ((short)value).ToString("G", (IFormatProvider)(object)formatInfo); } } public class Int32Converter : BaseNumberConverter { internal override System.Type TargetType => typeof(int); internal override object FromString(string value, int radix) { return Convert.ToInt32(value, radix); } internal override object FromString(string value, NumberFormatInfo formatInfo) { return int.Parse(value, (NumberStyles)7, (IFormatProvider)(object)formatInfo); } internal override object FromString(string value, CultureInfo culture) { return int.Parse(value, (IFormatProvider)(object)culture); } internal override string ToString(object value, NumberFormatInfo formatInfo) { return ((int)value).ToString("G", (IFormatProvider)(object)formatInfo); } } public class Int64Converter : BaseNumberConverter { internal override System.Type TargetType => typeof(long); internal override object FromString(string value, int radix) { return Convert.ToInt64(value, radix); } internal override object FromString(string value, NumberFormatInfo formatInfo) { return long.Parse(value, (NumberStyles)7, (IFormatProvider)(object)formatInfo); } internal override object FromString(string value, CultureInfo culture) { return long.Parse(value, (IFormatProvider)(object)culture); } internal override string ToString(object value, NumberFormatInfo formatInfo) { return ((long)value).ToString("G", (IFormatProvider)(object)formatInfo); } } public interface ITypeDescriptorContext : IServiceProvider { IContainer Container { get; } object Instance { get; } PropertyDescriptor PropertyDescriptor { get; } bool OnComponentChanging(); void OnComponentChanged(); } public class MultilineStringConverter : TypeConverter { public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) if (destinationType == null) { throw new ArgumentNullException("destinationType"); } if (destinationType == typeof(string) && value is string) { return System.SR.Text; } return base.ConvertTo(context, culture, value, destinationType); } public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, System.Attribute[] attributes) { return null; } public override bool GetPropertiesSupported(ITypeDescriptorContext context) { return false; } } public class NullableConverter : TypeConverter { private readonly System.Type _nullableType; private readonly System.Type _simpleType; private readonly TypeConverter _simpleTypeConverter; public System.Type NullableType => _nullableType; public System.Type UnderlyingType => _simpleType; public TypeConverter UnderlyingTypeConverter => _simpleTypeConverter; public NullableConverter(System.Type type) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) _nullableType = type; _simpleType = Nullable.GetUnderlyingType(type); if (_simpleType == null) { throw new ArgumentException(System.SR.NullableConverterBadCtorArg, "type"); } _simpleTypeConverter = TypeDescriptor.GetConverter(_simpleType); } public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType) { if (sourceType == _simpleType) { return true; } if (_simpleTypeConverter != null) { return _simpleTypeConverter.CanConvertFrom(context, sourceType); } return base.CanConvertFrom(context, sourceType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value == null || value.GetType() == _simpleType) { return value; } if (value is string && string.IsNullOrEmpty(value as string)) { return null; } if (_simpleTypeConverter != null) { return _simpleTypeConverter.ConvertFrom(context, culture, value); } return base.ConvertFrom(context, culture, value); } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { if (destinationType == _simpleType) { return true; } if (_simpleTypeConverter != null) { return _simpleTypeConverter.CanConvertTo(context, destinationType); } return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) if (destinationType == null) { throw new ArgumentNullException("destinationType"); } if (destinationType == _simpleType && value != null && IntrospectionExtensions.GetTypeInfo(_nullableType).IsAssignableFrom(IntrospectionExtensions.GetTypeInfo(value.GetType()))) { return value; } if (value == null) { if (destinationType == typeof(string)) { return string.Empty; } } else if (_simpleTypeConverter != null) { return _simpleTypeConverter.ConvertTo(context, culture, value, destinationType); } return base.ConvertTo(context, culture, value, destinationType); } public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues) { if (_simpleTypeConverter != null) { return _simpleTypeConverter.CreateInstance(context, propertyValues); } return base.CreateInstance(context, propertyValues); } public override bool GetCreateInstanceSupported(ITypeDescriptorContext context) { if (_simpleTypeConverter != null) { return _simpleTypeConverter.GetCreateInstanceSupported(context); } return base.GetCreateInstanceSupported(context); } public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, System.Attribute[] attributes) { if (_simpleTypeConverter != null) { return _simpleTypeConverter.GetProperties(context, value, attributes); } return base.GetProperties(context, value, attributes); } public override bool GetPropertiesSupported(ITypeDescriptorContext context) { if (_simpleTypeConverter != null) { return _simpleTypeConverter.GetPropertiesSupported(context); } return base.GetPropertiesSupported(context); } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { if (_simpleTypeConverter != null) { StandardValuesCollection standardValues = _simpleTypeConverter.GetStandardValues(context); if (GetStandardValuesSupported(context) && standardValues != null) { object[] array = new object[standardValues.Count + 1]; int num = 0; array[num++] = null; foreach (object item in standardValues) { array[num++] = item; } return new StandardValuesCollection((System.Collections.ICollection)(object)array); } } return base.GetStandardValues(context); } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { if (_simpleTypeConverter != null) { return _simpleTypeConverter.GetStandardValuesExclusive(context); } return base.GetStandardValuesExclusive(context); } public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { if (_simpleTypeConverter != null) { return _simpleTypeConverter.GetStandardValuesSupported(context); } return base.GetStandardValuesSupported(context); } public override bool IsValid(ITypeDescriptorContext context, object value) { if (_simpleTypeConverter != null) { if (value == null) { return true; } return _simpleTypeConverter.IsValid(context, value); } return base.IsValid(context, value); } } public abstract class PropertyDescriptor : MemberDescriptor { private TypeConverter _converter; private Hashtable _valueChangedHandlers; private object[] _editors; private System.Type[] _editorTypes; private int _editorCount; public abstract System.Type ComponentType { get; } public virtual TypeConverter Converter { get { AttributeCollection attributes = Attributes; if (_converter == null) { TypeConverterAttribute typeConverterAttribute = (TypeConverterAttribute)attributes[typeof(TypeConverterAttribute)]; if (typeConverterAttribute.ConverterTypeName != null && typeConverterAttribute.ConverterTypeName.Length > 0) { System.Type typeFromName = GetTypeFromName(typeConverterAttribute.ConverterTypeName); if (typeFromName != null && IntrospectionExtensions.GetTypeInfo(typeof(TypeConverter)).IsAssignableFrom(typeFromName)) { _converter = (TypeConverter)CreateInstance(typeFromName); } } if (_converter == null) { _converter = TypeDescriptor.GetConverter(PropertyType); } } return _converter; } } public virtual bool IsLocalizable => ((object)LocalizableAttribute.Yes).Equals((object)Attributes[typeof(LocalizableAttribute)]); public abstract bool IsReadOnly { get; } public DesignerSerializationVisibility SerializationVisibility { get { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown //IL_001c: Unknown result type (might be due to invalid IL or missing references) DesignerSerializationVisibilityAttribute val = (DesignerSerializationVisibilityAttribute)Attributes[typeof(DesignerSerializationVisibilityAttribute)]; return val.Visibility; } } public abstract System.Type PropertyType { get; } public virtual bool SupportsChangeEvents => false; protected PropertyDescriptor(string name, System.Attribute[] attrs) : base(name, attrs) { } protected PropertyDescriptor(MemberDescriptor descr) : base(descr) { } protected PropertyDescriptor(MemberDescriptor descr, System.Attribute[] attrs) : base(descr, attrs) { } public virtual void AddValueChanged(object component, EventHandler handler) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0016: 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_0041: Expected O, but got Unknown //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown if (component == null) { throw new ArgumentNullException("component"); } if (handler == null) { throw new ArgumentNullException("handler"); } if (_valueChangedHandlers == null) { _valueChangedHandlers = new Hashtable(); } EventHandler val = (EventHandler)_valueChangedHandlers[component]; _valueChangedHandlers[component] = System.Delegate.Combine((System.Delegate)(object)val, (System.Delegate)(object)handler); } public abstract bool CanResetValue(object component); public override bool Equals(object obj) { try { if (obj == this) { return true; } if (obj == null) { return false; } if (obj is PropertyDescriptor propertyDescriptor && propertyDescriptor.NameHashCode == NameHashCode && propertyDescriptor.PropertyType == PropertyType && propertyDescriptor.Name.Equals(Name)) { return true; } } catch { } return false; } protected object CreateInstance(System.Type type) { System.Type[] array = new System.Type[1] { typeof(System.Type) }; ConstructorInfo constructor = IntrospectionExtensions.GetTypeInfo(type).GetConstructor(array); if (constructor != null) { return TypeDescriptor.CreateInstance(null, type, array, new object[1] { PropertyType }); } return TypeDescriptor.CreateInstance(null, type, null, null); } protected override void FillAttributes(System.Collections.IList attributeList) { _converter = null; _editors = null; _editorTypes = null; _editorCount = 0; base.FillAttributes(attributeList); } public PropertyDescriptorCollection GetChildProperties() { return GetChildProperties(null, null); } public PropertyDescriptorCollection GetChildProperties(System.Attribute[] filter) { return GetChildProperties(null, filter); } public PropertyDescriptorCollection GetChildProperties(object instance) { return GetChildProperties(instance, null); } public virtual PropertyDescriptorCollection GetChildProperties(object instance, System.Attribute[] filter) { if (instance == null) { return TypeDescriptor.GetProperties(PropertyType, filter); } return TypeDescriptor.GetProperties(instance, filter); } public virtual object GetEditor(System.Type editorBaseType) { object obj = null; AttributeCollection attributes = Attributes; if (_editorTypes != null) { for (int i = 0; i < _editorCount; i++) { if (_editorTypes[i] == editorBaseType) { return _editors[i]; } } } if (obj == null) { if (obj == null) { obj = TypeDescriptor.GetEditor(PropertyType, editorBaseType); } if (_editorTypes == null) { _editorTypes = new System.Type[5]; _editors = new object[5]; } if (_editorCount >= _editorTypes.Length) { System.Type[] array = new System.Type[_editorTypes.Length * 2]; object[] array2 = new object[_editors.Length * 2]; System.Array.Copy((System.Array)_editorTypes, (System.Array)array, _editorTypes.Length); System.Array.Copy((System.Array)_editors, (System.Array)array2, _editors.Length); _editorTypes = array; _editors = array2; } _editorTypes[_editorCount] = editorBaseType; _editors[_editorCount++] = obj; } return obj; } public override int GetHashCode() { return NameHashCode ^ ((object)PropertyType).GetHashCode(); } protected override object GetInvocationTarget(System.Type type, object instance) { object obj = base.GetInvocationTarget(type, instance); if (obj is ICustomTypeDescriptor customTypeDescriptor) { obj = customTypeDescriptor.GetPropertyOwner(this); } return obj; } protected System.Type GetTypeFromName(string typeName) { if (typeName == null || typeName.Length == 0) { return null; } System.Type type = System.Type.GetType(typeName); System.Type type2 = null; if (ComponentType != null && (type == null || IntrospectionExtensions.GetTypeInfo(ComponentType).Assembly.FullName.Equals(IntrospectionExtensions.GetTypeInfo(type).Assembly.FullName))) { int num = typeName.IndexOf(','); if (num != -1) { typeName = typeName.Substring(0, num); } type2 = IntrospectionExtensions.GetTypeInfo(ComponentType).Assembly.GetType(typeName); } return type2 ?? type; } public abstract object GetValue(object component); protected virtual void OnValueChanged(object component, EventArgs e) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) if (component != null && _valueChangedHandlers != null) { EventHandler val = (EventHandler)_valueChangedHandlers[component]; if ((int)val != 0) { val.Invoke(component, e); } } } public virtual void RemoveValueChanged(object component, EventHandler handler) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Expected O, but got Unknown if (component == null) { throw new ArgumentNullException("component"); } if (handler == null) { throw new ArgumentNullException("handler"); } if (_valueChangedHandlers != null) { EventHandler val = (EventHandler)_valueChangedHandlers[component]; val = (EventHandler)System.Delegate.Remove((System.Delegate)(object)val, (System.Delegate)(object)handler); if (val != null) { _valueChangedHandlers[component] = val; } else { _valueChangedHandlers.Remove(component); } } } protected internal EventHandler GetValueChangedHandler(object component) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown if (component != null && _valueChangedHandlers != null) { return (EventHandler)_valueChangedHandlers[component]; } return null; } public abstract void ResetValue(object component); public abstract void SetValue(object component, object value); public abstract bool ShouldSerializeValue(object component); } public class SByteConverter : BaseNumberConverter { internal override System.Type TargetType => typeof(sbyte); internal override object FromString(string value, int radix) { return Convert.ToSByte(value, radix); } internal override object FromString(string value, NumberFormatInfo formatInfo) { return sbyte.Parse(value, (NumberStyles)7, (IFormatProvider)(object)formatInfo); } internal override object FromString(string value, CultureInfo culture) { return sbyte.Parse(value, (IFormatProvider)(object)culture); } internal override string ToString(object value, NumberFormatInfo formatInfo) { return ((sbyte)value).ToString("G", (IFormatProvider)(object)formatInfo); } } public class SingleConverter : BaseNumberConverter { internal override bool AllowHex => false; internal override System.Type TargetType => typeof(float); internal override object FromString(string value, int radix) { return Convert.ToSingle(value, (IFormatProvider)(object)CultureInfo.CurrentCulture); } internal override object FromString(string value, NumberFormatInfo formatInfo) { return float.Parse(value, (NumberStyles)167, (IFormatProvider)(object)formatInfo); } internal override object FromString(string value, CultureInfo culture) { return float.Parse(value, (IFormatProvider)(object)culture); } internal override string ToString(object value, NumberFormatInfo formatInfo) { return ((float)value).ToString("R", (IFormatProvider)(object)formatInfo); } } public class StringConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType) { if (sourceType != typeof(string)) { return base.CanConvertFrom(context, sourceType); } return true; } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string) { return (string)value; } if (value == null) { return string.Empty; } return base.ConvertFrom(context, culture, value); } } public class TimeSpanConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType) { if (sourceType != typeof(string)) { return base.CanConvertFrom(context, sourceType); } return true; } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { return base.CanConvertTo(context, destinationType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { //IL_0021: Expected O, but got Unknown //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) if (value is string text) { string text2 = text.Trim(); try { return TimeSpan.Parse(text2, (IFormatProvider)(object)culture); } catch (FormatException val) { FormatException val2 = val; throw new FormatException(System.SR.Format(System.SR.ConvertInvalidPrimitive, (string)value, "TimeSpan"), (System.Exception)(object)val2); } } return base.ConvertFrom(context, culture, value); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) if (destinationType == null) { throw new ArgumentNullException("destinationType"); } return base.ConvertTo(context, culture, value, destinationType); } } public class TypeConverter { protected abstract class SimplePropertyDescriptor : PropertyDescriptor { private System.Type _componentType; private System.Type _propertyType; public override System.Type ComponentType => _componentType; public override bool IsReadOnly => Attributes.Contains((System.Attribute)(object)ReadOnlyAttribute.Yes); public override System.Type PropertyType => _propertyType; protected SimplePropertyDescriptor(System.Type componentType, string name, System.Type propertyType) : this(componentType, name, propertyType, new System.Attribute[0]) { } protected SimplePropertyDescriptor(System.Type componentType, string name, System.Type propertyType, System.Attribute[] attributes) : base(name, attributes) { _componentType = componentType; _propertyType = propertyType; } public override bool CanResetValue(object component) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown DefaultValueAttribute val = (DefaultValueAttribute)Attributes[typeof(DefaultValueAttribute)]; if (val == null) { return false; } return val.Value.Equals(GetValue(component)); } public override void ResetValue(object component) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown DefaultValueAttribute val = (DefaultValueAttribute)Attributes[typeof(DefaultValueAttribute)]; if (val != null) { SetValue(component, val.Value); } } public override bool ShouldSerializeValue(object component) { return false; } } [DefaultMember("Item")] public class StandardValuesCollection : System.Collections.ICollection, System.Collections.IEnumerable { private System.Collections.ICollection _values; private System.Array _valueArray; public int Count { get { if (_valueArray != null) { return _valueArray.Length; } return _values.Count; } } public object this[int index] { get { if (_valueArray != null) { return _valueArray.GetValue(index); } if (_values is System.Collections.IList list) { return list[index]; } _valueArray = new object[_values.Count]; _values.CopyTo(_valueArray, 0); return _valueArray.GetValue(index); } } bool System.Collections.ICollection.IsSynchronized => false; object System.Collections.ICollection.SyncRoot => null; public StandardValuesCollection(System.Collections.ICollection values) { if (values == null) { values = (System.Collections.ICollection)(object)new object[0]; } if (values is System.Array valueArray) { _valueArray = valueArray; } _values = values; } public void CopyTo(System.Array array, int index) { _values.CopyTo(array, index); } public System.Collections.IEnumerator GetEnumerator() { return ((System.Collections.IEnumerable)_values).GetEnumerator(); } } public bool CanConvertFrom(System.Type sourceType) { return CanConvertFrom(null, sourceType); } public virtual bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType) { return false; } public bool CanConvertTo(System.Type destinationType) { return CanConvertTo(null, destinationType); } public virtual bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { return destinationType == typeof(string); } public object ConvertFrom(object value) { return ConvertFrom(null, CultureInfo.CurrentCulture, value); } public virtual object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { throw GetConvertFromException(value); } public object ConvertFromInvariantString(string text) { return ConvertFromString(null, CultureInfo.InvariantCulture, text); } public object ConvertFromInvariantString(ITypeDescriptorContext context, string text) { return ConvertFromString(context, CultureInfo.InvariantCulture, text); } public object ConvertFromString(string text) { return ConvertFrom(null, null, text); } public object ConvertFromString(ITypeDescriptorContext context, string text) { return ConvertFrom(context, CultureInfo.CurrentCulture, text); } public object ConvertFromString(ITypeDescriptorContext context, CultureInfo culture, string text) { return ConvertFrom(context, culture, text); } public object ConvertTo(object value, System.Type destinationType) { return ConvertTo(null, null, value, destinationType); } public virtual object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) if (destinationType == null) { throw new ArgumentNullException("destinationType"); } if (destinationType == typeof(string)) { if (value == null) { return string.Empty; } if (culture != null && culture != CultureInfo.CurrentCulture && value is System.IFormattable formattable) { return formattable.ToString((string)null, (IFormatProvider)(object)culture); } return value.ToString(); } throw GetConvertToException(value, destinationType); } public string ConvertToInvariantString(object value) { return ConvertToString(null, CultureInfo.InvariantCulture, value); } public string ConvertToInvariantString(ITypeDescriptorContext context, object value) { return ConvertToString(context, CultureInfo.InvariantCulture, value); } public string ConvertToString(object value) { return (string)ConvertTo(null, CultureInfo.CurrentCulture, value, typeof(string)); } public string ConvertToString(ITypeDescriptorContext context, object value) { return (string)ConvertTo(context, CultureInfo.CurrentCulture, value, typeof(string)); } public string ConvertToString(ITypeDescriptorContext context, CultureInfo culture, object value) { return (string)ConvertTo(context, culture, value, typeof(string)); } public object CreateInstance(IDictionary propertyValues) { return CreateInstance(null, propertyValues); } public virtual object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues) { return null; } protected System.Exception GetConvertFromException(object value) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(System.SR.Format(p2: (value != null) ? value.GetType().FullName : System.SR.Null, resourceFormat: System.SR.ConvertFromException, p1: base.GetType().Name)); } protected System.Exception GetConvertToException(object value, System.Type destinationType) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(System.SR.Format(p2: (value != null) ? value.GetType().FullName : System.SR.Null, resourceFormat: System.SR.ConvertToException, p1: base.GetType().Name, p3: destinationType.FullName)); } public bool GetCreateInstanceSupported() { return GetCreateInstanceSupported(null); } public virtual bool GetCreateInstanceSupported(ITypeDescriptorContext context) { return false; } public PropertyDescriptorCollection GetProperties(object value) { return GetProperties(null, value); } public PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value) { return GetProperties(context, value, new System.Attribute[1] { (System.Attribute)(object)BrowsableAttribute.Yes }); } public virtual PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, System.Attribute[] attributes) { return null; } public bool GetPropertiesSupported() { return GetPropertiesSupported(null); } public virtual bool GetPropertiesSupported(ITypeDescriptorContext context) { return false; } public System.Collections.ICollection GetStandardValues() { return GetStandardValues(null); } public virtual StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return null; } public bool GetStandardValuesExclusive() { return GetStandardValuesExclusive(null); } public virtual bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; } public bool GetStandardValuesSupported() { return GetStandardValuesSupported(null); } public virtual bool GetStandardValuesSupported(ITypeDescriptorContext context) { return false; } public bool IsValid(object value) { return IsValid(null, value); } public virtual bool IsValid(ITypeDescriptorContext context, object value) { bool result = true; try { if (value == null || CanConvertFrom(context, value.GetType())) { ConvertFrom(context, CultureInfo.InvariantCulture, value); } else { result = false; } } catch { result = false; } return result; } protected PropertyDescriptorCollection SortProperties(PropertyDescriptorCollection props, string[] names) { props.Sort(names); return props; } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public sealed class TypeConverterAttribute : System.Attribute { private readonly string _typeName; public static readonly TypeConverterAttribute Default = new TypeConverterAttribute(); public string ConverterTypeName => _typeName; public TypeConverterAttribute() { _typeName = string.Empty; } public TypeConverterAttribute(System.Type type) { _typeName = type.AssemblyQualifiedName; } public TypeConverterAttribute(string typeName) { _typeName = typeName; } public bool Equals(object obj) { if (obj is TypeConverterAttribute typeConverterAttribute) { return typeConverterAttribute.ConverterTypeName == _typeName; } return false; } public int GetHashCode() { return ((object)_typeName).GetHashCode(); } } public abstract class TypeListConverter : TypeConverter { private readonly System.Type[] _types; private StandardValuesCollection _values; protected TypeListConverter(System.Type[] types) { _types = types; } public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType) { if (sourceType == typeof(string)) { return true; } return base.CanConvertFrom(context, sourceType); } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { return base.CanConvertTo(context, destinationType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string) { System.Type[] types = _types; foreach (System.Type type in types) { if (value.Equals((object)type.FullName)) { return type; } } } return base.ConvertFrom(context, culture, value); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) if (destinationType == null) { throw new ArgumentNullException("destinationType"); } if (destinationType == typeof(string)) { if (value == null) { return System.SR.none; } return ((System.Type)value).FullName; } return base.ConvertTo(context, culture, value, destinationType); } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { if (_values == null) { object[] array; if (_types != null) { array = new object[_types.Length]; System.Array.Copy((System.Array)_types, (System.Array)array, _types.Length); } else { array = null; } _values = new StandardValuesCollection((System.Collections.ICollection)(object)array); } return _values; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } } public class UInt16Converter : BaseNumberConverter { internal override System.Type TargetType => typeof(ushort); internal override object FromString(string value, int radix) { return Convert.ToUInt16(value, radix); } internal override object FromString(string value, NumberFormatInfo formatInfo) { return ushort.Parse(value, (NumberStyles)7, (IFormatProvider)(object)formatInfo); } internal override object FromString(string value, CultureInfo culture) { return ushort.Parse(value, (IFormatProvider)(object)culture); } internal override string ToString(object value, NumberFormatInfo formatInfo) { return ((ushort)value).ToString("G", (IFormatProvider)(object)formatInfo); } } public class UInt32Converter : BaseNumberConverter { internal override System.Type TargetType => typeof(uint); internal override object FromString(string value, int radix) { return Convert.ToUInt32(value, radix); } internal override object FromString(string value, NumberFormatInfo formatInfo) { return uint.Parse(value, (NumberStyles)7, (IFormatProvider)(object)formatInfo); } internal override object FromString(string value, CultureInfo culture) { return uint.Parse(value, (IFormatProvider)(object)culture); } internal override string ToString(object value, NumberFormatInfo formatInfo) { return ((uint)value).ToString("G", (IFormatProvider)(object)formatInfo); } } public class UInt64Converter : BaseNumberConverter { internal override System.Type TargetType => typeof(ulong); internal override object FromString(string value, int radix) { return Convert.ToUInt64(value, radix); } internal override object FromString(string value, NumberFormatInfo formatInfo) { return ulong.Parse(value, (NumberStyles)7, (IFormatProvider)(object)formatInfo); } internal override object FromString(string value, CultureInfo culture) { return ulong.Parse(value, (IFormatProvider)(object)culture); } internal override string ToString(object value, NumberFormatInfo formatInfo) { return ((ulong)value).ToString("G", (IFormatProvider)(object)formatInfo); } } [DefaultMember("Item")] public class AttributeCollection : System.Collections.ICollection, System.Collections.IEnumerable { private struct AttributeEntry { public System.Type type; public int index; } public static readonly AttributeCollection Empty = new AttributeCollection((System.Attribute[])null); private static Hashtable s_defaultAttributes; private readonly System.Attribute[] _attributes; private static readonly object s_internalSyncObject = new object(); private const int FOUND_TYPES_LIMIT = 5; private AttributeEntry[] _foundAttributeTypes; private int _index; protected virtual System.Attribute[] Attributes => _attributes; public int Count => Attributes.Length; public virtual System.Attribute this[int index] => Attributes[index]; public virtual System.Attribute this[System.Type attributeType] { get { lock (s_internalSyncObject) { if (_foundAttributeTypes == null) { _foundAttributeTypes = new AttributeEntry[5]; } int i; for (i = 0; i < 5; i++) { if (_foundAttributeTypes[i].type == attributeType) { int index = _foundAttributeTypes[i].index; if (index != -1) { return Attributes[index]; } return GetDefaultAttribute(attributeType); } if (_foundAttributeTypes[i].type == null) { break; } } i = _index++; if (_index >= 5) { _index = 0; } _foundAttributeTypes[i].type = attributeType; int num = Attributes.Length; for (int j = 0; j < num; j++) { System.Attribute attribute = Attributes[j]; System.Type type = ((object)attribute).GetType(); if (type == attributeType) { _foundAttributeTypes[i].index = j; return attribute; } } for (int k = 0; k < num; k++) { System.Attribute attribute2 = Attributes[k]; System.Type type2 = ((object)attribute2).GetType(); if (IntrospectionExtensions.GetTypeInfo(attributeType).IsAssignableFrom(IntrospectionExtensions.GetTypeInfo(type2))) { _foundAttributeTypes[i].index = k; return attribute2; } } _foundAttributeTypes[i].index = -1; return GetDefaultAttribute(attributeType); } } } bool System.Collections.ICollection.IsSynchronized => false; object System.Collections.ICollection.SyncRoot => null; public AttributeCollection(params System.Attribute[] attributes) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) _attributes = attributes ?? new System.Attribute[0]; for (int i = 0; i < _attributes.Length; i++) { if (_attributes[i] == null) { throw new ArgumentNullException("attributes"); } } } protected AttributeCollection() { } public static AttributeCollection FromExisting(AttributeCollection existing, params System.Attribute[] newAttributes) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) if (existing == null) { throw new ArgumentNullException("existing"); } if (newAttributes == null) { newAttributes = new System.Attribute[0]; } System.Attribute[] array = new System.Attribute[existing.Count + newAttributes.Length]; int count = existing.Count; existing.CopyTo(array, 0); for (int i = 0; i < newAttributes.Length; i++) { if (newAttributes[i] == null) { throw new ArgumentNullException("newAttributes"); } bool flag = false; for (int j = 0; j < existing.Count; j++) { if (array[j].GetTypeId().Equals(newAttributes[i].GetTypeId())) { flag = true; array[j] = newAttributes[i]; break; } } if (!flag) { array[count++] = newAttributes[i]; } } System.Attribute[] array2 = null; if (count < array.Length) { array2 = new System.Attribute[count]; System.Array.Copy((System.Array)array, 0, (System.Array)array2, 0, count); } else { array2 = array; } return new AttributeCollection(array2); } public bool Contains(System.Attribute attribute) { return ((object)this[((object)attribute).GetType()])?.Equals((object)attribute) ?? false; } public bool Contains(System.Attribute[] attributes) { if (attributes == null) { return true; } for (int i = 0; i < attributes.Length; i++) { if (!Contains(attributes[i])) { return false; } } return true; } protected System.Attribute GetDefaultAttribute(System.Type attributeType) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown lock (s_internalSyncObject) { if (s_defaultAttributes == null) { s_defaultAttributes = new Hashtable(); } if (s_defaultAttributes.ContainsKey((object)attributeType)) { return (System.Attribute)s_defaultAttributes[(object)attributeType]; } System.Attribute attribute = null; System.Type reflectionType = TypeDescriptor.GetReflectionType(attributeType); FieldInfo field = IntrospectionExtensions.GetTypeInfo(reflectionType).GetField("Default", (BindingFlags)1048); if (field != null && field.IsStatic) { attribute = (System.Attribute)field.GetValue((object)null); } else { ConstructorInfo constructor = IntrospectionExtensions.GetTypeInfo(IntrospectionExtensions.GetTypeInfo(reflectionType).UnderlyingSystemType).GetConstructor(new System.Type[0]); if (constructor != null) { attribute = (System.Attribute)constructor.Invoke(new object[0]); if (!attribute.IsDefaultAttribute()) { attribute = null; } } } s_defaultAttributes[(object)attributeType] = attribute; return attribute; } } public System.Collections.IEnumerator GetEnumerator() { return ((System.Array)Attributes).GetEnumerator(); } public bool Matches(System.Attribute attribute) { for (int i = 0; i < Attributes.Length; i++) { if (Attributes[i].Match(attribute)) { return true; } } return false; } public bool Matches(System.Attribute[] attributes) { for (int i = 0; i < attributes.Length; i++) { if (!Matches(attributes[i])) { return false; } } return true; } public void CopyTo(System.Array array, int index) { System.Array.Copy((System.Array)Attributes, 0, array, index, Attributes.Length); } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public class AttributeProviderAttribute : System.Attribute { private readonly string _typeName; private readonly string _propertyName; public string TypeName => _typeName; public string PropertyName => _propertyName; public AttributeProviderAttribute(string typeName) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) if (typeName == null) { throw new ArgumentNullException("typeName"); } _typeName = typeName; } public AttributeProviderAttribute(string typeName, string propertyName) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) if (typeName == null) { throw new ArgumentNullException("typeName"); } if (propertyName == null) { throw new ArgumentNullException("propertyName"); } _typeName = typeName; _propertyName = propertyName; } public AttributeProviderAttribute(System.Type type) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) if (type == null) { throw new ArgumentNullException("type"); } _typeName = type.AssemblyQualifiedName; } } public delegate void CancelEventHandler(object sender, CancelEventArgs e); public enum CollectionChangeAction { Add = 1, Remove, Refresh } public class CollectionChangeEventArgs : EventArgs { private readonly CollectionChangeAction _action; private readonly object _element; public virtual CollectionChangeAction Action => _action; public virtual object Element => _element; public CollectionChangeEventArgs(CollectionChangeAction action, object element) { _action = action; _element = element; } } public delegate void CollectionChangeEventHandler(object sender, CollectionChangeEventArgs e); internal static class ComponentModelExtensions { private static readonly Dictionary<System.Type, Func<System.Attribute, object>> s_typeId; private static readonly Dictionary<System.Type, Func<System.Attribute, bool>> s_defaultAttributes; public static bool IsDefaultAttribute(this System.Attribute attribute) { Func<System.Attribute, bool> val = default(Func<System.Attribute, bool>); if (s_defaultAttributes.TryGetValue(((object)attribute).GetType(), ref val)) { return val.Invoke(attribute); } return false; } public static object GetTypeId(this System.Attribute attribute) { Func<System.Attribute, object> val = default(Func<System.Attribute, object>); if (!s_typeId.TryGetValue(((object)attribute).GetType(), ref val)) { return ((object)attribute).GetType(); } return val.Invoke(attribute); } public static bool Match(this System.Attribute attribute, object obj) { return ((object)attribute).Equals(obj); } static ComponentModelExtensions() { Dictionary<System.Type, Func<System.Attribute, object>> val = new Dictionary<System.Type, Func<System.Attribute, object>>(); val.Add(typeof(DesignerCategoryAttribute), (Func<System.Attribute, object>)((System.Attribute attr) => ((object)attr).GetType().FullName + ((DesignerCategoryAttribute)attr).Category)); val.Add(typeof(ProvidePropertyAttribute), (Func<System.Attribute, object>)((System.Attribute attr) => ((object)attr).GetType().FullName + ((ProvidePropertyAttribute)attr).PropertyName)); s_typeId = val; Dictionary<System.Type, Func<System.Attribute, bool>> val2 = new Dictionary<System.Type, Func<System.Attribute, bool>>(); val2.Add(typeof(BrowsableAttribute), (Func<System.Attribute, bool>)((System.Attribute attr) => ((object)attr).Equals((object)BrowsableAttribute.Default))); val2.Add(typeof(CategoryAttribute), (Func<System.Attribute, bool>)((System.Attribute attr) => ((CategoryAttribute)attr).Category.Equals(CategoryAttribute.Default.Category))); val2.Add(typeof(DescriptionAttribute), (Func<System.Attribute, bool>)((System.Attribute attr) => ((object)attr).Equals((object)DescriptionAttribute.Default))); val2.Add(typeof(DesignOnlyAttribute), (Func<System.Attribute, bool>)((System.Attribute attr) => ((DesignOnlyAttribute)attr).IsDesignOnly == DesignOnlyAttribute.Default.IsDesignOnly)); val2.Add(typeof(DisplayNameAttribute), (Func<System.Attribute, bool>)((System.Attribute attr) => ((object)attr).Equals((object)DisplayNameAttribute.Default))); val2.Add(typeof(ImmutableObjectAttribute), (Func<System.Attribute, bool>)((System.Attribute attr) => ((object)attr).Equals((object)ImmutableObjectAttribute.Default))); val2.Add(typeof(LocalizableAttribute), (Func<System.Attribute, bool>)((System.Attribute attr) => ((LocalizableAttribute)attr).IsLocalizable == LocalizableAttribute.Default.IsLocalizable)); val2.Add(typeof(MergablePropertyAttribute), (Func<System.Attribute, bool>)((System.Attribute attr) => ((object)attr).Equals((object)MergablePropertyAttribute.Default))); val2.Add(typeof(NotifyParentPropertyAttribute), (Func<System.Attribute, bool>)((System.Attribute attr) => ((object)attr).Equals((object)NotifyParentPropertyAttribute.Default))); val2.Add(typeof(ParenthesizePropertyNameAttribute), (Func<System.Attribute, bool>)((System.Attribute attr) => ((object)attr).Equals((object)ParenthesizePropertyNameAttribute.Default))); val2.Add(typeof(ReadOnlyAttribute), (Func<System.Attribute, bool>)((System.Attribute attr) => ((ReadOnlyAttribute)attr).IsReadOnly == ReadOnlyAttribute.Default.IsReadOnly)); val2.Add(typeof(RefreshPropertiesAttribute), (Func<System.Attribute, bool>)((System.Attribute attr) => ((object)attr).Equals((object)RefreshPropertiesAttribute.Default))); val2.Add(typeof(DesignerSerializationVisibilityAttribute), (Func<System.Attribute, bool>)((System.Attribute attr) => ((object)attr).Equals((object)DesignerSerializationVisibilityAttribute.Default))); val2.Add(typeof(ExtenderProvidedPropertyAttribute), (Func<System.Attribute, bool>)((System.Attribute attr) => ((ExtenderProvidedPropertyAttribute)attr).ReceiverType == null)); val2.Add(typeof(DesignerCategoryAttribute), (Func<System.Attribute, bool>)((System.Attribute attr) => ((object)attr).Equals((object)DesignerCategoryAttribute.Default.Category))); s_defaultAttributes = val2; } } public abstract class CustomTypeDescriptor : ICustomTypeDescriptor { private readonly ICustomTypeDescriptor _parent; protected CustomTypeDescriptor() { } protected CustomTypeDescriptor(ICustomTypeDescriptor parent) { _parent = parent; } public virtual AttributeCollection GetAttributes() { if (_parent != null) { return _parent.GetAttributes(); } return AttributeCollection.Empty; } public virtual string GetClassName() { if (_parent != null) { return _parent.GetClassName(); } return null; } public virtual string GetComponentName() { if (_parent != null) { return _parent.GetComponentName(); } return null; } public virtual TypeConverter GetConverter() { if (_parent != null) { return _parent.GetConverter(); } return new TypeConverter(); } public virtual EventDescriptor GetDefaultEvent() { if (_parent != null) { return _parent.GetDefaultEvent(); } return null; } public virtual PropertyDescriptor GetDefaultProperty() { if (_parent != null) { return _parent.GetDefaultProperty(); } return null; } public virtual object GetEditor(System.Type editorBaseType) { if (_parent != null) { return _parent.GetEditor(editorBaseType); } return null; } public virtual EventDescriptorCollection GetEvents() { if (_parent != null) { return _parent.GetEvents(); } return EventDescriptorCollection.Empty; } public virtual EventDescriptorCollection GetEvents(System.Attribute[] attributes) { if (_parent != null) { return _parent.GetEvents(attributes); } return EventDescriptorCollection.Empty; } public virtual PropertyDescriptorCollection GetProperties() { if (_parent != null) { return _parent.GetProperties(); } return PropertyDescriptorCollection.Empty; } public virtual PropertyDescriptorCollection GetProperties(System.Attribute[] attributes) { if (_parent != null) { return _parent.GetProperties(attributes); } return PropertyDescriptorCollection.Empty; } public virtual object GetPropertyOwner(PropertyDescriptor pd) { if (_parent != null) { return _parent.GetPropertyOwner(pd); } return null; } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public sealed class DefaultEventAttribute : System.Attribute { private readonly string _name; public static readonly DefaultEventAttribute Default = new DefaultEventAttribute(null); public string Name => _name; public DefaultEventAttribute(string name) { _name = name; } public bool Equals(object obj) { if (obj is DefaultEventAttribute defaultEventAttribute) { return defaultEventAttribute.Name == _name; } return false; } public int GetHashCode() { return base.GetHashCode(); } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public sealed class DefaultPropertyAttribute : System.Attribute { private readonly string _name; public static readonly DefaultPropertyAttribute Default = new DefaultPropertyAttribute(null); public string Name => _name; public DefaultPropertyAttribute(string name) { _name = name; } public bool Equals(object obj) { if (obj is DefaultPropertyAttribute defaultPropertyAttribute) { return defaultPropertyAttribute.Name == _name; } return false; } public int GetHashCode() { return base.GetHashCode(); } } internal sealed class DelegatingTypeDescriptionProvider : TypeDescriptionProvider { private readonly System.Type _type; internal TypeDescriptionProvider Provider => TypeDescriptor.GetProviderRecursive(_type); internal DelegatingTypeDescriptionProvider(System.Type type) { _type = type; } public override object CreateInstance(IServiceProvider provider, System.Type objectType, System.Type[] argTypes, object[] args) { return Provider.CreateInstance(provider, objectType, argTypes, args); } public override IDictionary GetCache(object instance) { return Provider.GetCache(instance); } public override string GetFullComponentName(object component) { return Provider.GetFullComponentName(component); } public override ICustomTypeDescriptor GetExtendedTypeDescriptor(object instance) { return Provider.GetExtendedTypeDescriptor(instance); } protected internal override IExtenderProvider[] GetExtenderProviders(object instance) { return Provider.GetExtenderProviders(instance); } public override System.Type GetReflectionType(System.Type objectType, object instance) { return Provider.GetReflectionType(objectType, instance); } public override System.Type GetRuntimeType(System.Type objectType) { return Provider.GetRuntimeType(objectType); } public override ICustomTypeDescriptor GetTypeDescriptor(System.Type objectType, object instance) { return Provider.GetTypeDescriptor(objectType, instance); } public override bool IsSupportedType(System.Type type) { return Provider.IsSupportedType(type); } } public abstract class EventDescriptor : MemberDescriptor { public abstract System.Type ComponentType { get; } public abstract System.Type EventType { get; } public abstract bool IsMulticast { get; } protected EventDescriptor(string name, System.Attribute[] attrs) : base(name, attrs) { } protected EventDescriptor(MemberDescriptor descr) : base(descr) { } protected EventDescriptor(MemberDescriptor descr, System.Attribute[] attrs) : base(descr, attrs) { } public abstract void AddEventHandler(object component, System.Delegate value); public abstract void RemoveEventHandler(object component, System.Delegate value); } [DefaultMember("Item")] public class EventDescriptorCollection : System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList { private class ArraySubsetEnumerator : System.Collections.IEnumerator { private readonly System.Array _array; private readonly int _total; private int _current; public object Current { get { //IL_0009: Unknown result type (might be due to invalid IL or missing references) if (_current == -1) { throw new InvalidOperationException(); } return _array.GetValue(_current); } } public ArraySubsetEnumerator(System.Array array, int count) { _array = array; _total = count; _current = -1; } public bool MoveNext() { if (_current < _total - 1) { _current++; return true; } return false; } public void Reset() { _current = -1; } } private EventDescriptor[] _events; private string[] _namedSort; private readonly IComparer _comparer; private bool _eventsOwned; private bool _needSort; private int _eventCount; private readonly bool _readOnly; public static readonly EventDescriptorCollection Empty = new EventDescriptorCollection(null, readOnly: true); public int Count => _eventCount; public virtual EventDescriptor this[int index] { get { //IL_0009: Unknown result type (might be due to invalid IL or missing references) if (index >= _eventCount) { throw new IndexOutOfRangeException(); } EnsureEventsOwned(); return _events[index]; } } public virtual EventDescriptor this[string name] => Find(name, ignoreCase: false); bool System.Collections.ICollection.IsSynchronized => false; object System.Collections.ICollection.SyncRoot => null; object System.Collections.IList.this[int index] { get { return this[index]; } set { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(); } if (index >= _eventCount) { throw new IndexOutOfRangeException(); } EnsureEventsOwned(); _events[index] = (EventDescriptor)value; } } bool System.Collections.IList.IsReadOnly => _readOnly; bool System.Collections.IList.IsFixedSize => _readOnly; public EventDescriptorCollection(EventDescriptor[] events) { _events = events; if (events == null) { _events = new EventDescriptor[0]; _eventCount = 0; } else { _eventCount = _events.Length; } _eventsOwned = true; } public EventDescriptorCollection(EventDescriptor[] events, bool readOnly) : this(events) { _readOnly = readOnly; } private EventDescriptorCollection(EventDescriptor[] events, int eventCount, string[] namedSort, IComparer comparer) { _eventsOwned = false; if (namedSort != null) { _namedSort = (string[])((System.Array)namedSort).Clone(); } _comparer = comparer; _events = events; _eventCount = eventCount; _needSort = true; } public int Add(EventDescriptor value) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(); } EnsureSize(_eventCount + 1); _events[_eventCount++] = value; return _eventCount - 1; } public void Clear() { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(); } _eventCount = 0; } public bool Contains(EventDescriptor value) { return IndexOf(value) >= 0; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { EnsureEventsOwned(); System.Array.Copy((System.Array)_events, 0, array, index, Count); } private void EnsureEventsOwned() { if (!_eventsOwned) { _eventsOwned = true; if (_events != null) { EventDescriptor[] array = new EventDescriptor[Count]; System.Array.Copy((System.Array)_events, 0, (System.Array)array, 0, Count); _events = array; } } if (_needSort) { _needSort = false; InternalSort(_namedSort); } } private void EnsureSize(int sizeNeeded) { if (sizeNeeded > _events.Length) { if (_events == null || _events.Length == 0) { _eventCount = 0; _events = new EventDescriptor[sizeNeeded]; return; } EnsureEventsOwned(); int num = Math.Max(sizeNeeded, _events.Length * 2); EventDescriptor[] array = new EventDescriptor[num]; System.Array.Copy((System.Array)_events, 0, (System.Array)array, 0, _eventCount); _events = array; } } public virtual EventDescriptor Find(string name, bool ignoreCase) { EventDescriptor result = null; if (ignoreCase) { for (int i = 0; i < Count; i++) { if (string.Equals(_events[i].Name, name, (StringComparison)5)) { result = _events[i]; break; } } } else { for (int j = 0; j < Count; j++) { if (string.Equals(_events[j].Name, name, (StringComparison)4)) { result = _events[j]; break; } } } return result; } public int IndexOf(EventDescriptor value) { return System.Array.IndexOf<EventDescriptor>(_events, value, 0, _eventCount); } public void Insert(int index, EventDescriptor value) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(); } EnsureSize(_eventCount + 1); if (index < _eventCount) { System.Array.Copy((System.Array)_events, index, (System.Array)_events, index + 1, _eventCount - index); } _events[index] = value; _eventCount++; } public void Remove(EventDescriptor value) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(); } int num = IndexOf(value); if (num != -1) { RemoveAt(num); } } public void RemoveAt(int index) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (_readOnly) { throw new NotSupportedException(); } if (index < _eventCount - 1) { System.Array.Copy((System.Array)_events, index + 1, (System.Array)_events, index, _eventCount - index - 1); } _events[_eventCount - 1] = null; _eventCount--; } public System.Collections.IEnumerator GetEnumerator() { if (_events.Length == _eventCount) { return ((System.Array)_events).GetEnumerator(); } return new ArraySubsetEnumerator(_events, _eventCount); } public virtual EventDescriptorCollection Sort() { return new EventDescriptorCollection(_events, _eventCount, _namedSort, _comparer); } public virtual EventDescriptorCollection Sort(string[] names) { return new EventDescriptorCollection(_events, _eventCount, names, _comparer); } public virtual EventDescriptorCollection Sort(string[] names, IComparer comparer) { return new EventDescriptorCollection(_events, _eventCount, names, comparer); } public virtual EventDescriptorCollection Sort(IComparer comparer) { return new EventDescriptorCollection(_events, _eventCount, _namedSort, comparer); } protected void InternalSort(string[] names) { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Expected O, but got Unknown if (_events == null || _events.Length == 0) { return; } InternalSort(_comparer); if (names == null || names.Length == 0) { return; } ArrayList val = new ArrayList((System.Collections.ICollection)(object)_events); int num = 0; int num2 = _events.Length; for (int i = 0; i < names.Length; i++) { for (int j = 0; j < num2; j++) { EventDescriptor eventDescriptor = (EventDescriptor)val[j]; if (eventDescriptor != null && eventDescriptor.Name.Equals(names[i])) { _events[num++] = eventDescriptor; val[j] = null; break; } } } for (int k = 0; k < num2; k++) { if (val[k] != null) { _events[num++] = (EventDescriptor)val[k]; } } } protected void InternalSort(IComparer sorter) { if (sorter == null) { TypeDescriptor.SortDescriptorArray(this); } else { System.Array.Sort((System.Array)_events, sorter); } } int System.Collections.IList.Add(object value) { return Add((EventDescriptor)value); } bool System.Collections.IList.Contains(object value) { return Contains((EventDescriptor)value); } int System.Collections.IList.IndexOf(object value) { return IndexOf((EventDescriptor)value); } void System.Collections.IList.Insert(int index, object value) { Insert(index, (EventDescriptor)value); } void System.Collections.IList.Remove(object value) { Remove((EventDescriptor)value); } } internal sealed class ExtendedPropertyDescriptor : PropertyDescriptor { private readonly ReflectPropertyDescriptor _extenderInfo; private readonly IExtenderProvider _provider; public override System.Type ComponentType => _extenderInfo.ComponentType; public override bool IsReadOnly => ((object)Attributes[typeof(ReadOnlyAttribute)]).Equals((object)ReadOnlyAttribute.Yes); public override System.Type PropertyType => _extenderInfo.ExtenderGetType(_provider); public override string DisplayName { get { string text = base.DisplayName; System.Attribute attribute = Attributes[typeof(DisplayNameAttribute)]; DisplayNameAttribute val = (DisplayNameAttribute)(object)((attribute is DisplayNameAttribute) ? attribute : null); if (val == null || ((System.Attribute)(object)val).IsDefaultAttribute()) { ISite site = MemberDescriptor.GetSite(_provider); if (site != null) { string name = site.Name; if (name != null && name.Length > 0) { text = string.Format(System.SR.MetaExtenderName, (object)text, (object)name); } } } return text; } } public ExtendedPropertyDescriptor(ReflectPropertyDescriptor extenderInfo, System.Type receiverType, IExtenderProvider provider, System.Attribute[] attributes) : base(extenderInfo, attributes) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected O, but got Unknown ArrayList val = new ArrayList((System.Collections.ICollection)(object)AttributeArray); val.Add((object)ExtenderProvidedPropertyAttribute.Create(extenderInfo, receiverType, provider)); if (extenderInfo.IsReadOnly) { val.Add((object)ReadOnlyAttribute.Yes); } System.Attribute[] array = new System.Attribute[val.Count]; val.CopyTo((System.Array)array, 0); AttributeArray = array; _extenderInfo = extenderInfo; _provider = provider; } public ExtendedPropertyDescriptor(PropertyDescriptor extender, System.Attribute[] attributes) : base(extender, attributes) { ExtenderProvidedPropertyAttribute extenderProvidedPropertyAttribute = extender.Attributes[typeof(ExtenderProvidedPropertyAttribute)] as ExtenderProvidedPropertyAttribute; ReflectPropertyDescriptor extenderInfo = extenderProvidedPropertyAttribute.ExtenderProperty as ReflectPropertyDescriptor; _extenderInfo = extenderInfo; _provider = extenderProvidedPropertyAttribute.Provider; } public override bool CanResetValue(object comp) { return _extenderInfo.ExtenderCanResetValue(_provider, comp); } public override object GetValue(object comp) { return _extenderInfo.ExtenderGetValue(_provider, comp); } public override void ResetValue(object comp) { _extenderInfo.ExtenderResetValue(_provider, comp, this); } public override void SetValue(object component, object value)
System.IO.FileSystem.Primitives.dll
Decompiled 5 days agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: AssemblyTitle("System.IO.FileSystem.Primitives")] [assembly: AssemblyDescription("System.IO.FileSystem.Primitives")] [assembly: AssemblyDefaultAlias("System.IO.FileSystem.Primitives")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyProduct("Microsoft® .NET Framework")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyFileVersion("4.6.24705.01")] [assembly: AssemblyInformationalVersion("4.6.24705.01. Commit Hash: 4d1af962ca0fede10beb01d197367c2f90e92c97")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyVersion("4.0.2.0")] namespace System.IO; [Flags] public enum FileAccess { Read = 1, Write = 2, ReadWrite = 3 } [Flags] public enum FileAttributes { ReadOnly = 1, Hidden = 2, System = 4, Directory = 0x10, Archive = 0x20, Device = 0x40, Normal = 0x80, Temporary = 0x100, SparseFile = 0x200, ReparsePoint = 0x400, Compressed = 0x800, Offline = 0x1000, NotContentIndexed = 0x2000, Encrypted = 0x4000, IntegrityStream = 0x8000, NoScrubData = 0x20000 } public enum FileMode { CreateNew = 1, Create, Open, OpenOrCreate, Truncate, Append } [Flags] public enum FileShare { None = 0, Read = 1, Write = 2, ReadWrite = 3, Delete = 4, Inheritable = 0x10 }
System.Linq.dll
Decompiled 5 days ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using FxResources.System.Linq; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyTitle("System.Linq")] [assembly: AssemblyDescription("System.Linq")] [assembly: AssemblyDefaultAlias("System.Linq")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyProduct("Microsoft® .NET Framework")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyFileVersion("4.6.24705.01")] [assembly: AssemblyInformationalVersion("4.6.24705.01. Commit Hash: 4d1af962ca0fede10beb01d197367c2f90e92c97")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyVersion("4.1.1.0")] namespace FxResources.System.Linq { internal static class SR { } } namespace System { internal static class SR { private static ResourceManager s_resourceManager; private const string s_resourcesName = "FxResources.System.Linq.SR"; private static ResourceManager ResourceManager { get { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown if (s_resourceManager == null) { s_resourceManager = new ResourceManager(ResourceType); } return s_resourceManager; } } internal static string EmptyEnumerable => GetResourceString("EmptyEnumerable", null); internal static string MoreThanOneElement => GetResourceString("MoreThanOneElement", null); internal static string MoreThanOneMatch => GetResourceString("MoreThanOneMatch", null); internal static string NoElements => GetResourceString("NoElements", null); internal static string NoMatch => GetResourceString("NoMatch", null); internal static System.Type ResourceType => typeof(FxResources.System.Linq.SR); [MethodImpl(8)] private static bool UsingResourceKeys() { return false; } internal static string GetResourceString(string resourceKey, string defaultString) { string text = null; try { text = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } if (defaultString != null && resourceKey.Equals(text, (StringComparison)4)) { return defaultString; } return text; } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", new object[2] { resourceFormat, p1 }); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", new object[3] { resourceFormat, p1, p2 }); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", new object[4] { resourceFormat, p1, p2, p3 }); } return string.Format(resourceFormat, p1, p2, p3); } } } namespace System.Linq { public static class Enumerable { private abstract class AppendPrependIterator<TSource> : Iterator<TSource>, IIListProvider<TSource>, System.Collections.Generic.IEnumerable<TSource>, System.Collections.IEnumerable { protected readonly System.Collections.Generic.IEnumerable<TSource> _source; protected System.Collections.Generic.IEnumerator<TSource> _enumerator; protected AppendPrependIterator(System.Collections.Generic.IEnumerable<TSource> source) { _source = source; } protected void GetSourceEnumerator() { _enumerator = _source.GetEnumerator(); } public abstract AppendPrependIterator<TSource> Append(TSource item); public abstract AppendPrependIterator<TSource> Prepend(TSource item); protected bool LoadFromEnumerator() { if (((System.Collections.IEnumerator)_enumerator).MoveNext()) { _current = _enumerator.Current; return true; } Dispose(); return false; } public override void Dispose() { if (_enumerator != null) { ((System.IDisposable)_enumerator).Dispose(); _enumerator = null; } base.Dispose(); } public abstract TSource[] ToArray(); public abstract List<TSource> ToList(); public abstract int GetCount(bool onlyIfCheap); } private class AppendPrepend1Iterator<TSource> : AppendPrependIterator<TSource> { private readonly TSource _item; private readonly bool _appending; public AppendPrepend1Iterator(System.Collections.Generic.IEnumerable<TSource> source, TSource item, bool appending) : base(source) { _item = item; _appending = appending; } public override Iterator<TSource> Clone() { return new AppendPrepend1Iterator<TSource>(_source, _item, _appending); } public override bool MoveNext() { switch (_state) { case 1: _state = 2; if (!_appending) { _current = _item; return true; } goto case 2; case 2: GetSourceEnumerator(); _state = 3; goto case 3; case 3: if (LoadFromEnumerator()) { return true; } if (_appending) { _current = _item; return true; } break; } Dispose(); return false; } public override AppendPrependIterator<TSource> Append(TSource item) { if (_appending) { return new AppendPrependN<TSource>(_source, null, new SingleLinkedNode<TSource>(_item, item)); } return new AppendPrependN<TSource>(_source, new SingleLinkedNode<TSource>(_item), new SingleLinkedNode<TSource>(item)); } public override AppendPrependIterator<TSource> Prepend(TSource item) { if (_appending) { return new AppendPrependN<TSource>(_source, new SingleLinkedNode<TSource>(item), new SingleLinkedNode<TSource>(_item)); } return new AppendPrependN<TSource>(_source, new SingleLinkedNode<TSource>(_item, item), null); } public override TSource[] ToArray() { int count = GetCount(onlyIfCheap: true); if (count == -1) { return EnumerableHelpers.ToArray(this); } TSource[] array = new TSource[count]; int num; if (_appending) { num = 0; } else { array[0] = _item; num = 1; } if (_source is System.Collections.Generic.ICollection<TSource> collection) { collection.CopyTo(array, num); } else { System.Collections.Generic.IEnumerator<TSource> enumerator = _source.GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { TSource current = enumerator.Current; array[num] = current; num++; } } finally { ((System.IDisposable)enumerator)?.Dispose(); } } if (_appending) { array[array.Length - 1] = _item; } return array; } public override List<TSource> ToList() { int count = GetCount(onlyIfCheap: true); List<TSource> val = ((count == -1) ? new List<TSource>() : new List<TSource>(count)); if (!_appending) { val.Add(_item); } val.AddRange(_source); if (_appending) { val.Add(_item); } return val; } public override int GetCount(bool onlyIfCheap) { if (_source is IIListProvider<TSource> iIListProvider) { int count = iIListProvider.GetCount(onlyIfCheap); if (count != -1) { return count + 1; } return -1; } if (onlyIfCheap && !(_source is System.Collections.Generic.ICollection<TSource>)) { return -1; } return _source.Count() + 1; } } private sealed class SingleLinkedNode<TSource> { public TSource Item { [CompilerGenerated] get; } public SingleLinkedNode<TSource> Linked { [CompilerGenerated] get; } public int Count { [CompilerGenerated] get; } public SingleLinkedNode(TSource first, TSource second) { Linked = new SingleLinkedNode<TSource>(first); Item = second; Count = 2; } public SingleLinkedNode(TSource item) { Item = item; Count = 1; } private SingleLinkedNode(SingleLinkedNode<TSource> linked, TSource item) { Linked = linked; Item = item; Count = linked.Count + 1; } public SingleLinkedNode<TSource> Add(TSource item) { return new SingleLinkedNode<TSource>(this, item); } public System.Collections.Generic.IEnumerator<TSource> GetEnumerator() { TSource[] array = new TSource[Count]; int num = Count; for (SingleLinkedNode<TSource> singleLinkedNode = this; singleLinkedNode != null; singleLinkedNode = singleLinkedNode.Linked) { num--; array[num] = singleLinkedNode.Item; } return ((System.Collections.Generic.IEnumerable<TSource>)array).GetEnumerator(); } } private class AppendPrependN<TSource> : AppendPrependIterator<TSource> { private readonly SingleLinkedNode<TSource> _prepended; private readonly SingleLinkedNode<TSource> _appended; private SingleLinkedNode<TSource> _node; public AppendPrependN(System.Collections.Generic.IEnumerable<TSource> source, SingleLinkedNode<TSource> prepended, SingleLinkedNode<TSource> appended) : base(source) { _prepended = prepended; _appended = appended; } public override Iterator<TSource> Clone() { return new AppendPrependN<TSource>(_source, _prepended, _appended); } public override bool MoveNext() { switch (_state) { case 1: _node = _prepended; _state = 2; goto case 2; case 2: if (_node != null) { _current = _node.Item; _node = _node.Linked; return true; } GetSourceEnumerator(); _state = 3; goto case 3; case 3: if (LoadFromEnumerator()) { return true; } if (_appended == null) { return false; } _enumerator = _appended.GetEnumerator(); _state = 4; goto case 4; case 4: return LoadFromEnumerator(); default: Dispose(); return false; } } public override AppendPrependIterator<TSource> Append(TSource item) { return new AppendPrependN<TSource>(_source, _prepended, (_appended != null) ? _appended.Add(item) : new SingleLinkedNode<TSource>(item)); } public override AppendPrependIterator<TSource> Prepend(TSource item) { return new AppendPrependN<TSource>(_source, (_prepended != null) ? _prepended.Add(item) : new SingleLinkedNode<TSource>(item), _appended); } public override TSource[] ToArray() { int count = GetCount(onlyIfCheap: true); if (count == -1) { return EnumerableHelpers.ToArray(this); } TSource[] array = new TSource[count]; int num = 0; for (SingleLinkedNode<TSource> singleLinkedNode = _prepended; singleLinkedNode != null; singleLinkedNode = singleLinkedNode.Linked) { array[num] = singleLinkedNode.Item; num++; } if (_source is System.Collections.Generic.ICollection<TSource> collection) { collection.CopyTo(array, num); } else { System.Collections.Generic.IEnumerator<TSource> enumerator = _source.GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { TSource current = enumerator.Current; array[num] = current; num++; } } finally { ((System.IDisposable)enumerator)?.Dispose(); } } num = array.Length; for (SingleLinkedNode<TSource> singleLinkedNode2 = _appended; singleLinkedNode2 != null; singleLinkedNode2 = singleLinkedNode2.Linked) { num--; array[num] = singleLinkedNode2.Item; } return array; } public override List<TSource> ToList() { int count = GetCount(onlyIfCheap: true); List<TSource> val = ((count == -1) ? new List<TSource>() : new List<TSource>(count)); for (SingleLinkedNode<TSource> singleLinkedNode = _prepended; singleLinkedNode != null; singleLinkedNode = singleLinkedNode.Linked) { val.Add(singleLinkedNode.Item); } val.AddRange(_source); if (_appended != null) { System.Collections.Generic.IEnumerator<TSource> enumerator = _appended.GetEnumerator(); while (((System.Collections.IEnumerator)enumerator).MoveNext()) { val.Add(enumerator.Current); } } return val; } public override int GetCount(bool onlyIfCheap) { if (_source is IIListProvider<TSource> iIListProvider) { int count = iIListProvider.GetCount(onlyIfCheap); if (count != -1) { return count + ((_appended != null) ? _appended.Count : 0) + ((_prepended != null) ? _prepended.Count : 0); } return -1; } if (onlyIfCheap && !(_source is System.Collections.Generic.ICollection<TSource>)) { return -1; } return _source.Count() + ((_appended != null) ? _appended.Count : 0) + ((_prepended != null) ? _prepended.Count : 0); } } private sealed class Concat2Iterator<TSource> : ConcatIterator<TSource> { private readonly System.Collections.Generic.IEnumerable<TSource> _first; private readonly System.Collections.Generic.IEnumerable<TSource> _second; internal Concat2Iterator(System.Collections.Generic.IEnumerable<TSource> first, System.Collections.Generic.IEnumerable<TSource> second) { _first = first; _second = second; } public override Iterator<TSource> Clone() { return new Concat2Iterator<TSource>(_first, _second); } internal override ConcatIterator<TSource> Concat(System.Collections.Generic.IEnumerable<TSource> next) { return new ConcatNIterator<TSource>(this, next, 2); } internal override System.Collections.Generic.IEnumerable<TSource> GetEnumerable(int index) { return index switch { 0 => _first, 1 => _second, _ => null, }; } } private sealed class ConcatNIterator<TSource> : ConcatIterator<TSource> { private readonly ConcatIterator<TSource> _previousConcat; private readonly System.Collections.Generic.IEnumerable<TSource> _next; private readonly int _nextIndex; internal ConcatNIterator(ConcatIterator<TSource> previousConcat, System.Collections.Generic.IEnumerable<TSource> next, int nextIndex) { _previousConcat = previousConcat; _next = next; _nextIndex = nextIndex; } public override Iterator<TSource> Clone() { return new ConcatNIterator<TSource>(_previousConcat, _next, _nextIndex); } internal override ConcatIterator<TSource> Concat(System.Collections.Generic.IEnumerable<TSource> next) { if (_nextIndex == 2147483645) { return new Concat2Iterator<TSource>(this, next); } return new ConcatNIterator<TSource>(this, next, _nextIndex + 1); } internal override System.Collections.Generic.IEnumerable<TSource> GetEnumerable(int index) { if (index > _nextIndex) { return null; } ConcatNIterator<TSource> concatNIterator = this; while (true) { if (index == concatNIterator._nextIndex) { return concatNIterator._next; } if (!(concatNIterator._previousConcat is ConcatNIterator<TSource> concatNIterator2)) { break; } concatNIterator = concatNIterator2; } return concatNIterator._previousConcat.GetEnumerable(index); } } private abstract class ConcatIterator<TSource> : Iterator<TSource>, IIListProvider<TSource>, System.Collections.Generic.IEnumerable<TSource>, System.Collections.IEnumerable { private System.Collections.Generic.IEnumerator<TSource> _enumerator; public override void Dispose() { if (_enumerator != null) { ((System.IDisposable)_enumerator).Dispose(); _enumerator = null; } base.Dispose(); } internal abstract System.Collections.Generic.IEnumerable<TSource> GetEnumerable(int index); internal abstract ConcatIterator<TSource> Concat(System.Collections.Generic.IEnumerable<TSource> next); public override bool MoveNext() { if (_state == 1) { _enumerator = GetEnumerable(0).GetEnumerator(); _state = 2; } if (_state > 1) { while (true) { if (((System.Collections.IEnumerator)_enumerator).MoveNext()) { _current = _enumerator.Current; return true; } System.Collections.Generic.IEnumerable<TSource> enumerable = GetEnumerable(_state++ - 1); if (enumerable == null) { break; } ((System.IDisposable)_enumerator).Dispose(); _enumerator = enumerable.GetEnumerator(); } Dispose(); } return false; } public TSource[] ToArray() { return EnumerableHelpers.ToArray(this); } public List<TSource> ToList() { List<TSource> val = new List<TSource>(); int num = 0; while (true) { System.Collections.Generic.IEnumerable<TSource> enumerable = GetEnumerable(num); if (enumerable == null) { break; } val.AddRange(enumerable); num++; } return val; } public int GetCount(bool onlyIfCheap) { if (onlyIfCheap) { return -1; } int num = 0; int num2 = 0; while (true) { System.Collections.Generic.IEnumerable<TSource> enumerable = GetEnumerable(num2); if (enumerable == null) { break; } num = checked(num + enumerable.Count()); num2++; } return num; } } private sealed class DefaultIfEmptyIterator<TSource> : Iterator<TSource>, IIListProvider<TSource>, System.Collections.Generic.IEnumerable<TSource>, System.Collections.IEnumerable { private readonly System.Collections.Generic.IEnumerable<TSource> _source; private readonly TSource _default; private System.Collections.Generic.IEnumerator<TSource> _enumerator; public DefaultIfEmptyIterator(System.Collections.Generic.IEnumerable<TSource> source, TSource defaultValue) { _source = source; _default = defaultValue; } public override Iterator<TSource> Clone() { return new DefaultIfEmptyIterator<TSource>(_source, _default); } public override bool MoveNext() { switch (_state) { case 1: _enumerator = _source.GetEnumerator(); if (((System.Collections.IEnumerator)_enumerator).MoveNext()) { _current = _enumerator.Current; _state = 2; } else { _current = _default; _state = -1; } return true; case 2: if (((System.Collections.IEnumerator)_enumerator).MoveNext()) { _current = _enumerator.Current; return true; } break; } Dispose(); return false; } public override void Dispose() { if (_enumerator != null) { ((System.IDisposable)_enumerator).Dispose(); _enumerator = null; } base.Dispose(); } public TSource[] ToArray() { TSource[] array = _source.ToArray(); if (array.Length != 0) { return array; } return new TSource[1] { _default }; } public List<TSource> ToList() { List<TSource> val = _source.ToList(); if (val.Count == 0) { val.Add(_default); } return val; } public int GetCount(bool onlyIfCheap) { int num = ((onlyIfCheap && !(_source is System.Collections.Generic.ICollection<TSource>) && !(_source is System.Collections.ICollection)) ? ((!(_source is IIListProvider<TSource> iIListProvider)) ? (-1) : iIListProvider.GetCount(onlyIfCheap: true)) : _source.Count()); if (num != 0) { return num; } return 1; } } private sealed class DistinctIterator<TSource> : Iterator<TSource>, IIListProvider<TSource>, System.Collections.Generic.IEnumerable<TSource>, System.Collections.IEnumerable { private readonly System.Collections.Generic.IEnumerable<TSource> _source; private readonly IEqualityComparer<TSource> _comparer; private Set<TSource> _set; private System.Collections.Generic.IEnumerator<TSource> _enumerator; public DistinctIterator(System.Collections.Generic.IEnumerable<TSource> source, IEqualityComparer<TSource> comparer) { _source = source; _comparer = comparer; } public override Iterator<TSource> Clone() { return new DistinctIterator<TSource>(_source, _comparer); } public override bool MoveNext() { int state = _state; TSource current; if (state != 1) { if (state == 2) { while (((System.Collections.IEnumerator)_enumerator).MoveNext()) { current = _enumerator.Current; if (_set.Add(current)) { _current = current; return true; } } } Dispose(); return false; } _enumerator = _source.GetEnumerator(); if (!((System.Collections.IEnumerator)_enumerator).MoveNext()) { Dispose(); return false; } current = _enumerator.Current; _set = new Set<TSource>(_comparer); _set.Add(current); _current = current; _state = 2; return true; } public override void Dispose() { if (_enumerator != null) { ((System.IDisposable)_enumerator).Dispose(); _enumerator = null; _set = null; } base.Dispose(); } private Set<TSource> FillSet() { Set<TSource> set = new Set<TSource>(_comparer); System.Collections.Generic.IEnumerator<TSource> enumerator = _source.GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { TSource current = enumerator.Current; set.Add(current); } return set; } finally { ((System.IDisposable)enumerator)?.Dispose(); } } public TSource[] ToArray() { return FillSet().ToArray(); } public List<TSource> ToList() { return FillSet().ToList(); } public int GetCount(bool onlyIfCheap) { if (!onlyIfCheap) { return FillSet().Count; } return -1; } } internal abstract class Iterator<TSource> : System.Collections.Generic.IEnumerable<TSource>, System.Collections.IEnumerable, System.Collections.Generic.IEnumerator<TSource>, System.Collections.IEnumerator, System.IDisposable { private readonly int _threadId; internal int _state; internal TSource _current; public TSource Current => _current; object System.Collections.IEnumerator.Current => Current; protected Iterator() { _threadId = Environment.CurrentManagedThreadId; } public abstract Iterator<TSource> Clone(); public virtual void Dispose() { _current = default(TSource); _state = -1; } public System.Collections.Generic.IEnumerator<TSource> GetEnumerator() { Iterator<TSource> iterator = ((_state == 0 && _threadId == Environment.CurrentManagedThreadId) ? this : Clone()); iterator._state = 1; return iterator; } public abstract bool MoveNext(); public virtual System.Collections.Generic.IEnumerable<TResult> Select<TResult>(Func<TSource, TResult> selector) { return new SelectEnumerableIterator<TSource, TResult>(this, selector); } public virtual System.Collections.Generic.IEnumerable<TSource> Where(Func<TSource, bool> predicate) { return new WhereEnumerableIterator<TSource>(this, predicate); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)GetEnumerator(); } void System.Collections.IEnumerator.Reset() { throw Error.NotSupported(); } } private sealed class ListPartition<TSource> : Iterator<TSource>, IPartition<TSource>, IIListProvider<TSource>, System.Collections.Generic.IEnumerable<TSource>, System.Collections.IEnumerable { private readonly System.Collections.Generic.IList<TSource> _source; private readonly int _minIndexInclusive; private readonly int _maxIndexInclusive; private int _index; private int Count { get { int count = ((System.Collections.Generic.ICollection<TSource>)_source).Count; if (count <= _minIndexInclusive) { return 0; } return Math.Min(count - 1, _maxIndexInclusive) - _minIndexInclusive + 1; } } public ListPartition(System.Collections.Generic.IList<TSource> source, int minIndexInclusive, int maxIndexInclusive) { _source = source; _minIndexInclusive = minIndexInclusive; _maxIndexInclusive = maxIndexInclusive; _index = minIndexInclusive; } public override Iterator<TSource> Clone() { return new ListPartition<TSource>(_source, _minIndexInclusive, _maxIndexInclusive); } public override bool MoveNext() { if (((_state == 1) & (_index <= _maxIndexInclusive)) && _index < ((System.Collections.Generic.ICollection<TSource>)_source).Count) { _current = _source[_index]; _index++; return true; } Dispose(); return false; } public override System.Collections.Generic.IEnumerable<TResult> Select<TResult>(Func<TSource, TResult> selector) { return new SelectListPartitionIterator<TSource, TResult>(_source, selector, _minIndexInclusive, _maxIndexInclusive); } public IPartition<TSource> Skip(int count) { int num = _minIndexInclusive + count; if ((uint)num <= (uint)_maxIndexInclusive) { return new ListPartition<TSource>(_source, num, _maxIndexInclusive); } return EmptyPartition<TSource>.Instance; } public IPartition<TSource> Take(int count) { int num = _minIndexInclusive + count - 1; if ((uint)num < (uint)_maxIndexInclusive) { return new ListPartition<TSource>(_source, _minIndexInclusive, num); } return this; } public TSource TryGetElementAt(int index, out bool found) { if ((uint)index <= (uint)(_maxIndexInclusive - _minIndexInclusive) && index < ((System.Collections.Generic.ICollection<TSource>)_source).Count - _minIndexInclusive) { found = true; return _source[_minIndexInclusive + index]; } found = false; return default(TSource); } public TSource TryGetFirst(out bool found) { if (((System.Collections.Generic.ICollection<TSource>)_source).Count > _minIndexInclusive) { found = true; return _source[_minIndexInclusive]; } found = false; return default(TSource); } public TSource TryGetLast(out bool found) { int num = ((System.Collections.Generic.ICollection<TSource>)_source).Count - 1; if (num >= _minIndexInclusive) { found = true; return _source[Math.Min(num, _maxIndexInclusive)]; } found = false; return default(TSource); } public TSource[] ToArray() { int count = Count; if (count == 0) { return System.Array.Empty<TSource>(); } TSource[] array = new TSource[count]; int num = 0; int num2 = _minIndexInclusive; while (num != array.Length) { array[num] = _source[num2]; num++; num2++; } return array; } public List<TSource> ToList() { int count = Count; if (count == 0) { return new List<TSource>(); } List<TSource> val = new List<TSource>(count); int num = _minIndexInclusive + count; for (int i = _minIndexInclusive; i != num; i++) { val.Add(_source[i]); } return val; } public int GetCount(bool onlyIfCheap) { return Count; } } private sealed class RangeIterator : Iterator<int>, IPartition<int>, IIListProvider<int>, System.Collections.Generic.IEnumerable<int>, System.Collections.IEnumerable { private readonly int _start; private readonly int _end; public RangeIterator(int start, int count) { _start = start; _end = start + count; } public override Iterator<int> Clone() { return new RangeIterator(_start, _end - _start); } public override bool MoveNext() { switch (_state) { case 1: _current = _start; _state = 2; return true; case 2: if (++_current != _end) { return true; } break; } _state = -1; return false; } public override void Dispose() { _state = -1; } public override System.Collections.Generic.IEnumerable<TResult> Select<TResult>(Func<int, TResult> selector) { return new SelectIPartitionIterator<int, TResult>(this, selector); } public int[] ToArray() { int[] array = new int[_end - _start]; int num = _start; for (int i = 0; i != array.Length; i++) { array[i] = num; num++; } return array; } public List<int> ToList() { List<int> val = new List<int>(_end - _start); for (int i = _start; i != _end; i++) { val.Add(i); } return val; } public int GetCount(bool onlyIfCheap) { return _end - _start; } public IPartition<int> Skip(int count) { if (count >= _end - _start) { return EmptyPartition<int>.Instance; } return new RangeIterator(_start + count, _end - _start - count); } public IPartition<int> Take(int count) { int num = _end - _start; if (count >= num) { return this; } return new RangeIterator(_start, count); } public int TryGetElementAt(int index, out bool found) { if ((uint)index < (uint)(_end - _start)) { found = true; return _start + index; } found = false; return 0; } public int TryGetFirst(out bool found) { found = true; return _start; } public int TryGetLast(out bool found) { found = true; return _end - 1; } } private sealed class RepeatIterator<TResult> : Iterator<TResult>, IPartition<TResult>, IIListProvider<TResult>, System.Collections.Generic.IEnumerable<TResult>, System.Collections.IEnumerable { private readonly int _count; private int _sent; public RepeatIterator(TResult element, int count) { _current = element; _count = count; } public override Iterator<TResult> Clone() { return new RepeatIterator<TResult>(_current, _count); } public override void Dispose() { _state = -1; } public override bool MoveNext() { if ((_state == 1) & (_sent != _count)) { _sent++; return true; } _state = -1; return false; } public override System.Collections.Generic.IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) { return new SelectIPartitionIterator<TResult, TResult2>(this, selector); } public TResult[] ToArray() { TResult[] array = new TResult[_count]; if (_current != null) { for (int i = 0; i != array.Length; i++) { array[i] = _current; } } return array; } public List<TResult> ToList() { List<TResult> val = new List<TResult>(_count); for (int i = 0; i != _count; i++) { val.Add(_current); } return val; } public int GetCount(bool onlyIfCheap) { return _count; } public IPartition<TResult> Skip(int count) { if (count >= _count) { return EmptyPartition<TResult>.Instance; } return new RepeatIterator<TResult>(_current, _count - count); } public IPartition<TResult> Take(int count) { if (count >= _count) { return this; } return new RepeatIterator<TResult>(_current, count); } public TResult TryGetElementAt(int index, out bool found) { if ((uint)index < (uint)_count) { found = true; return _current; } found = false; return default(TResult); } public TResult TryGetFirst(out bool found) { found = true; return _current; } public TResult TryGetLast(out bool found) { found = true; return _current; } } private sealed class ReverseIterator<TSource> : Iterator<TSource>, IIListProvider<TSource>, System.Collections.Generic.IEnumerable<TSource>, System.Collections.IEnumerable { private readonly System.Collections.Generic.IEnumerable<TSource> _source; private TSource[] _buffer; private int _index; public ReverseIterator(System.Collections.Generic.IEnumerable<TSource> source) { _source = source; } public override Iterator<TSource> Clone() { return new ReverseIterator<TSource>(_source); } public override bool MoveNext() { int state = _state; if (state != 1) { if (state != 2) { goto IL_006f; } } else { Buffer<TSource> buffer = new Buffer<TSource>(_source); _buffer = buffer._items; _index = buffer._count - 1; _state = 2; } if (_index != -1) { _current = _buffer[_index]; _index--; return true; } goto IL_006f; IL_006f: Dispose(); return false; } public override void Dispose() { _buffer = null; base.Dispose(); } public TSource[] ToArray() { TSource[] array = _source.ToArray(); int num = 0; int num2 = array.Length - 1; while (num < num2) { TSource val = array[num]; array[num] = array[num2]; array[num2] = val; num++; num2--; } return array; } public List<TSource> ToList() { List<TSource> val = _source.ToList(); val.Reverse(); return val; } public int GetCount(bool onlyIfCheap) { if (onlyIfCheap) { if (_source is IIListProvider<TSource> iIListProvider) { return iIListProvider.GetCount(onlyIfCheap: true); } if (!(_source is System.Collections.Generic.ICollection<TSource>) && !(_source is System.Collections.ICollection)) { return -1; } } return _source.Count(); } } internal sealed class SelectEnumerableIterator<TSource, TResult> : Iterator<TResult> { private readonly System.Collections.Generic.IEnumerable<TSource> _source; private readonly Func<TSource, TResult> _selector; private System.Collections.Generic.IEnumerator<TSource> _enumerator; public SelectEnumerableIterator(System.Collections.Generic.IEnumerable<TSource> source, Func<TSource, TResult> selector) { _source = source; _selector = selector; } public override Iterator<TResult> Clone() { return new SelectEnumerableIterator<TSource, TResult>(_source, _selector); } public override void Dispose() { if (_enumerator != null) { ((System.IDisposable)_enumerator).Dispose(); _enumerator = null; } base.Dispose(); } public override bool MoveNext() { int state = _state; if (state != 1) { if (state != 2) { goto IL_005a; } } else { _enumerator = _source.GetEnumerator(); _state = 2; } if (((System.Collections.IEnumerator)_enumerator).MoveNext()) { _current = _selector.Invoke(_enumerator.Current); return true; } Dispose(); goto IL_005a; IL_005a: return false; } public override System.Collections.Generic.IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) { return new SelectEnumerableIterator<TSource, TResult2>(_source, CombineSelectors<TSource, TResult, TResult2>(_selector, selector)); } } internal sealed class SelectArrayIterator<TSource, TResult> : Iterator<TResult>, IPartition<TResult>, IIListProvider<TResult>, System.Collections.Generic.IEnumerable<TResult>, System.Collections.IEnumerable { private readonly TSource[] _source; private readonly Func<TSource, TResult> _selector; private int _index; public SelectArrayIterator(TSource[] source, Func<TSource, TResult> selector) { _source = source; _selector = selector; } public override Iterator<TResult> Clone() { return new SelectArrayIterator<TSource, TResult>(_source, _selector); } public override bool MoveNext() { if (_state == 1 && _index < _source.Length) { _current = _selector.Invoke(_source[_index++]); return true; } Dispose(); return false; } public override System.Collections.Generic.IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) { return new SelectArrayIterator<TSource, TResult2>(_source, CombineSelectors<TSource, TResult, TResult2>(_selector, selector)); } public TResult[] ToArray() { if (_source.Length == 0) { return System.Array.Empty<TResult>(); } TResult[] array = new TResult[_source.Length]; for (int i = 0; i < array.Length; i++) { array[i] = _selector.Invoke(_source[i]); } return array; } public List<TResult> ToList() { TSource[] source = _source; List<TResult> val = (List<TResult>)(object)new List<?>(source.Length); for (int i = 0; i < source.Length; i++) { ((List<?>)(object)val).Add(_selector.Invoke(source[i])); } return val; } public int GetCount(bool onlyIfCheap) { return _source.Length; } public IPartition<TResult> Skip(int count) { if (count >= _source.Length) { return EmptyPartition<TResult>.Instance; } return new SelectListPartitionIterator<TSource, TResult>(_source, _selector, count, 2147483647); } public IPartition<TResult> Take(int count) { if (count < _source.Length) { return new SelectListPartitionIterator<TSource, TResult>(_source, _selector, 0, count - 1); } return this; } public TResult TryGetElementAt(int index, out bool found) { if ((uint)index < (uint)_source.Length) { found = true; return _selector.Invoke(_source[index]); } found = false; return default(TResult); } public TResult TryGetFirst(out bool found) { if (_source.Length != 0) { found = true; return _selector.Invoke(_source[0]); } found = false; return default(TResult); } public TResult TryGetLast(out bool found) { int num = _source.Length; if (num != 0) { found = true; return _selector.Invoke(_source[num - 1]); } found = false; return default(TResult); } } internal sealed class SelectListIterator<TSource, TResult> : Iterator<TResult>, IPartition<TResult>, IIListProvider<TResult>, System.Collections.Generic.IEnumerable<TResult>, System.Collections.IEnumerable { private readonly List<TSource> _source; private readonly Func<TSource, TResult> _selector; private Enumerator<TSource> _enumerator; public SelectListIterator(List<TSource> source, Func<TSource, TResult> selector) { _source = source; _selector = selector; } public override Iterator<TResult> Clone() { return new SelectListIterator<TSource, TResult>(_source, _selector); } public override bool MoveNext() { //IL_0018: 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) int state = _state; if (state != 1) { if (state != 2) { goto IL_005a; } } else { _enumerator = _source.GetEnumerator(); _state = 2; } if (_enumerator.MoveNext()) { _current = _selector.Invoke(_enumerator.Current); return true; } Dispose(); goto IL_005a; IL_005a: return false; } public override System.Collections.Generic.IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) { return new SelectListIterator<TSource, TResult2>(_source, CombineSelectors<TSource, TResult, TResult2>(_selector, selector)); } public TResult[] ToArray() { int count = _source.Count; if (count == 0) { return System.Array.Empty<TResult>(); } TResult[] array = new TResult[count]; for (int i = 0; i < array.Length; i++) { array[i] = _selector.Invoke(_source[i]); } return array; } public List<TResult> ToList() { int count = _source.Count; List<TResult> val = (List<TResult>)(object)new List<?>(count); for (int i = 0; i < count; i++) { ((List<?>)(object)val).Add(_selector.Invoke(_source[i])); } return val; } public int GetCount(bool onlyIfCheap) { return _source.Count; } public IPartition<TResult> Skip(int count) { return new SelectListPartitionIterator<TSource, TResult>((System.Collections.Generic.IList<TSource>)_source, _selector, count, 2147483647); } public IPartition<TResult> Take(int count) { return new SelectListPartitionIterator<TSource, TResult>((System.Collections.Generic.IList<TSource>)_source, _selector, 0, count - 1); } public TResult TryGetElementAt(int index, out bool found) { if ((uint)index < (uint)_source.Count) { found = true; return _selector.Invoke(_source[index]); } found = false; return default(TResult); } public TResult TryGetFirst(out bool found) { if (_source.Count != 0) { found = true; return _selector.Invoke(_source[0]); } found = false; return default(TResult); } public TResult TryGetLast(out bool found) { int count = _source.Count; if (count != 0) { found = true; return _selector.Invoke(_source[count - 1]); } found = false; return default(TResult); } } internal sealed class SelectIListIterator<TSource, TResult> : Iterator<TResult>, IPartition<TResult>, IIListProvider<TResult>, System.Collections.Generic.IEnumerable<TResult>, System.Collections.IEnumerable { private readonly System.Collections.Generic.IList<TSource> _source; private readonly Func<TSource, TResult> _selector; private System.Collections.Generic.IEnumerator<TSource> _enumerator; public SelectIListIterator(System.Collections.Generic.IList<TSource> source, Func<TSource, TResult> selector) { _source = source; _selector = selector; } public override Iterator<TResult> Clone() { return new SelectIListIterator<TSource, TResult>(_source, _selector); } public override bool MoveNext() { int state = _state; if (state != 1) { if (state != 2) { goto IL_005a; } } else { _enumerator = ((System.Collections.Generic.IEnumerable<TSource>)_source).GetEnumerator(); _state = 2; } if (((System.Collections.IEnumerator)_enumerator).MoveNext()) { _current = _selector.Invoke(_enumerator.Current); return true; } Dispose(); goto IL_005a; IL_005a: return false; } public override void Dispose() { if (_enumerator != null) { ((System.IDisposable)_enumerator).Dispose(); _enumerator = null; } base.Dispose(); } public override System.Collections.Generic.IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) { return new SelectIListIterator<TSource, TResult2>(_source, CombineSelectors<TSource, TResult, TResult2>(_selector, selector)); } public TResult[] ToArray() { int count = ((System.Collections.Generic.ICollection<TSource>)_source).Count; if (count == 0) { return System.Array.Empty<TResult>(); } TResult[] array = new TResult[count]; for (int i = 0; i < array.Length; i++) { array[i] = _selector.Invoke(_source[i]); } return array; } public List<TResult> ToList() { int count = ((System.Collections.Generic.ICollection<TSource>)_source).Count; List<TResult> val = (List<TResult>)(object)new List<?>(count); for (int i = 0; i < count; i++) { ((List<?>)(object)val).Add(_selector.Invoke(_source[i])); } return val; } public int GetCount(bool onlyIfCheap) { return ((System.Collections.Generic.ICollection<TSource>)_source).Count; } public IPartition<TResult> Skip(int count) { return new SelectListPartitionIterator<TSource, TResult>(_source, _selector, count, 2147483647); } public IPartition<TResult> Take(int count) { return new SelectListPartitionIterator<TSource, TResult>(_source, _selector, 0, count - 1); } public TResult TryGetElementAt(int index, out bool found) { if ((uint)index < (uint)((System.Collections.Generic.ICollection<TSource>)_source).Count) { found = true; return _selector.Invoke(_source[index]); } found = false; return default(TResult); } public TResult TryGetFirst(out bool found) { if (((System.Collections.Generic.ICollection<TSource>)_source).Count != 0) { found = true; return _selector.Invoke(_source[0]); } found = false; return default(TResult); } public TResult TryGetLast(out bool found) { int count = ((System.Collections.Generic.ICollection<TSource>)_source).Count; if (count != 0) { found = true; return _selector.Invoke(_source[count - 1]); } found = false; return default(TResult); } } internal sealed class SelectIPartitionIterator<TSource, TResult> : Iterator<TResult>, IPartition<TResult>, IIListProvider<TResult>, System.Collections.Generic.IEnumerable<TResult>, System.Collections.IEnumerable { private readonly IPartition<TSource> _source; private readonly Func<TSource, TResult> _selector; private System.Collections.Generic.IEnumerator<TSource> _enumerator; public SelectIPartitionIterator(IPartition<TSource> source, Func<TSource, TResult> selector) { _source = source; _selector = selector; } public override Iterator<TResult> Clone() { return new SelectIPartitionIterator<TSource, TResult>(_source, _selector); } public override bool MoveNext() { int state = _state; if (state != 1) { if (state != 2) { goto IL_005a; } } else { _enumerator = ((System.Collections.Generic.IEnumerable<TSource>)_source).GetEnumerator(); _state = 2; } if (((System.Collections.IEnumerator)_enumerator).MoveNext()) { _current = _selector.Invoke(_enumerator.Current); return true; } Dispose(); goto IL_005a; IL_005a: return false; } public override void Dispose() { if (_enumerator != null) { ((System.IDisposable)_enumerator).Dispose(); _enumerator = null; } base.Dispose(); } public override System.Collections.Generic.IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) { return new SelectIPartitionIterator<TSource, TResult2>(_source, CombineSelectors<TSource, TResult, TResult2>(_selector, selector)); } public IPartition<TResult> Skip(int count) { return new SelectIPartitionIterator<TSource, TResult>(_source.Skip(count), _selector); } public IPartition<TResult> Take(int count) { return new SelectIPartitionIterator<TSource, TResult>(_source.Take(count), _selector); } public TResult TryGetElementAt(int index, out bool found) { bool found2; TSource val = _source.TryGetElementAt(index, out found2); found = found2; if (!found2) { return default(TResult); } return _selector.Invoke(val); } public TResult TryGetFirst(out bool found) { bool found2; TSource val = _source.TryGetFirst(out found2); found = found2; if (!found2) { return default(TResult); } return _selector.Invoke(val); } public TResult TryGetLast(out bool found) { bool found2; TSource val = _source.TryGetLast(out found2); found = found2; if (!found2) { return default(TResult); } return _selector.Invoke(val); } public TResult[] ToArray() { int count = _source.GetCount(onlyIfCheap: true); switch (count) { case -1: return EnumerableHelpers.ToArray(this); case 0: return System.Array.Empty<TResult>(); default: { TResult[] array = new TResult[count]; int num = 0; System.Collections.Generic.IEnumerator<TSource> enumerator = ((System.Collections.Generic.IEnumerable<TSource>)_source).GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { TSource current = enumerator.Current; array[num] = _selector.Invoke(current); num++; } return array; } finally { ((System.IDisposable)enumerator)?.Dispose(); } } } } public List<TResult> ToList() { int count = _source.GetCount(onlyIfCheap: true); List<TResult> val; switch (count) { case -1: val = (List<TResult>)(object)new List<?>(); break; case 0: return (List<TResult>)(object)new List<?>(); default: val = (List<TResult>)(object)new List<?>(count); break; } System.Collections.Generic.IEnumerator<TSource> enumerator = ((System.Collections.Generic.IEnumerable<TSource>)_source).GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { TSource current = enumerator.Current; ((List<?>)(object)val).Add(_selector.Invoke(current)); } return val; } finally { ((System.IDisposable)enumerator)?.Dispose(); } } public int GetCount(bool onlyIfCheap) { return _source.GetCount(onlyIfCheap); } } private sealed class SelectListPartitionIterator<TSource, TResult> : Iterator<TResult>, IPartition<TResult>, IIListProvider<TResult>, System.Collections.Generic.IEnumerable<TResult>, System.Collections.IEnumerable { private readonly System.Collections.Generic.IList<TSource> _source; private readonly Func<TSource, TResult> _selector; private readonly int _minIndexInclusive; private readonly int _maxIndexInclusive; private int _index; private int Count { get { int count = ((System.Collections.Generic.ICollection<TSource>)_source).Count; if (count <= _minIndexInclusive) { return 0; } return Math.Min(count - 1, _maxIndexInclusive) - _minIndexInclusive + 1; } } public SelectListPartitionIterator(System.Collections.Generic.IList<TSource> source, Func<TSource, TResult> selector, int minIndexInclusive, int maxIndexInclusive) { _source = source; _selector = selector; _minIndexInclusive = minIndexInclusive; _maxIndexInclusive = maxIndexInclusive; _index = minIndexInclusive; } public override Iterator<TResult> Clone() { return new SelectListPartitionIterator<TSource, TResult>(_source, _selector, _minIndexInclusive, _maxIndexInclusive); } public override bool MoveNext() { if (((_state == 1) & (_index <= _maxIndexInclusive)) && _index < ((System.Collections.Generic.ICollection<TSource>)_source).Count) { _current = _selector.Invoke(_source[_index]); _index++; return true; } Dispose(); return false; } public override System.Collections.Generic.IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) { return new SelectListPartitionIterator<TSource, TResult2>(_source, CombineSelectors<TSource, TResult, TResult2>(_selector, selector), _minIndexInclusive, _maxIndexInclusive); } public IPartition<TResult> Skip(int count) { int num = _minIndexInclusive + count; if ((uint)num <= (uint)_maxIndexInclusive) { return new SelectListPartitionIterator<TSource, TResult>(_source, _selector, num, _maxIndexInclusive); } return EmptyPartition<TResult>.Instance; } public IPartition<TResult> Take(int count) { int num = _minIndexInclusive + count - 1; if ((uint)num < (uint)_maxIndexInclusive) { return new SelectListPartitionIterator<TSource, TResult>(_source, _selector, _minIndexInclusive, num); } return this; } public TResult TryGetElementAt(int index, out bool found) { if ((uint)index <= (uint)(_maxIndexInclusive - _minIndexInclusive) && index < ((System.Collections.Generic.ICollection<TSource>)_source).Count - _minIndexInclusive) { found = true; return _selector.Invoke(_source[_minIndexInclusive + index]); } found = false; return default(TResult); } public TResult TryGetFirst(out bool found) { if (((System.Collections.Generic.ICollection<TSource>)_source).Count > _minIndexInclusive) { found = true; return _selector.Invoke(_source[_minIndexInclusive]); } found = false; return default(TResult); } public TResult TryGetLast(out bool found) { int num = ((System.Collections.Generic.ICollection<TSource>)_source).Count - 1; if (num >= _minIndexInclusive) { found = true; return _selector.Invoke(_source[Math.Min(num, _maxIndexInclusive)]); } found = false; return default(TResult); } public TResult[] ToArray() { int count = Count; if (count == 0) { return System.Array.Empty<TResult>(); } TResult[] array = new TResult[count]; int num = 0; int num2 = _minIndexInclusive; while (num != array.Length) { array[num] = _selector.Invoke(_source[num2]); num++; num2++; } return array; } public List<TResult> ToList() { int count = Count; if (count == 0) { return (List<TResult>)(object)new List<?>(); } List<TResult> val = (List<TResult>)(object)new List<?>(count); int num = _minIndexInclusive + count; for (int i = _minIndexInclusive; i != num; i++) { ((List<?>)(object)val).Add(_selector.Invoke(_source[i])); } return val; } public int GetCount(bool onlyIfCheap) { return Count; } } private abstract class UnionIterator<TSource> : Iterator<TSource>, IIListProvider<TSource>, System.Collections.Generic.IEnumerable<TSource>, System.Collections.IEnumerable { internal readonly IEqualityComparer<TSource> _comparer; private System.Collections.Generic.IEnumerator<TSource> _enumerator; private Set<TSource> _set; public UnionIterator(IEqualityComparer<TSource> comparer) { _comparer = comparer; } public sealed override void Dispose() { if (_enumerator != null) { ((System.IDisposable)_enumerator).Dispose(); _enumerator = null; _set = null; } base.Dispose(); } internal abstract System.Collections.Generic.IEnumerable<TSource> GetEnumerable(int index); internal abstract UnionIterator<TSource> Union(System.Collections.Generic.IEnumerable<TSource> next); protected void SetEnumerator(System.Collections.Generic.IEnumerator<TSource> enumerator) { if (_enumerator != null) { ((System.IDisposable)_enumerator).Dispose(); } _enumerator = enumerator; } protected void StoreFirst() { Set<TSource> set = new Set<TSource>(_comparer); TSource current = _enumerator.Current; set.Add(current); _current = current; _set = set; } protected bool GetNext() { Set<TSource> set = _set; while (((System.Collections.IEnumerator)_enumerator).MoveNext()) { TSource current = _enumerator.Current; if (set.Add(current)) { _current = current; return true; } } return false; } public sealed override bool MoveNext() { if (_state == 1) { for (System.Collections.Generic.IEnumerable<TSource> enumerable = GetEnumerable(0); enumerable != null; enumerable = GetEnumerable(_state - 1)) { System.Collections.Generic.IEnumerator<TSource> enumerator = enumerable.GetEnumerator(); _state++; if (((System.Collections.IEnumerator)enumerator).MoveNext()) { SetEnumerator(enumerator); StoreFirst(); return true; } } } else if (_state > 0) { while (true) { if (GetNext()) { return true; } System.Collections.Generic.IEnumerable<TSource> enumerable2 = GetEnumerable(_state - 1); if (enumerable2 == null) { break; } SetEnumerator(enumerable2.GetEnumerator()); _state++; } } Dispose(); return false; } private Set<TSource> FillSet() { Set<TSource> set = new Set<TSource>(_comparer); int num = 0; while (true) { System.Collections.Generic.IEnumerable<TSource> enumerable = GetEnumerable(num); if (enumerable == null) { break; } System.Collections.Generic.IEnumerator<TSource> enumerator = enumerable.GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { TSource current = enumerator.Current; set.Add(current); } } finally { ((System.IDisposable)enumerator)?.Dispose(); } num++; } return set; } public TSource[] ToArray() { return FillSet().ToArray(); } public List<TSource> ToList() { return FillSet().ToList(); } public int GetCount(bool onlyIfCheap) { if (!onlyIfCheap) { return FillSet().Count; } return -1; } } private sealed class UnionIterator2<TSource> : UnionIterator<TSource> { private readonly System.Collections.Generic.IEnumerable<TSource> _first; private readonly System.Collections.Generic.IEnumerable<TSource> _second; public UnionIterator2(System.Collections.Generic.IEnumerable<TSource> first, System.Collections.Generic.IEnumerable<TSource> second, IEqualityComparer<TSource> comparer) : base(comparer) { _first = first; _second = second; } public override Iterator<TSource> Clone() { return new UnionIterator2<TSource>(_first, _second, _comparer); } internal override System.Collections.Generic.IEnumerable<TSource> GetEnumerable(int index) { return index switch { 0 => _first, 1 => _second, _ => null, }; } internal override UnionIterator<TSource> Union(System.Collections.Generic.IEnumerable<TSource> next) { return new UnionIteratorN<TSource>(this, next, 2); } } private sealed class UnionIteratorN<TSource> : UnionIterator<TSource> { private readonly UnionIterator<TSource> _previous; private readonly System.Collections.Generic.IEnumerable<TSource> _next; private readonly int _nextIndex; public UnionIteratorN(UnionIterator<TSource> previous, System.Collections.Generic.IEnumerable<TSource> next, int nextIndex) : base(previous._comparer) { _previous = previous; _next = next; _nextIndex = nextIndex; } public override Iterator<TSource> Clone() { return new UnionIteratorN<TSource>(_previous, _next, _nextIndex); } internal override System.Collections.Generic.IEnumerable<TSource> GetEnumerable(int index) { if (index > _nextIndex) { return null; } UnionIteratorN<TSource> unionIteratorN = this; while (index < unionIteratorN._nextIndex) { UnionIterator<TSource> previous = unionIteratorN._previous; unionIteratorN = previous as UnionIteratorN<TSource>; if (unionIteratorN == null) { return previous.GetEnumerable(index); } } return unionIteratorN._next; } internal override UnionIterator<TSource> Union(System.Collections.Generic.IEnumerable<TSource> next) { if (_nextIndex == 2147483645) { return new UnionIterator2<TSource>(this, next, _comparer); } return new UnionIteratorN<TSource>(this, next, _nextIndex + 1); } } internal sealed class WhereEnumerableIterator<TSource> : Iterator<TSource> { private readonly System.Collections.Generic.IEnumerable<TSource> _source; private readonly Func<TSource, bool> _predicate; private System.Collections.Generic.IEnumerator<TSource> _enumerator; public WhereEnumerableIterator(System.Collections.Generic.IEnumerable<TSource> source, Func<TSource, bool> predicate) { _source = source; _predicate = predicate; } public override Iterator<TSource> Clone() { return new WhereEnumerableIterator<TSource>(_source, _predicate); } public override void Dispose() { if (_enumerator != null) { ((System.IDisposable)_enumerator).Dispose(); _enumerator = null; } base.Dispose(); } public override bool MoveNext() { int state = _state; if (state != 1) { if (state != 2) { goto IL_0061; } } else { _enumerator = _source.GetEnumerator(); _state = 2; } while (((System.Collections.IEnumerator)_enumerator).MoveNext()) { TSource current = _enumerator.Current; if (_predicate.Invoke(current)) { _current = current; return true; } } Dispose(); goto IL_0061; IL_0061: return false; } public override System.Collections.Generic.IEnumerable<TResult> Select<TResult>(Func<TSource, TResult> selector) { return new WhereSelectEnumerableIterator<TSource, TResult>(_source, _predicate, selector); } public override System.Collections.Generic.IEnumerable<TSource> Where(Func<TSource, bool> predicate) { return new WhereEnumerableIterator<TSource>(_source, CombinePredicates<TSource>(_predicate, predicate)); } } internal sealed class WhereArrayIterator<TSource> : Iterator<TSource> { private readonly TSource[] _source; private readonly Func<TSource, bool> _predicate; private int _index; public WhereArrayIterator(TSource[] source, Func<TSource, bool> predicate) { _source = source; _predicate = predicate; } public override Iterator<TSource> Clone() { return new WhereArrayIterator<TSource>(_source, _predicate); } public override bool MoveNext() { if (_state == 1) { while (_index < _source.Length) { TSource val = _source[_index]; _index++; if (_predicate.Invoke(val)) { _current = val; return true; } } Dispose(); } return false; } public override System.Collections.Generic.IEnumerable<TResult> Select<TResult>(Func<TSource, TResult> selector) { return new WhereSelectArrayIterator<TSource, TResult>(_source, _predicate, selector); } public override System.Collections.Generic.IEnumerable<TSource> Where(Func<TSource, bool> predicate) { return new WhereArrayIterator<TSource>(_source, CombinePredicates<TSource>(_predicate, predicate)); } } internal sealed class WhereListIterator<TSource> : Iterator<TSource> { private readonly List<TSource> _source; private readonly Func<TSource, bool> _predicate; private Enumerator<TSource> _enumerator; public WhereListIterator(List<TSource> source, Func<TSource, bool> predicate) { _source = source; _predicate = predicate; } public override Iterator<TSource> Clone() { return new WhereListIterator<TSource>(_source, _predicate); } public override bool MoveNext() { //IL_0018: 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) int state = _state; if (state != 1) { if (state != 2) { goto IL_0061; } } else { _enumerator = _source.GetEnumerator(); _state = 2; } while (_enumerator.MoveNext()) { TSource current = _enumerator.Current; if (_predicate.Invoke(current)) { _current = current; return true; } } Dispose(); goto IL_0061; IL_0061: return false; } public override System.Collections.Generic.IEnumerable<TResult> Select<TResult>(Func<TSource, TResult> selector) { return new WhereSelectListIterator<TSource, TResult>(_source, _predicate, selector); } public override System.Collections.Generic.IEnumerable<TSource> Where(Func<TSource, bool> predicate) { return new WhereListIterator<TSource>(_source, CombinePredicates<TSource>(_predicate, predicate)); } } internal sealed class WhereSelectArrayIterator<TSource, TResult> : Iterator<TResult> { private readonly TSource[] _source; private readonly Func<TSource, bool> _predicate; private readonly Func<TSource, TResult> _selector; private int _index; public WhereSelectArrayIterator(TSource[] source, Func<TSource, bool> predicate, Func<TSource, TResult> selector) { _source = source; _predicate = predicate; _selector = selector; } public override Iterator<TResult> Clone() { return new WhereSelectArrayIterator<TSource, TResult>(_source, _predicate, _selector); } public override bool MoveNext() { if (_state == 1) { while (_index < _source.Length) { TSource val = _source[_index]; _index++; if (_predicate.Invoke(val)) { _current = _selector.Invoke(val); return true; } } Dispose(); } return false; } public override System.Collections.Generic.IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) { return new WhereSelectArrayIterator<TSource, TResult2>(_source, _predicate, CombineSelectors<TSource, TResult, TResult2>(_selector, selector)); } } internal sealed class WhereSelectListIterator<TSource, TResult> : Iterator<TResult> { private readonly List<TSource> _source; private readonly Func<TSource, bool> _predicate; private readonly Func<TSource, TResult> _selector; private Enumerator<TSource> _enumerator; public WhereSelectListIterator(List<TSource> source, Func<TSource, bool> predicate, Func<TSource, TResult> selector) { _source = source; _predicate = predicate; _selector = selector; } public override Iterator<TResult> Clone() { return new WhereSelectListIterator<TSource, TResult>(_source, _predicate, _selector); } public override bool MoveNext() { //IL_0018: 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) int state = _state; if (state != 1) { if (state != 2) { goto IL_006c; } } else { _enumerator = _source.GetEnumerator(); _state = 2; } while (_enumerator.MoveNext()) { TSource current = _enumerator.Current; if (_predicate.Invoke(current)) { _current = _selector.Invoke(current); return true; } } Dispose(); goto IL_006c; IL_006c: return false; } public override System.Collections.Generic.IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) { return new WhereSelectListIterator<TSource, TResult2>(_source, _predicate, CombineSelectors<TSource, TResult, TResult2>(_selector, selector)); } } internal sealed class WhereSelectEnumerableIterator<TSource, TResult> : Iterator<TResult> { private readonly System.Collections.Generic.IEnumerable<TSource> _source; private readonly Func<TSource, bool> _predicate; private readonly Func<TSource, TResult> _selector; private System.Collections.Generic.IEnumerator<TSource> _enumerator; public WhereSelectEnumerableIterator(System.Collections.Generic.IEnumerable<TSource> source, Func<TSource, bool> predicate, Func<TSource, TResult> selector) { _source = source; _predicate = predicate; _selector = selector; } public override Iterator<TResult> Clone() { return new WhereSelectEnumerableIterator<TSource, TResult>(_source, _predicate, _selector); } public override void Dispose() { if (_enumerator != null) { ((System.IDisposable)_enumerator).Dispose(); _enumerator = null; } base.Dispose(); } public override bool MoveNext() { int state = _state; if (state != 1) { if (state != 2) { goto IL_006c; } } else { _enumerator = _source.GetEnumerator(); _state = 2; } while (((System.Collections.IEnumerator)_enumerator).MoveNext()) { TSource current = _enumerator.Current; if (_predicate.Invoke(current)) { _current = _selector.Invoke(current); return true; } } Dispose(); goto IL_006c; IL_006c: return false; } public override System.Collections.Generic.IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) { return new WhereSelectEnumerableIterator<TSource, TResult2>(_source, _predicate, CombineSelectors<TSource, TResult, TResult2>(_selector, selector)); } } [CompilerGenerated] private sealed class <OfTypeIterator>d__33<TResult> : System.Collections.Generic.IEnumerable<TResult>, System.Collections.IEnumerable, System.Collections.Generic.IEnumerator<TResult>, System.Collections.IEnumerator, System.IDisposable { private int <>1__state; private TResult <>2__current; private int <>l__initialThreadId; private System.Collections.IEnumerable source; public System.Collections.IEnumerable <>3__source; private System.Collections.IEnumerator <>7__wrap1; TResult System.Collections.Generic.IEnumerator<TResult>.Current { [DebuggerHidden] get { return <>2__current; } } object System.Collections.IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <OfTypeIterator>d__33(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void System.IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } } private bool MoveNext() { try { switch (<>1__state) { default: return false; case 0: <>1__state = -1; <>7__wrap1 = source.GetEnumerator(); <>1__state = -3; break; case 1: <>1__state = -3; break; } while (<>7__wrap1.MoveNext()) { object current = <>7__wrap1.Current; if (current is TResult) { <>2__current = (TResult)current; <>1__state = 1; return true; } } <>m__Finally1(); <>7__wrap1 = null; return false; } catch { //try-fault ((System.IDisposable)this).Dispose(); throw; } } bool System.Collections.IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap1 is System.IDisposable disposable) { disposable.Dispose(); } } [DebuggerHidden] void System.Collections.IEnumerator.Reset() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } [DebuggerHidden] System.Collections.Generic.IEnumerator<TResult> System.Collections.Generic.IEnumerable<TResult>.GetEnumerator() { <OfTypeIterator>d__33<TResult> <OfTypeIterator>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; <OfTypeIterator>d__ = this; } else { <OfTypeIterator>d__ = new <OfTypeIterator>d__33<TResult>(0); } <OfTypeIterator>d__.source = <>3__source; return <OfTypeIterator>d__; } [DebuggerHidden] System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)((System.Collections.Generic.IEnumerable<TResult>)this).GetEnumerator(); } } [CompilerGenerated] private sealed class <CastIterator>d__35<TResult> : System.Collections.Generic.IEnumerable<TResult>, System.Collections.IEnumerable, System.Collections.Generic.IEnumerator<TResult>, System.Collections.IEnumerator, System.IDisposable { private int <>1__state; private TResult <>2__current; private int <>l__initialThreadId; private System.Collections.IEnumerable source; public System.Collections.IEnumerable <>3__source; private System.Collections.IEnumerator <>7__wrap1; TResult System.Collections.Generic.IEnumerator<TResult>.Current { [DebuggerHidden] get { return <>2__current; } } object System.Collections.IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <CastIterator>d__35(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void System.IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } } private bool MoveNext() { try { switch (<>1__state) { default: return false; case 0: <>1__state = -1; <>7__wrap1 = source.GetEnumerator(); <>1__state = -3; break; case 1: <>1__state = -3; break; } if (<>7__wrap1.MoveNext()) { object current = <>7__wrap1.Current; <>2__current = (TResult)current; <>1__state = 1; return true; } <>m__Finally1(); <>7__wrap1 = null; return false; } catch { //try-fault ((System.IDisposable)this).Dispose(); throw; } } bool System.Collections.IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap1 is System.IDisposable disposable) { disposable.Dispose(); } } [DebuggerHidden] void System.Collections.IEnumerator.Reset() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } [DebuggerHidden] System.Collections.Generic.IEnumerator<TResult> System.Collections.Generic.IEnumerable<TResult>.GetEnumerator() { <CastIterator>d__35<TResult> <CastIterator>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; <CastIterator>d__ = this; } else { <CastIterator>d__ = new <CastIterator>d__35<TResult>(0); } <CastIterator>d__.source = <>3__source; return <CastIterator>d__; } [DebuggerHidden] System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)((System.Collections.Generic.IEnumerable<TResult>)this).GetEnumerator(); } } [CompilerGenerated] private sealed class <ExceptIterator>d__58<TSource> : System.Collections.Generic.IEnumerable<TSource>, System.Collections.IEnumerable, System.Collections.Generic.IEnumerator<TSource>, System.Collections.IEnumerator, System.IDisposable { private int <>1__state; private TSource <>2__current; private int <>l__initialThreadId; private IEqualityComparer<TSource> comparer; public IEqualityComparer<TSource> <>3__comparer; private System.Collections.Generic.IEnumerable<TSource> second; public System.Collections.Generic.IEnumerable<TSource> <>3__second; private System.Collections.Generic.IEnumerable<TSource> first; public System.Collections.Generic.IEnumerable<TSource> <>3__first; private Set<TSource> <set>5__1; private System.Collections.Generic.IEnumerator<TSource> <>7__wrap1; TSource System.Collections.Generic.IEnumerator<TSource>.Current { [DebuggerHidden] get { return <>2__current; } } object System.Collections.IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <ExceptIterator>d__58(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void System.IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } } private bool MoveNext() { try { switch (<>1__state) { default: return false; case 0: { <>1__state = -1; <set>5__1 = new Set<TSource>(comparer); System.Collections.Generic.IEnumerator<TSource> enumerator = second.GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { TSource current = enumerator.Current; <set>5__1.Add(current); } } finally { ((System.IDisposable)enumerator)?.Dispose(); } <>7__wrap1 = first.GetEnumerator(); <>1__state = -3; break; } case 1: <>1__state = -3; break; } while (((System.Collections.IEnumerator)<>7__wrap1).MoveNext()) { TSource current2 = <>7__wrap1.Current; if (<set>5__1.Add(current2)) { <>2__current = current2; <>1__state = 1; return true; } } <>m__Finally1(); <>7__wrap1 = null; return false; } catch { //try-fault ((System.IDisposable)this).Dispose(); throw; } } bool System.Collections.IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap1 != null) { ((System.IDisposable)<>7__wrap1).Dispose(); } } [DebuggerHidden] void System.Collections.IEnumerator.Reset() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } [DebuggerHidden] System.Collections.Generic.IEnumerator<TSource> System.Collections.Generic.IEnumerable<TSource>.GetEnumerator() { <ExceptIterator>d__58<TSource> <ExceptIterator>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; <ExceptIterator>d__ = this; } else { <ExceptIterator>d__ = new <ExceptIterator>d__58<TSource>(0); } <ExceptIterator>d__.first = <>3__first; <ExceptIterator>d__.second = <>3__second; <ExceptIterator>d__.comparer = <>3__comparer; return <ExceptIterator>d__; } [DebuggerHidden] System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)((System.Collections.Generic.IEnumerable<TSource>)this).GetEnumerator(); } } [CompilerGenerated] private sealed class <GroupJoinIterator>d__73<TOuter, TInner, TKey, TResult> : System.Collections.Generic.IEnumerable<TResult>, System.Collections.IEnumerable, System.Collections.Generic.IEnumerator<TResult>, System.Collections.IEnumerator, System.IDisposable { private int <>1__state; private TResult <>2__current; private int <>l__initialThreadId; private System.Collections.Generic.IEnumerable<TOuter> outer; public System.Collections.Generic.IEnumerable<TOuter> <>3__outer; private System.Collections.Generic.IEnumerable<TInner> inner; public System.Collections.Generic.IEnumerable<TInner> <>3__inner; private Func<TInner, TKey> innerKeySelector; public Func<TInner, TKey> <>3__innerKeySelector; private IEqualityComparer<TKey> comparer; public IEqualityComparer<TKey> <>3__comparer; private System.Collections.Generic.IEnumerator<TOuter> <e>5__1; private Func<TOuter, System.Collections.Generic.IEnumerable<TInner>, TResult> resultSelector; public Func<TOuter, System.Collections.Generic.IEnumerable<TInner>, TResult> <>3__resultSelector; private Lookup<TKey, TInner> <lookup>5__2; private Func<TOuter, TKey> outerKeySelector; public Func<TOuter, TKey> <>3__outerKeySelector; TResult System.Collections.Generic.IEnumerator<?>.Current { [DebuggerHidden] get { return <>2__current; } } object System.Collections.IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <GroupJoinIterator>d__73(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void System.IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } } private bool MoveNext() { try { int num = <>1__state; if (num != 0) { if (num != 1) { return false; } <>1__state = -3; if (((System.Collections.IEnumerator)<e>5__1).MoveNext()) { goto IL_0062; } <lookup>5__2 = null; } else { <>1__state = -1; <e>5__1 = outer.GetEnumerator(); <>1__state = -3; if (((System.Collections.IEnumerator)<e>5__1).MoveNext()) { <lookup>5__2 = Lookup<TKey, TInner>.CreateForJoin(inner, innerKeySelector, comparer); goto IL_0062; } } <>m__Finally1(); <e>5__1 = null; return false; IL_0062: TOuter current = <e>5__1.Current; <>2__current = ((Func<TOuter, System.Collections.Generic.IEnumerable<System.Collections.Generic.IEnumerable<TInner>>, ?>)(object)resultSelector).Invoke(current, (System.Collections.Generic.IEnumerable<System.Collections.Generic.IEnumerable<TInner>>)<lookup>5__2[((Func<TOuter, ?>)(object)outerKeySelector).Invoke(current)]); <>1__state = 1; return true; } catch { //try-fault ((System.IDisposable)this).Dispose(); throw; } } bool System.Collections.IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<e>5__1 != null) { ((System.IDisposable)<e>5__1).Dispose(); } } [DebuggerHidden] void System.Collections.IEnumerator.Reset() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } [DebuggerHidden] System.Collections.Generic.IEnumerator<TResult> System.Collections.Generic.IEnumerable<?>.GetEnumerator() { <GroupJoinIterator>d__73<TOuter, TInner, TKey, TResult> <GroupJoinIterator>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; <GroupJoinIterator>d__ = this; } else { <GroupJoinIterator>d__ = new <GroupJoinIterator>d__73<TOuter, TInner, TKey, TResult>(0); } <GroupJoinIterator>d__.outer = <>3__outer; <GroupJoinIterator>d__.inner = <>3__inner; <GroupJoinIterator>d__.outerKeySelector = <>3__outerKeySelector; <GroupJoinIterator>d__.innerKeySelector = <>3__innerKeySelector; <GroupJoinIterator>d__.resultSelector = <>3__resultSelector; <GroupJoinIterator>d__.comparer = <>3__comparer; return <GroupJoinIterator>d__; } [DebuggerHidden] System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)((System.Collections.Generic.IEnumerable<?>)(object)this).GetEnumerator(); } } [CompilerGenerated] private sealed class <IntersectIterator>d__76<TSource> : System.Collections.Generic.IEnumerable<TSource>, System.Collections.IEnumerable, System.Collections.Generic.IEnumerator<TSource>, System.Collections.IEnumerator, System.IDisposable { private int <>1__state; private TSource <>2__current; private int <>l__initialThreadId; private IEqualityComparer<TSource> comparer; public IEqualityComparer<TSource> <>3__comparer; private System.Collections.Generic.IEnumerable<TSource> second; public System.Collections.Generic.IEnumerable<TSource> <>3__second; private System.Collections.Generic.IEnumerable<TSource> first; public System.Collections.Generic.IEnumerable<TSource> <>3__first; private Set<TSource> <set>5__1; private System.Collections.Generic.IEnumerator<TSource> <>7__wrap1; TSource System.Collections.Generic.IEnumerator<TSource>.Current { [DebuggerHidden] get { return <>2__current; } } object System.Collections.IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <IntersectIterator>d__76(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void System.IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } } private bool MoveNext() { try { switch (<>1__state) { default: return false; case 0: { <>1__state = -1; <set>5__1 = new Set<TSource>(comparer); System.Collections.Generic.IEnumerator<TSource> enumerator = second.GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { TSource current = enumerator.Current; <set>5__1.Add(current); } } finally { ((System.IDisposable)enumerator)?.Dispose(); } <>7__wrap1 = first.GetEnumerator(); <>1__state = -3; break; } case 1: <>1__state = -3; break; } while (((System.Collections.IEnumerator)<>7__wrap1).MoveNext()) { TSource current2 = <>7__wrap1.Current; if (<set>5__1.Remove(current2)) { <>2__current = current2; <>1__state = 1; return true; } } <>m__Finally1(); <>7__wrap1 = null; return false; } catch { //try-fault ((System.IDisposable)this).Dispose(); throw; } } bool System.Collections.IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap1 != null) { ((System.IDisposable)<>7__wrap1).Dispose(); } } [DebuggerHidden] void System.Collections.IEnumerator.Reset() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } [DebuggerHidden] System.Collections.Generic.IEnumerator<TSource> System.Collections.Generic.IEnumerable<TSource>.GetEnumerator() { <IntersectIterator>d__76<TSource> <IntersectIterator>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; <IntersectIterator>d__ = this; } else { <IntersectIterator>d__ = new <IntersectIterator>d__76<TSource>(0); } <IntersectIterator>d__.first = <>3__first; <IntersectIterator>d__.second = <>3__second; <IntersectIterator>d__.comparer = <>3__comparer; return <IntersectIterator>d__; } [DebuggerHidden] System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)((System.Collections.Generic.IEnumerable<TSource>)this).GetEnumerator(); } } [CompilerGenerated] private sealed class <JoinIterator>d__80<TOuter, TInner, TKey, TResult> : System.Collections.Generic.IEnumerable<TResult>, System.Collections.IEnumerable, System.Collections.Generic.IEnumerator<TResult>, System.Collections.IEnumerator, System.IDisposable { private int <>1__state; private TResult <>2__current; private int <>l__initialThreadId; private System.Collections.Generic.IEnumerable<TOuter> outer; public System.Collections.Generic.IEnumerable<TOuter> <>3__outer; private System.Collections.Generic.IEnumerable<TInner> inner; public System.Collections.Generic.IEnumerable<TInner> <>3__inner; private Func<TInner, TKey> innerKeySelector; public Func<TInner, TKey> <>3__innerKeySelector; private IEqualityComparer<TKey> comparer; public IEqualityComparer<TKey> <>3__comparer; private System.Collections.Generic.IEnumerator<TOuter> <e>5__1; private Lookup<TKey, TInner> <lookup>5__2; private Func<TOuter, TKey> outerKeySelector; public Func<TOuter, TKey> <>3__outerKeySelector; private Func<TOuter, TInner, TResult> resultSelector; public Func<TOuter, TInner, TResult> <>3__resultSelector; private TOuter <item>5__3; private TInner[] <elements>5__4; private int <i>5__5; private int <count>5__6; TResult System.Collections.Generic.IEnumerator<?>.Current { [DebuggerHidden] get { return <>2__current; } } object System.Collections.IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <JoinIterator>d__80(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void System.IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } } private bool MoveNext() { try { int num = <>1__state; if (num != 0) { if (num != 1) { return false; } <>1__state = -3; int num2 = <i>5__5 + 1; <i>5__5 = num2; goto IL_0116; } <>1__state = -1; <e>5__1 = outer.GetEnumerator(); <>1__state = -3; if (((System.Collections.IEnumerator)<e>5__1).MoveNext()) { <lookup>5__2 = Lookup<TKey, TInner>.CreateForJoin(inner, innerKeySelector, comparer); if (<lookup>5__2.Count != 0) { goto IL_0075; } goto IL_0147; } goto IL_014e; IL_0075: <item>5__3 = <e>5__1.Current; Grouping<TKey, TInner> grouping = <lookup>5__2.GetGrouping(((Func<TOuter, ?>)(object)outerKeySelector).Invoke(<item>5__3), create: false); if (grouping != null) { <count>5__6 = grouping._count; <elements>5__4 = grouping._elements; <i>5__5 = 0; goto IL_0116; } goto IL_012b; IL_0116: if (<i>5__5 != <count>5__6) { <>2__current = ((Func<TOuter, TInner, ?>)(object)resultSelector).Invoke(<item>5__3, <elements>5__4[<i>5__5]); <>1__state = 1; return true; } <elements>5__4 = null; goto IL_012b; IL_0147: <lookup>5__2 = null; goto IL_014e; IL_012b: <item>5__3 = default(TOuter); if (((System.Collections.IEnumerator)<e>5__1).MoveNext()) { goto IL_0075; } goto IL_0147; IL_014e: <>m__Finally1(); <e>5__1 = null; return false; } catch { //try-fault ((System.IDisposable)this).Dispose(); throw; } } bool System.Collections.IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<e>5__1 != null) { ((System.IDisposable)<e>5__1).Dispose(); } } [DebuggerHidden] void System.Collections.IEnumerator.Reset() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } [DebuggerHidden] System.Collections.Generic.IEnumerator<TResult> System.Collections.Generic.IEnumerable<?>.GetEnumerator() { <JoinIterator>d__80<TOuter, TInner, TKey, TResult> <JoinIterator>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; <JoinIterator>d__ = this; } else { <JoinIterator>d__ = new <JoinIterator>d__80<TOuter, TInner, TKey, TResult>(0); } <JoinIterator>d__.outer = <>3__outer; <JoinIterator>d__.inner = <>3__inner; <JoinIterator>d__.outerKeySelector = <>3__outerKeySelector; <JoinIterator>d__.innerKeySelector = <>3__innerKeySelector; <JoinIterator>d__.resultSelector = <>3__resultSelector; <JoinIterator>d__.comparer = <>3__comparer; return <JoinIterator>d__; } [DebuggerHidden] System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)((System.Collections.Generic.IEnumerable<?>)(object)this).GetEnumerator(); } } [CompilerGenerated] private sealed class <SelectIterator>d__150<TSource, TResult> : System.Collections.Generic.IEnumerable<TResult>, System.Collections.IEnumerable, System.Collections.Generic.IEnumerator<TResult>, System.Collections.IEnumerator, System.IDisposable { private int <>1__state; private TResult <>2__current; private int <>l__initialThreadId; private System.Collections.Generic.IEnumerable<TSource> source; public System.Collections.Generic.IEnumerable<TSource> <>3__source; private int <index>5__1; private Func<TSource, int, TResult> selector; public Func<TSource, int, TResult> <>3__selector; private System.Collections.Generic.IEnumerator<TSource> <>7__wrap1; TResult System.Collections.Generic.IEnumerator<?>.Current { [DebuggerHidden] get { return <>2__current; } } object System.Collections.IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <SelectIterator>d__150(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void System.IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } } private bool MoveNext() { checked { try { switch (<>1__state) { default: return false; case 0: <>1__state = -1; <index>5__1 = -1; <>7__wrap1 = source.GetEnumerator(); <>1__state = -3; break; case 1: <>1__state = -3; break; } if (((System.Collections.IEnumerator)<>7__wrap1).MoveNext()) { TSource current = <>7__wrap1.Current; <index>5__1++; <>2__current = ((Func<TSource, int, int>)(object)selector).Invoke(current, <index>5__1); <>1__state = 1; return true; } <>m__Finally1(); <>7__wrap1 = null; return false; } catch { //try-fault ((System.IDisposable)this).Dispose(); throw; } } } bool System.Collections.IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap1 != null) { ((System.IDisposable)<>7__wrap1).Dispose(); } } [DebuggerHidden] void System.Collections.IEnumerator.Reset() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } [DebuggerHidden] System.Collections.Generic.IEnumerator<TResult> System.Collections.Generic.IEnumerable<?>.GetEnumerator() { <SelectIterator>d__150<TSource, TResult> <SelectIterator>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; <SelectIterator>d__ = this; } else { <SelectIterator>d__ = new <SelectIterator>d__150<TSource, TResult>(0); } <SelectIterator>d__.source = <>3__source; <SelectIterator>d__.selector = <>3__selector; return <SelectIterator>d__; } [DebuggerHidden] System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)((System.Collections.Generic.IEnumerable<?>)(object)this).GetEnumerator(); } } [CompilerGenerated] private sealed class <SelectManyIterator>d__159<TSource, TResult> : System.Collections.Generic.IEnumerable<TResult>, System.Collections.IEnumerable, System.Collections.Generic.IEnumerator<TResult>, System.Collections.IEnumerator, System.IDisposable { private int <>1__state; private TResult <>2__current; private int <>l__initialThreadId; private System.Collections.Generic.IEnumerable<TSource> source; public System.Collections.Generic.IEnumerable<TSource> <>3__source; private Func<TSource, System.Collections.Generic.IEnumerable<TResult>> selector; public Func<TSource, System.Collections.Generic.IEnumerable<TResult>> <>3__selector; private System.Collections.Generic.IEnumerator<TSource> <>7__wrap1; private System.Collections.Generic.IEnumerator<TResult> <>7__wrap2; TResult System.Collections.Generic.IEnumerator<?>.Current { [DebuggerHidden] get { return <>2__current; } } object System.Collections.IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <SelectManyIterator>d__159(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void System.IDisposable.Dispose() { int num = <>1__state; if (num != -4 && num != -3 && num != 1) { return; } try { if (num != -4 && num != 1) { return; } try { } finally { <>m__Finally2(); } } finally { <>m__Finally1(); } } private bool MoveNext() { try { int num = <>1__state; if (num != 0) { if (num != 1) { return false; } <>1__state = -4; goto IL_008a; } <>1__state = -1; <>7__wrap1 = source.GetEnumerator(); <>1__state = -3; goto IL_00a4; IL_008a: if (((System.Collections.IEnumerator)<>7__wrap2).MoveNext()) { TResult current = ((System.Collections.Generic.IEnumerator<?>)<>7__wrap2).Current; <>2__current = current; <>1__state = 1; return true; } <>m__Finally2(); <>7__wrap2 = null; goto IL_00a4; IL_00a4: if (((System.Collections.IEnumerator)<>7__wrap1).MoveNext()) { TSource current2 = <>7__wrap1.Current; <>7__wrap2 = ((System.Collections.Generic.IEnumerable<?>)((Func<TSource, System.Collections.Generic.IEnumerable<System.Collections.Generic.IEnumerable<TResult>>>)(object)selector).Invoke(current2)).GetEnumerator(); <>1__state = -4; goto IL_008a; } <>m__Finally1(); <>7__wrap1 = null; return false; } catch { //try-fault ((System.IDisposable)this).Dispose(); throw; } } bool System.Collections.IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap1 != null) { ((System.IDisposable)<>7__wrap1).Dispose(); } } private void <>m__Finally2() { <>1__state = -3; if (<>7__wrap2 != null) { ((System.IDisposable)<>7__wrap2).Dispose(); } } [DebuggerHidden] void System.Collections.IEnumerator.Reset() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } [DebuggerHidden] System.Collections.Generic.IEnumerator<TResult> System.Collections.Generic.IEnumerable<?>.GetEnumerator() { <SelectManyIterator>d__159<TSource, TResult> <SelectManyIterator>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; <SelectManyIterator>d__ = this; } else { <SelectManyIterator>d__ = new <SelectManyIterator>d__159<TSource, TResult>(0); } <SelectManyIterator>d__.source = <>3__source; <SelectManyIterator>d__.selector = <>3__selector; return <SelectManyIterator>d__; } [DebuggerHidden] System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)((System.Collections.Generic.IEnumerable<?>)(object)this).GetEnumerator(); } } [CompilerGenerated] private sealed class <SelectManyIterator>d__161<TSource, TResult> : System.Collections.Generic.IEnumerable<TResult>, System.Collections.IEnumerable, System.Collections.Generic.IEnumerator<TResult>, System.Collections.IEnumerator, System.IDisposable { private int <>1__state; private TResult <>2__current; private int <>l__initialThreadId; private System.Collections.Generic.IEnumerable<TSource> source; public System.Collections.Generic.IEnumerable<TSource> <>3__source; private int <index>5__1; private Func<TSource, int, System.Collections.Generic.IEnumerable<TResult>> selector; public Func<TSource, int, System.Collections.Generic.IEnumerable<TResult>> <>3__selector; private System.Collections.Generic.IEnumerator<TSource> <>7__wrap1; private System.Collections.Generic.IEnumerator<TResul
System.Memory.dll
Decompiled 5 days ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; using System.Buffers.Binary; using System.Buffers.Text; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Numerics; using System.Numerics.Hashing; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Text; using FxResources.System.Memory; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyTitle("System.Memory")] [assembly: AssemblyDescription("System.Memory")] [assembly: AssemblyDefaultAlias("System.Memory")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyProduct("Microsoft® .NET Framework")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyFileVersion("4.6.31308.01")] [assembly: AssemblyInformationalVersion("4.6.31308.01 @BuiltBy: cloudtest-841353dfc000000 @Branch: release/2.1-MSRC @SrcCode: https://github.com/dotnet/corefx/tree/32b491939fbd125f304031c35038b1e14b4e3958")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.0.1.2")] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsByRefLikeAttribute : Attribute { } } namespace FxResources.System.Memory { internal static class SR { } } namespace System { public readonly struct SequencePosition : IEquatable<SequencePosition> { private readonly object _object; private readonly int _integer; public SequencePosition(object @object, int integer) { _object = @object; _integer = integer; } [EditorBrowsable(EditorBrowsableState.Never)] public object GetObject() { return _object; } [EditorBrowsable(EditorBrowsableState.Never)] public int GetInteger() { return _integer; } public bool Equals(SequencePosition other) { if (_integer == other._integer) { return object.Equals(_object, other._object); } return false; } [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { if (obj is SequencePosition other) { return Equals(other); } return false; } [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { return HashHelpers.Combine(_object?.GetHashCode() ?? 0, _integer); } } internal static class ThrowHelper { internal static void ThrowArgumentNullException(System.ExceptionArgument argument) { throw CreateArgumentNullException(argument); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentNullException(System.ExceptionArgument argument) { return new ArgumentNullException(argument.ToString()); } internal static void ThrowArrayTypeMismatchException() { throw CreateArrayTypeMismatchException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArrayTypeMismatchException() { return new ArrayTypeMismatchException(); } internal static void ThrowArgumentException_InvalidTypeWithPointersNotSupported(Type type) { throw CreateArgumentException_InvalidTypeWithPointersNotSupported(type); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentException_InvalidTypeWithPointersNotSupported(Type type) { return new ArgumentException(System.SR.Format(System.SR.Argument_InvalidTypeWithPointersNotSupported, type)); } internal static void ThrowArgumentException_DestinationTooShort() { throw CreateArgumentException_DestinationTooShort(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentException_DestinationTooShort() { return new ArgumentException(System.SR.Argument_DestinationTooShort); } internal static void ThrowIndexOutOfRangeException() { throw CreateIndexOutOfRangeException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateIndexOutOfRangeException() { return new IndexOutOfRangeException(); } internal static void ThrowArgumentOutOfRangeException() { throw CreateArgumentOutOfRangeException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentOutOfRangeException() { return new ArgumentOutOfRangeException(); } internal static void ThrowArgumentOutOfRangeException(System.ExceptionArgument argument) { throw CreateArgumentOutOfRangeException(argument); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentOutOfRangeException(System.ExceptionArgument argument) { return new ArgumentOutOfRangeException(argument.ToString()); } internal static void ThrowArgumentOutOfRangeException_PrecisionTooLarge() { throw CreateArgumentOutOfRangeException_PrecisionTooLarge(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentOutOfRangeException_PrecisionTooLarge() { return new ArgumentOutOfRangeException("precision", System.SR.Format(System.SR.Argument_PrecisionTooLarge, (byte)99)); } internal static void ThrowArgumentOutOfRangeException_SymbolDoesNotFit() { throw CreateArgumentOutOfRangeException_SymbolDoesNotFit(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentOutOfRangeException_SymbolDoesNotFit() { return new ArgumentOutOfRangeException("symbol", System.SR.Argument_BadFormatSpecifier); } internal static void ThrowInvalidOperationException() { throw CreateInvalidOperationException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateInvalidOperationException() { return new InvalidOperationException(); } internal static void ThrowInvalidOperationException_OutstandingReferences() { throw CreateInvalidOperationException_OutstandingReferences(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateInvalidOperationException_OutstandingReferences() { return new InvalidOperationException(System.SR.OutstandingReferences); } internal static void ThrowInvalidOperationException_UnexpectedSegmentType() { throw CreateInvalidOperationException_UnexpectedSegmentType(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateInvalidOperationException_UnexpectedSegmentType() { return new InvalidOperationException(System.SR.UnexpectedSegmentType); } internal static void ThrowInvalidOperationException_EndPositionNotReached() { throw CreateInvalidOperationException_EndPositionNotReached(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateInvalidOperationException_EndPositionNotReached() { return new InvalidOperationException(System.SR.EndPositionNotReached); } internal static void ThrowArgumentOutOfRangeException_PositionOutOfRange() { throw CreateArgumentOutOfRangeException_PositionOutOfRange(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentOutOfRangeException_PositionOutOfRange() { return new ArgumentOutOfRangeException("position"); } internal static void ThrowArgumentOutOfRangeException_OffsetOutOfRange() { throw CreateArgumentOutOfRangeException_OffsetOutOfRange(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentOutOfRangeException_OffsetOutOfRange() { return new ArgumentOutOfRangeException("offset"); } internal static void ThrowObjectDisposedException_ArrayMemoryPoolBuffer() { throw CreateObjectDisposedException_ArrayMemoryPoolBuffer(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateObjectDisposedException_ArrayMemoryPoolBuffer() { return new ObjectDisposedException("ArrayMemoryPoolBuffer"); } internal static void ThrowFormatException_BadFormatSpecifier() { throw CreateFormatException_BadFormatSpecifier(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateFormatException_BadFormatSpecifier() { return new FormatException(System.SR.Argument_BadFormatSpecifier); } internal static void ThrowArgumentException_OverlapAlignmentMismatch() { throw CreateArgumentException_OverlapAlignmentMismatch(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentException_OverlapAlignmentMismatch() { return new ArgumentException(System.SR.Argument_OverlapAlignmentMismatch); } internal static void ThrowNotSupportedException() { throw CreateThrowNotSupportedException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateThrowNotSupportedException() { return new NotSupportedException(); } public static bool TryFormatThrowFormatException(out int bytesWritten) { bytesWritten = 0; ThrowFormatException_BadFormatSpecifier(); return false; } public static bool TryParseThrowFormatException<T>(out T value, out int bytesConsumed) { value = default(T); bytesConsumed = 0; ThrowFormatException_BadFormatSpecifier(); return false; } public static void ThrowArgumentValidationException<T>(ReadOnlySequenceSegment<T> startSegment, int startIndex, ReadOnlySequenceSegment<T> endSegment) { throw CreateArgumentValidationException(startSegment, startIndex, endSegment); } private static Exception CreateArgumentValidationException<T>(ReadOnlySequenceSegment<T> startSegment, int startIndex, ReadOnlySequenceSegment<T> endSegment) { if (startSegment == null) { return CreateArgumentNullException(System.ExceptionArgument.startSegment); } if (endSegment == null) { return CreateArgumentNullException(System.ExceptionArgument.endSegment); } if (startSegment != endSegment && startSegment.RunningIndex > endSegment.RunningIndex) { return CreateArgumentOutOfRangeException(System.ExceptionArgument.endSegment); } if ((uint)startSegment.Memory.Length < (uint)startIndex) { return CreateArgumentOutOfRangeException(System.ExceptionArgument.startIndex); } return CreateArgumentOutOfRangeException(System.ExceptionArgument.endIndex); } public static void ThrowArgumentValidationException(Array array, int start) { throw CreateArgumentValidationException(array, start); } private static Exception CreateArgumentValidationException(Array array, int start) { if (array == null) { return CreateArgumentNullException(System.ExceptionArgument.array); } if ((uint)start > (uint)array.Length) { return CreateArgumentOutOfRangeException(System.ExceptionArgument.start); } return CreateArgumentOutOfRangeException(System.ExceptionArgument.length); } public static void ThrowStartOrEndArgumentValidationException(long start) { throw CreateStartOrEndArgumentValidationException(start); } private static Exception CreateStartOrEndArgumentValidationException(long start) { if (start < 0) { return CreateArgumentOutOfRangeException(System.ExceptionArgument.start); } return CreateArgumentOutOfRangeException(System.ExceptionArgument.length); } } internal enum ExceptionArgument { length, start, minimumBufferSize, elementIndex, comparable, comparer, destination, offset, startSegment, endSegment, startIndex, endIndex, array, culture, manager } internal static class DecimalDecCalc { private static uint D32DivMod1E9(uint hi32, ref uint lo32) { ulong num = ((ulong)hi32 << 32) | lo32; lo32 = (uint)(num / 1000000000); return (uint)(num % 1000000000); } internal static uint DecDivMod1E9(ref MutableDecimal value) { return D32DivMod1E9(D32DivMod1E9(D32DivMod1E9(0u, ref value.High), ref value.Mid), ref value.Low); } internal static void DecAddInt32(ref MutableDecimal value, uint i) { if (D32AddCarry(ref value.Low, i) && D32AddCarry(ref value.Mid, 1u)) { D32AddCarry(ref value.High, 1u); } } private static bool D32AddCarry(ref uint value, uint i) { uint num = value; uint num2 = (value = num + i); if (num2 >= num) { return num2 < i; } return true; } internal static void DecMul10(ref MutableDecimal value) { MutableDecimal d = value; DecShiftLeft(ref value); DecShiftLeft(ref value); DecAdd(ref value, d); DecShiftLeft(ref value); } private static void DecShiftLeft(ref MutableDecimal value) { uint num = (((value.Low & 0x80000000u) != 0) ? 1u : 0u); uint num2 = (((value.Mid & 0x80000000u) != 0) ? 1u : 0u); value.Low <<= 1; value.Mid = (value.Mid << 1) | num; value.High = (value.High << 1) | num2; } private static void DecAdd(ref MutableDecimal value, MutableDecimal d) { if (D32AddCarry(ref value.Low, d.Low) && D32AddCarry(ref value.Mid, 1u)) { D32AddCarry(ref value.High, 1u); } if (D32AddCarry(ref value.Mid, d.Mid)) { D32AddCarry(ref value.High, 1u); } D32AddCarry(ref value.High, d.High); } } internal static class Number { private static class DoubleHelper { public unsafe static uint Exponent(double d) { return (*(uint*)((byte*)(&d) + 4) >> 20) & 0x7FFu; } public unsafe static ulong Mantissa(double d) { return *(uint*)(&d) | ((ulong)(uint)(*(int*)((byte*)(&d) + 4) & 0xFFFFF) << 32); } public unsafe static bool Sign(double d) { return *(uint*)((byte*)(&d) + 4) >> 31 != 0; } } internal const int DECIMAL_PRECISION = 29; private static readonly ulong[] s_rgval64Power10 = new ulong[30] { 11529215046068469760uL, 14411518807585587200uL, 18014398509481984000uL, 11258999068426240000uL, 14073748835532800000uL, 17592186044416000000uL, 10995116277760000000uL, 13743895347200000000uL, 17179869184000000000uL, 10737418240000000000uL, 13421772800000000000uL, 16777216000000000000uL, 10485760000000000000uL, 13107200000000000000uL, 16384000000000000000uL, 14757395258967641293uL, 11805916207174113035uL, 9444732965739290428uL, 15111572745182864686uL, 12089258196146291749uL, 9671406556917033399uL, 15474250491067253438uL, 12379400392853802751uL, 9903520314283042201uL, 15845632502852867522uL, 12676506002282294018uL, 10141204801825835215uL, 16225927682921336344uL, 12980742146337069075uL, 10384593717069655260uL }; private static readonly sbyte[] s_rgexp64Power10 = new sbyte[15] { 4, 7, 10, 14, 17, 20, 24, 27, 30, 34, 37, 40, 44, 47, 50 }; private static readonly ulong[] s_rgval64Power10By16 = new ulong[42] { 10240000000000000000uL, 11368683772161602974uL, 12621774483536188886uL, 14012984643248170708uL, 15557538194652854266uL, 17272337110188889248uL, 9588073174409622172uL, 10644899600020376798uL, 11818212630765741798uL, 13120851772591970216uL, 14567071740625403792uL, 16172698447808779622uL, 17955302187076837696uL, 9967194951097567532uL, 11065809325636130658uL, 12285516299433008778uL, 13639663065038175358uL, 15143067982934716296uL, 16812182738118149112uL, 9332636185032188787uL, 10361307573072618722uL, 16615349947311448416uL, 14965776766268445891uL, 13479973333575319909uL, 12141680576410806707uL, 10936253623915059637uL, 9850501549098619819uL, 17745086042373215136uL, 15983352577617880260uL, 14396524142538228461uL, 12967236152753103031uL, 11679847981112819795uL, 10520271803096747049uL, 9475818434452569218uL, 17070116948172427008uL, 15375394465392026135uL, 13848924157002783096uL, 12474001934591998882uL, 11235582092889474480uL, 10120112665365530972uL, 18230774251475056952uL, 16420821625123739930uL }; private static readonly short[] s_rgexp64Power10By16 = new short[21] { 54, 107, 160, 213, 266, 319, 373, 426, 479, 532, 585, 638, 691, 745, 798, 851, 904, 957, 1010, 1064, 1117 }; public static void RoundNumber(ref NumberBuffer number, int pos) { Span<byte> digits = number.Digits; int i; for (i = 0; i < pos && digits[i] != 0; i++) { } if (i == pos && digits[i] >= 53) { while (i > 0 && digits[i - 1] == 57) { i--; } if (i > 0) { digits[i - 1]++; } else { number.Scale++; digits[0] = 49; i = 1; } } else { while (i > 0 && digits[i - 1] == 48) { i--; } } if (i == 0) { number.Scale = 0; number.IsNegative = false; } digits[i] = 0; } internal static bool NumberBufferToDouble(ref NumberBuffer number, out double value) { double num = NumberToDouble(ref number); uint num2 = DoubleHelper.Exponent(num); ulong num3 = DoubleHelper.Mantissa(num); switch (num2) { case 2047u: value = 0.0; return false; case 0u: if (num3 == 0L) { num = 0.0; } break; } value = num; return true; } public unsafe static bool NumberBufferToDecimal(ref NumberBuffer number, ref decimal value) { MutableDecimal source = default(MutableDecimal); byte* ptr = number.UnsafeDigits; int num = number.Scale; if (*ptr == 0) { if (num > 0) { num = 0; } } else { if (num > 29) { return false; } while ((num > 0 || (*ptr != 0 && num > -28)) && (source.High < 429496729 || (source.High == 429496729 && (source.Mid < 2576980377u || (source.Mid == 2576980377u && (source.Low < 2576980377u || (source.Low == 2576980377u && *ptr <= 53))))))) { DecimalDecCalc.DecMul10(ref source); if (*ptr != 0) { DecimalDecCalc.DecAddInt32(ref source, (uint)(*(ptr++) - 48)); } num--; } if (*(ptr++) >= 53) { bool flag = true; if (*(ptr - 1) == 53 && *(ptr - 2) % 2 == 0) { int num2 = 20; while (*ptr == 48 && num2 != 0) { ptr++; num2--; } if (*ptr == 0 || num2 == 0) { flag = false; } } if (flag) { DecimalDecCalc.DecAddInt32(ref source, 1u); if ((source.High | source.Mid | source.Low) == 0) { source.High = 429496729u; source.Mid = 2576980377u; source.Low = 2576980378u; num++; } } } } if (num > 0) { return false; } if (num <= -29) { source.High = 0u; source.Low = 0u; source.Mid = 0u; source.Scale = 28; } else { source.Scale = -num; } source.IsNegative = number.IsNegative; value = Unsafe.As<MutableDecimal, decimal>(ref source); return true; } public static void DecimalToNumber(decimal value, ref NumberBuffer number) { ref MutableDecimal reference = ref Unsafe.As<decimal, MutableDecimal>(ref value); Span<byte> digits = number.Digits; number.IsNegative = reference.IsNegative; int num = 29; while ((reference.Mid != 0) | (reference.High != 0)) { uint num2 = DecimalDecCalc.DecDivMod1E9(ref reference); for (int i = 0; i < 9; i++) { digits[--num] = (byte)(num2 % 10 + 48); num2 /= 10; } } for (uint num3 = reference.Low; num3 != 0; num3 /= 10) { digits[--num] = (byte)(num3 % 10 + 48); } int num4 = 29 - num; number.Scale = num4 - reference.Scale; Span<byte> digits2 = number.Digits; int index = 0; while (--num4 >= 0) { digits2[index++] = digits[num++]; } digits2[index] = 0; } private static uint DigitsToInt(ReadOnlySpan<byte> digits, int count) { uint value; int bytesConsumed; bool flag = Utf8Parser.TryParse(digits.Slice(0, count), out value, out bytesConsumed, 'D'); return value; } private static ulong Mul32x32To64(uint a, uint b) { return (ulong)a * (ulong)b; } private static ulong Mul64Lossy(ulong a, ulong b, ref int pexp) { ulong num = Mul32x32To64((uint)(a >> 32), (uint)(b >> 32)) + (Mul32x32To64((uint)(a >> 32), (uint)b) >> 32) + (Mul32x32To64((uint)a, (uint)(b >> 32)) >> 32); if ((num & 0x8000000000000000uL) == 0L) { num <<= 1; pexp--; } return num; } private static int abs(int value) { if (value < 0) { return -value; } return value; } private unsafe static double NumberToDouble(ref NumberBuffer number) { ReadOnlySpan<byte> digits = number.Digits; int i = 0; int numDigits = number.NumDigits; int num = numDigits; for (; digits[i] == 48; i++) { num--; } if (num == 0) { return 0.0; } int num2 = Math.Min(num, 9); num -= num2; ulong num3 = DigitsToInt(digits, num2); if (num > 0) { num2 = Math.Min(num, 9); num -= num2; uint b = (uint)(s_rgval64Power10[num2 - 1] >> 64 - s_rgexp64Power10[num2 - 1]); num3 = Mul32x32To64((uint)num3, b) + DigitsToInt(digits.Slice(9), num2); } int num4 = number.Scale - (numDigits - num); int num5 = abs(num4); if (num5 >= 352) { ulong num6 = ((num4 > 0) ? 9218868437227405312uL : 0); if (number.IsNegative) { num6 |= 0x8000000000000000uL; } return *(double*)(&num6); } int pexp = 64; if ((num3 & 0xFFFFFFFF00000000uL) == 0L) { num3 <<= 32; pexp -= 32; } if ((num3 & 0xFFFF000000000000uL) == 0L) { num3 <<= 16; pexp -= 16; } if ((num3 & 0xFF00000000000000uL) == 0L) { num3 <<= 8; pexp -= 8; } if ((num3 & 0xF000000000000000uL) == 0L) { num3 <<= 4; pexp -= 4; } if ((num3 & 0xC000000000000000uL) == 0L) { num3 <<= 2; pexp -= 2; } if ((num3 & 0x8000000000000000uL) == 0L) { num3 <<= 1; pexp--; } int num7 = num5 & 0xF; if (num7 != 0) { int num8 = s_rgexp64Power10[num7 - 1]; pexp += ((num4 < 0) ? (-num8 + 1) : num8); ulong b2 = s_rgval64Power10[num7 + ((num4 < 0) ? 15 : 0) - 1]; num3 = Mul64Lossy(num3, b2, ref pexp); } num7 = num5 >> 4; if (num7 != 0) { int num9 = s_rgexp64Power10By16[num7 - 1]; pexp += ((num4 < 0) ? (-num9 + 1) : num9); ulong b3 = s_rgval64Power10By16[num7 + ((num4 < 0) ? 21 : 0) - 1]; num3 = Mul64Lossy(num3, b3, ref pexp); } if (((uint)(int)num3 & 0x400u) != 0) { ulong num10 = num3 + 1023 + (ulong)(((int)num3 >> 11) & 1); if (num10 < num3) { num10 = (num10 >> 1) | 0x8000000000000000uL; pexp++; } num3 = num10; } pexp += 1022; num3 = ((pexp <= 0) ? ((pexp == -52 && num3 >= 9223372036854775896uL) ? 1 : ((pexp > -52) ? (num3 >> -pexp + 11 + 1) : 0)) : ((pexp < 2047) ? ((ulong)((long)pexp << 52) + ((num3 >> 11) & 0xFFFFFFFFFFFFFL)) : 9218868437227405312uL)); if (number.IsNegative) { num3 |= 0x8000000000000000uL; } return *(double*)(&num3); } } internal ref struct NumberBuffer { public int Scale; public bool IsNegative; public const int BufferSize = 51; private byte _b0; private byte _b1; private byte _b2; private byte _b3; private byte _b4; private byte _b5; private byte _b6; private byte _b7; private byte _b8; private byte _b9; private byte _b10; private byte _b11; private byte _b12; private byte _b13; private byte _b14; private byte _b15; private byte _b16; private byte _b17; private byte _b18; private byte _b19; private byte _b20; private byte _b21; private byte _b22; private byte _b23; private byte _b24; private byte _b25; private byte _b26; private byte _b27; private byte _b28; private byte _b29; private byte _b30; private byte _b31; private byte _b32; private byte _b33; private byte _b34; private byte _b35; private byte _b36; private byte _b37; private byte _b38; private byte _b39; private byte _b40; private byte _b41; private byte _b42; private byte _b43; private byte _b44; private byte _b45; private byte _b46; private byte _b47; private byte _b48; private byte _b49; private byte _b50; public unsafe Span<byte> Digits => new Span<byte>(Unsafe.AsPointer(ref _b0), 51); public unsafe byte* UnsafeDigits => (byte*)Unsafe.AsPointer(ref _b0); public int NumDigits => Digits.IndexOf<byte>(0); [Conditional("DEBUG")] public void CheckConsistency() { } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append('['); stringBuilder.Append('"'); Span<byte> digits = Digits; for (int i = 0; i < 51; i++) { byte b = digits[i]; if (b == 0) { break; } stringBuilder.Append((char)b); } stringBuilder.Append('"'); stringBuilder.Append(", Scale = " + Scale); stringBuilder.Append(", IsNegative = " + IsNegative); stringBuilder.Append(']'); return stringBuilder.ToString(); } } [DebuggerTypeProxy(typeof(System.MemoryDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] public readonly struct Memory<T> { private readonly object _object; private readonly int _index; private readonly int _length; private const int RemoveFlagsBitMask = int.MaxValue; public static Memory<T> Empty => default(Memory<T>); public int Length => _length & 0x7FFFFFFF; public bool IsEmpty => (_length & 0x7FFFFFFF) == 0; public Span<T> Span { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Span<T> result; if (_index < 0) { result = ((MemoryManager<T>)_object).GetSpan(); return result.Slice(_index & 0x7FFFFFFF, _length); } if (typeof(T) == typeof(char) && _object is string text) { result = new Span<T>(Unsafe.As<Pinnable<T>>(text), MemoryExtensions.StringAdjustment, text.Length); return result.Slice(_index, _length); } if (_object != null) { return new Span<T>((T[])_object, _index, _length & 0x7FFFFFFF); } result = default(Span<T>); return result; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory(T[] array) { if (array == null) { this = default(Memory<T>); return; } if (default(T) == null && array.GetType() != typeof(T[])) { System.ThrowHelper.ThrowArrayTypeMismatchException(); } _object = array; _index = 0; _length = array.Length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(T[] array, int start) { if (array == null) { if (start != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } this = default(Memory<T>); return; } if (default(T) == null && array.GetType() != typeof(T[])) { System.ThrowHelper.ThrowArrayTypeMismatchException(); } if ((uint)start > (uint)array.Length) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } _object = array; _index = start; _length = array.Length - start; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory(T[] array, int start, int length) { if (array == null) { if (start != 0 || length != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } this = default(Memory<T>); return; } if (default(T) == null && array.GetType() != typeof(T[])) { System.ThrowHelper.ThrowArrayTypeMismatchException(); } if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } _object = array; _index = start; _length = length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(MemoryManager<T> manager, int length) { if (length < 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } _object = manager; _index = int.MinValue; _length = length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(MemoryManager<T> manager, int start, int length) { if (length < 0 || start < 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } _object = manager; _index = start | int.MinValue; _length = length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(object obj, int start, int length) { _object = obj; _index = start; _length = length; } public static implicit operator Memory<T>(T[] array) { return new Memory<T>(array); } public static implicit operator Memory<T>(ArraySegment<T> segment) { return new Memory<T>(segment.Array, segment.Offset, segment.Count); } public static implicit operator ReadOnlyMemory<T>(Memory<T> memory) { return Unsafe.As<Memory<T>, ReadOnlyMemory<T>>(ref memory); } public override string ToString() { if (typeof(T) == typeof(char)) { if (!(_object is string text)) { return Span.ToString(); } return text.Substring(_index, _length & 0x7FFFFFFF); } return $"System.Memory<{typeof(T).Name}>[{_length & 0x7FFFFFFF}]"; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory<T> Slice(int start) { int length = _length; int num = length & 0x7FFFFFFF; if ((uint)start > (uint)num) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new Memory<T>(_object, _index + start, length - start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory<T> Slice(int start, int length) { int length2 = _length; int num = length2 & 0x7FFFFFFF; if ((uint)start > (uint)num || (uint)length > (uint)(num - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } return new Memory<T>(_object, _index + start, length | (length2 & int.MinValue)); } public void CopyTo(Memory<T> destination) { Span.CopyTo(destination.Span); } public bool TryCopyTo(Memory<T> destination) { return Span.TryCopyTo(destination.Span); } public unsafe MemoryHandle Pin() { if (_index < 0) { return ((MemoryManager<T>)_object).Pin(_index & 0x7FFFFFFF); } if (typeof(T) == typeof(char) && _object is string value) { GCHandle handle = GCHandle.Alloc(value, GCHandleType.Pinned); void* pointer = Unsafe.Add<T>((void*)handle.AddrOfPinnedObject(), _index); return new MemoryHandle(pointer, handle); } if (_object is T[] array) { if (_length < 0) { void* pointer2 = Unsafe.Add<T>(Unsafe.AsPointer(ref MemoryMarshal.GetReference<T>(array)), _index); return new MemoryHandle(pointer2); } GCHandle handle2 = GCHandle.Alloc(array, GCHandleType.Pinned); void* pointer3 = Unsafe.Add<T>((void*)handle2.AddrOfPinnedObject(), _index); return new MemoryHandle(pointer3, handle2); } return default(MemoryHandle); } public T[] ToArray() { return Span.ToArray(); } [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { if (obj is ReadOnlyMemory<T> readOnlyMemory) { return readOnlyMemory.Equals(this); } if (obj is Memory<T> other) { return Equals(other); } return false; } public bool Equals(Memory<T> other) { if (_object == other._object && _index == other._index) { return _length == other._length; } return false; } [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { if (_object == null) { return 0; } int hashCode = _object.GetHashCode(); int index = _index; int hashCode2 = index.GetHashCode(); index = _length; return CombineHashCodes(hashCode, hashCode2, index.GetHashCode()); } private static int CombineHashCodes(int left, int right) { return ((left << 5) + left) ^ right; } private static int CombineHashCodes(int h1, int h2, int h3) { return CombineHashCodes(CombineHashCodes(h1, h2), h3); } } internal sealed class MemoryDebugView<T> { private readonly ReadOnlyMemory<T> _memory; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items => _memory.ToArray(); public MemoryDebugView(Memory<T> memory) { _memory = memory; } public MemoryDebugView(ReadOnlyMemory<T> memory) { _memory = memory; } } public static class MemoryExtensions { internal static readonly IntPtr StringAdjustment = MeasureStringAdjustment(); public static ReadOnlySpan<char> Trim(this ReadOnlySpan<char> span) { return span.TrimStart().TrimEnd(); } public static ReadOnlySpan<char> TrimStart(this ReadOnlySpan<char> span) { int i; for (i = 0; i < span.Length && char.IsWhiteSpace(span[i]); i++) { } return span.Slice(i); } public static ReadOnlySpan<char> TrimEnd(this ReadOnlySpan<char> span) { int num = span.Length - 1; while (num >= 0 && char.IsWhiteSpace(span[num])) { num--; } return span.Slice(0, num + 1); } public static ReadOnlySpan<char> Trim(this ReadOnlySpan<char> span, char trimChar) { return span.TrimStart(trimChar).TrimEnd(trimChar); } public static ReadOnlySpan<char> TrimStart(this ReadOnlySpan<char> span, char trimChar) { int i; for (i = 0; i < span.Length && span[i] == trimChar; i++) { } return span.Slice(i); } public static ReadOnlySpan<char> TrimEnd(this ReadOnlySpan<char> span, char trimChar) { int num = span.Length - 1; while (num >= 0 && span[num] == trimChar) { num--; } return span.Slice(0, num + 1); } public static ReadOnlySpan<char> Trim(this ReadOnlySpan<char> span, ReadOnlySpan<char> trimChars) { return span.TrimStart(trimChars).TrimEnd(trimChars); } public static ReadOnlySpan<char> TrimStart(this ReadOnlySpan<char> span, ReadOnlySpan<char> trimChars) { if (trimChars.IsEmpty) { return span.TrimStart(); } int i; for (i = 0; i < span.Length; i++) { int num = 0; while (num < trimChars.Length) { if (span[i] != trimChars[num]) { num++; continue; } goto IL_003c; } break; IL_003c:; } return span.Slice(i); } public static ReadOnlySpan<char> TrimEnd(this ReadOnlySpan<char> span, ReadOnlySpan<char> trimChars) { if (trimChars.IsEmpty) { return span.TrimEnd(); } int num; for (num = span.Length - 1; num >= 0; num--) { int num2 = 0; while (num2 < trimChars.Length) { if (span[num] != trimChars[num2]) { num2++; continue; } goto IL_0044; } break; IL_0044:; } return span.Slice(0, num + 1); } public static bool IsWhiteSpace(this ReadOnlySpan<char> span) { for (int i = 0; i < span.Length; i++) { if (!char.IsWhiteSpace(span[i])) { return false; } } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf<T>(this Span<T> span, T value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value), span.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.IndexOf(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, char>(ref value), span.Length); } return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf<T>(this Span<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), value.Length); } return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOf<T>(this Span<T> span, T value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value), span.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, char>(ref value), span.Length); } return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOf<T>(this Span<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), value.Length); } return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool SequenceEqual<T>(this Span<T> span, ReadOnlySpan<T> other) where T : IEquatable<T> { int length = span.Length; if (default(T) != null && IsTypeComparableAsBytes<T>(out var size)) { if (length == other.Length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), (NUInt)length * size); } return false; } if (length == other.Length) { return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other), length); } return false; } public static int SequenceCompareTo<T>(this Span<T> span, ReadOnlySpan<T> other) where T : IComparable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), other.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(other)), other.Length); } return System.SpanHelpers.SequenceCompareTo(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(other), other.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf<T>(this ReadOnlySpan<T> span, T value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value), span.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.IndexOf(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, char>(ref value), span.Length); } return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), value.Length); } return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOf<T>(this ReadOnlySpan<T> span, T value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value), span.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, char>(ref value), span.Length); } return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOf<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), value.Length); } return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny<T>(this Span<T> span, T value0, T value1) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), span.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny<T>(this Span<T> span, T value0, T value1, T value2) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), Unsafe.As<T, byte>(ref value2), span.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny<T>(this Span<T> span, ReadOnlySpan<T> values) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(values)), values.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny<T>(this ReadOnlySpan<T> span, T value0, T value1) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), span.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny<T>(this ReadOnlySpan<T> span, T value0, T value1, T value2) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), Unsafe.As<T, byte>(ref value2), span.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> values) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(values)), values.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny<T>(this Span<T> span, T value0, T value1) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), span.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny<T>(this Span<T> span, T value0, T value1, T value2) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), Unsafe.As<T, byte>(ref value2), span.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny<T>(this Span<T> span, ReadOnlySpan<T> values) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(values)), values.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny<T>(this ReadOnlySpan<T> span, T value0, T value1) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), span.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny<T>(this ReadOnlySpan<T> span, T value0, T value1, T value2) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), Unsafe.As<T, byte>(ref value2), span.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> values) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(values)), values.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool SequenceEqual<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> other) where T : IEquatable<T> { int length = span.Length; if (default(T) != null && IsTypeComparableAsBytes<T>(out var size)) { if (length == other.Length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), (NUInt)length * size); } return false; } if (length == other.Length) { return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other), length); } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int SequenceCompareTo<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> other) where T : IComparable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), other.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(other)), other.Length); } return System.SpanHelpers.SequenceCompareTo(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(other), other.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool StartsWith<T>(this Span<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { int length = value.Length; if (default(T) != null && IsTypeComparableAsBytes<T>(out var size)) { if (length <= span.Length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (NUInt)length * size); } return false; } if (length <= span.Length) { return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(value), length); } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool StartsWith<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { int length = value.Length; if (default(T) != null && IsTypeComparableAsBytes<T>(out var size)) { if (length <= span.Length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (NUInt)length * size); } return false; } if (length <= span.Length) { return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(value), length); } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool EndsWith<T>(this Span<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { int length = span.Length; int length2 = value.Length; if (default(T) != null && IsTypeComparableAsBytes<T>(out var size)) { if (length2 <= length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), length - length2)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (NUInt)length2 * size); } return false; } if (length2 <= length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), length - length2), ref MemoryMarshal.GetReference(value), length2); } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool EndsWith<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { int length = span.Length; int length2 = value.Length; if (default(T) != null && IsTypeComparableAsBytes<T>(out var size)) { if (length2 <= length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), length - length2)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (NUInt)length2 * size); } return false; } if (length2 <= length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), length - length2), ref MemoryMarshal.GetReference(value), length2); } return false; } public static void Reverse<T>(this Span<T> span) { ref T reference = ref MemoryMarshal.GetReference(span); int num = 0; int num2 = span.Length - 1; while (num < num2) { T val = Unsafe.Add(ref reference, num); Unsafe.Add(ref reference, num) = Unsafe.Add(ref reference, num2); Unsafe.Add(ref reference, num2) = val; num++; num2--; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<T> AsSpan<T>(this T[] array) { return new Span<T>(array); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<T> AsSpan<T>(this T[] array, int start, int length) { return new Span<T>(array, start, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<T> AsSpan<T>(this ArraySegment<T> segment) { return new Span<T>(segment.Array, segment.Offset, segment.Count); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<T> AsSpan<T>(this ArraySegment<T> segment, int start) { if ((uint)start > segment.Count) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new Span<T>(segment.Array, segment.Offset + start, segment.Count - start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<T> AsSpan<T>(this ArraySegment<T> segment, int start, int length) { if ((uint)start > segment.Count) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } if ((uint)length > segment.Count - start) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.length); } return new Span<T>(segment.Array, segment.Offset + start, length); } public static Memory<T> AsMemory<T>(this T[] array) { return new Memory<T>(array); } public static Memory<T> AsMemory<T>(this T[] array, int start) { return new Memory<T>(array, start); } public static Memory<T> AsMemory<T>(this T[] array, int start, int length) { return new Memory<T>(array, start, length); } public static Memory<T> AsMemory<T>(this ArraySegment<T> segment) { return new Memory<T>(segment.Array, segment.Offset, segment.Count); } public static Memory<T> AsMemory<T>(this ArraySegment<T> segment, int start) { if ((uint)start > segment.Count) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new Memory<T>(segment.Array, segment.Offset + start, segment.Count - start); } public static Memory<T> AsMemory<T>(this ArraySegment<T> segment, int start, int length) { if ((uint)start > segment.Count) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } if ((uint)length > segment.Count - start) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.length); } return new Memory<T>(segment.Array, segment.Offset + start, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void CopyTo<T>(this T[] source, Span<T> destination) { new ReadOnlySpan<T>(source).CopyTo(destination); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void CopyTo<T>(this T[] source, Memory<T> destination) { source.CopyTo(destination.Span); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Overlaps<T>(this Span<T> span, ReadOnlySpan<T> other) { return ((ReadOnlySpan<T>)span).Overlaps(other); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Overlaps<T>(this Span<T> span, ReadOnlySpan<T> other, out int elementOffset) { return ((ReadOnlySpan<T>)span).Overlaps(other, out elementOffset); } public static bool Overlaps<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> other) { if (span.IsEmpty || other.IsEmpty) { return false; } IntPtr intPtr = Unsafe.ByteOffset(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other)); if (Unsafe.SizeOf<IntPtr>() == 4) { if ((uint)(int)intPtr >= (uint)(span.Length * Unsafe.SizeOf<T>())) { return (uint)(int)intPtr > (uint)(-(other.Length * Unsafe.SizeOf<T>())); } return true; } if ((ulong)(long)intPtr >= (ulong)((long)span.Length * (long)Unsafe.SizeOf<T>())) { return (ulong)(long)intPtr > (ulong)(-((long)other.Length * (long)Unsafe.SizeOf<T>())); } return true; } public static bool Overlaps<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> other, out int elementOffset) { if (span.IsEmpty || other.IsEmpty) { elementOffset = 0; return false; } IntPtr intPtr = Unsafe.ByteOffset(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other)); if (Unsafe.SizeOf<IntPtr>() == 4) { if ((uint)(int)intPtr < (uint)(span.Length * Unsafe.SizeOf<T>()) || (uint)(int)intPtr > (uint)(-(other.Length * Unsafe.SizeOf<T>()))) { if ((int)intPtr % Unsafe.SizeOf<T>() != 0) { System.ThrowHelper.ThrowArgumentException_OverlapAlignmentMismatch(); } elementOffset = (int)intPtr / Unsafe.SizeOf<T>(); return true; } elementOffset = 0; return false; } if ((ulong)(long)intPtr < (ulong)((long)span.Length * (long)Unsafe.SizeOf<T>()) || (ulong)(long)intPtr > (ulong)(-((long)other.Length * (long)Unsafe.SizeOf<T>()))) { if ((long)intPtr % Unsafe.SizeOf<T>() != 0L) { System.ThrowHelper.ThrowArgumentException_OverlapAlignmentMismatch(); } elementOffset = (int)((long)intPtr / Unsafe.SizeOf<T>()); return true; } elementOffset = 0; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T>(this Span<T> span, IComparable<T> comparable) { return span.BinarySearch<T, IComparable<T>>(comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T, TComparable>(this Span<T> span, TComparable comparable) where TComparable : IComparable<T> { return BinarySearch((ReadOnlySpan<T>)span, comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T, TComparer>(this Span<T> span, T value, TComparer comparer) where TComparer : IComparer<T> { return ((ReadOnlySpan<T>)span).BinarySearch(value, comparer); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T>(this ReadOnlySpan<T> span, IComparable<T> comparable) { return MemoryExtensions.BinarySearch<T, IComparable<T>>(span, comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T, TComparable>(this ReadOnlySpan<T> span, TComparable comparable) where TComparable : IComparable<T> { return System.SpanHelpers.BinarySearch(span, comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T, TComparer>(this ReadOnlySpan<T> span, T value, TComparer comparer) where TComparer : IComparer<T> { if (comparer == null) { System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.comparer); } System.SpanHelpers.ComparerComparable<T, TComparer> comparable = new System.SpanHelpers.ComparerComparable<T, TComparer>(value, comparer); return BinarySearch(span, comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsTypeComparableAsBytes<T>(out NUInt size) { if (typeof(T) == typeof(byte) || typeof(T) == typeof(sbyte)) { size = (NUInt)1; return true; } if (typeof(T) == typeof(char) || typeof(T) == typeof(short) || typeof(T) == typeof(ushort)) { size = (NUInt)2; return true; } if (typeof(T) == typeof(int) || typeof(T) == typeof(uint)) { size = (NUInt)4; return true; } if (typeof(T) == typeof(long) || typeof(T) == typeof(ulong)) { size = (NUInt)8; return true; } size = default(NUInt); return false; } public static Span<T> AsSpan<T>(this T[] array, int start) { return Span<T>.Create(array, start); } public static bool Contains(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType) { return span.IndexOf(value, comparisonType) >= 0; } public static bool Equals(this ReadOnlySpan<char> span, ReadOnlySpan<char> other, StringComparison comparisonType) { switch (comparisonType) { case StringComparison.Ordinal: return span.SequenceEqual(other); case StringComparison.OrdinalIgnoreCase: if (span.Length != other.Length) { return false; } return EqualsOrdinalIgnoreCase(span, other); default: return span.ToString().Equals(other.ToString(), comparisonType); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool EqualsOrdinalIgnoreCase(ReadOnlySpan<char> span, ReadOnlySpan<char> other) { if (other.Length == 0) { return true; } return CompareToOrdinalIgnoreCase(span, other) == 0; } public static int CompareTo(this ReadOnlySpan<char> span, ReadOnlySpan<char> other, StringComparison comparisonType) { return comparisonType switch { StringComparison.Ordinal => span.SequenceCompareTo(other), StringComparison.OrdinalIgnoreCase => CompareToOrdinalIgnoreCase(span, other), _ => string.Compare(span.ToString(), other.ToString(), comparisonType), }; } private unsafe static int CompareToOrdinalIgnoreCase(ReadOnlySpan<char> strA, ReadOnlySpan<char> strB) { int num = Math.Min(strA.Length, strB.Length); int num2 = num; fixed (char* ptr = &MemoryMarshal.GetReference(strA)) { fixed (char* ptr3 = &MemoryMarshal.GetReference(strB)) { char* ptr2 = ptr; char* ptr4 = ptr3; while (num != 0 && *ptr2 <= '\u007f' && *ptr4 <= '\u007f') { int num3 = *ptr2; int num4 = *ptr4; if (num3 == num4) { ptr2++; ptr4++; num--; continue; } if ((uint)(num3 - 97) <= 25u) { num3 -= 32; } if ((uint)(num4 - 97) <= 25u) { num4 -= 32; } if (num3 != num4) { return num3 - num4; } ptr2++; ptr4++; num--; } if (num == 0) { return strA.Length - strB.Length; } num2 -= num; return string.Compare(strA.Slice(num2).ToString(), strB.Slice(num2).ToString(), StringComparison.OrdinalIgnoreCase); } } } public static int IndexOf(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType) { if (comparisonType == StringComparison.Ordinal) { return span.IndexOf(value); } return span.ToString().IndexOf(value.ToString(), comparisonType); } public static int ToLower(this ReadOnlySpan<char> source, Span<char> destination, CultureInfo culture) { if (culture == null) { System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.culture); } if (destination.Length < source.Length) { return -1; } string text = source.ToString(); string text2 = text.ToLower(culture); AsSpan(text2).CopyTo(destination); return source.Length; } public static int ToLowerInvariant(this ReadOnlySpan<char> source, Span<char> destination) { return source.ToLower(destination, CultureInfo.InvariantCulture); } public static int ToUpper(this ReadOnlySpan<char> source, Span<char> destination, CultureInfo culture) { if (culture == null) { System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.culture); } if (destination.Length < source.Length) { return -1; } string text = source.ToString(); string text2 = text.ToUpper(culture); AsSpan(text2).CopyTo(destination); return source.Length; } public static int ToUpperInvariant(this ReadOnlySpan<char> source, Span<char> destination) { return source.ToUpper(destination, CultureInfo.InvariantCulture); } public static bool EndsWith(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType) { switch (comparisonType) { case StringComparison.Ordinal: return span.EndsWith(value); case StringComparison.OrdinalIgnoreCase: if (value.Length <= span.Length) { return EqualsOrdinalIgnoreCase(span.Slice(span.Length - value.Length), value); } return false; default: { string text = span.ToString(); string value2 = value.ToString(); return text.EndsWith(value2, comparisonType); } } } public static bool StartsWith(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType) { switch (comparisonType) { case StringComparison.Ordinal: return span.StartsWith(value); case StringComparison.OrdinalIgnoreCase: if (value.Length <= span.Length) { return EqualsOrdinalIgnoreCase(span.Slice(0, value.Length), value); } return false; default: { string text = span.ToString(); string value2 = value.ToString(); return text.StartsWith(value2, comparisonType); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<char> AsSpan(this string text) { if (text == null) { return default(ReadOnlySpan<char>); } return new ReadOnlySpan<char>(Unsafe.As<Pinnable<char>>(text), StringAdjustment, text.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<char> AsSpan(this string text, int start) { if (text == null) { if (start != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return default(ReadOnlySpan<char>); } if ((uint)start > (uint)text.Length) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new ReadOnlySpan<char>(Unsafe.As<Pinnable<char>>(text), StringAdjustment + start * 2, text.Length - start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<char> AsSpan(this string text, int start, int length) { if (text == null) { if (start != 0 || length != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return default(ReadOnlySpan<char>); } if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new ReadOnlySpan<char>(Unsafe.As<Pinnable<char>>(text), StringAdjustment + start * 2, length); } public static ReadOnlyMemory<char> AsMemory(this string text) { if (text == null) { return default(ReadOnlyMemory<char>); } return new ReadOnlyMemory<char>(text, 0, text.Length); } public static ReadOnlyMemory<char> AsMemory(this string text, int start) { if (text == null) { if (start != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return default(ReadOnlyMemory<char>); } if ((uint)start > (uint)text.Length) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new ReadOnlyMemory<char>(text, start, text.Length - start); } public static ReadOnlyMemory<char> AsMemory(this string text, int start, int length) { if (text == null) { if (start != 0 || length != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return default(ReadOnlyMemory<char>); } if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new ReadOnlyMemory<char>(text, start, length); } private unsafe static IntPtr MeasureStringAdjustment() { string text = "a"; fixed (char* source = text) { return Unsafe.ByteOffset(ref Unsafe.As<Pinnable<char>>(text).Data, ref Unsafe.AsRef<char>(source)); } } } [DebuggerTypeProxy(typeof(System.MemoryDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] public readonly struct ReadOnlyMemory<T> { private readonly object _object; private readonly int _index; private readonly int _length; internal const int RemoveFlagsBitMask = int.MaxValue; public static ReadOnlyMemory<T> Empty => default(ReadOnlyMemory<T>); public int Length => _length & 0x7FFFFFFF; public bool IsEmpty => (_length & 0x7FFFFFFF) == 0; public ReadOnlySpan<T> Span { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if (_index < 0) { return ((MemoryManager<T>)_object).GetSpan().Slice(_index & 0x7FFFFFFF, _length); } ReadOnlySpan<T> result; if (typeof(T) == typeof(char) && _object is string text) { result = new ReadOnlySpan<T>(Unsafe.As<Pinnable<T>>(text), MemoryExtensions.StringAdjustment, text.Length); return result.Slice(_index, _length); } if (_object != null) { return new ReadOnlySpan<T>((T[])_object, _index, _length & 0x7FFFFFFF); } result = default(ReadOnlySpan<T>); return result; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory(T[] array) { if (array == null) { this = default(ReadOnlyMemory<T>); return; } _object = array; _index = 0; _length = array.Length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory(T[] array, int start, int length) { if (array == null) { if (start != 0 || length != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } this = default(ReadOnlyMemory<T>); return; } if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } _object = array; _index = start; _length = length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ReadOnlyMemory(object obj, int start, int length) { _object = obj; _index = start; _length = length; } public static implicit operator ReadOnlyMemory<T>(T[] array) { return new ReadOnlyMemory<T>(array); } public static implicit operator ReadOnlyMemory<T>(ArraySegment<T> segment) { return new ReadOnlyMemory<T>(segment.Array, segment.Offset, segment.Count); } public override string ToString() { if (typeof(T) == typeof(char)) { if (!(_object is string text)) { return Span.ToString(); } return text.Substring(_index, _length & 0x7FFFFFFF); } return $"System.ReadOnlyMemory<{typeof(T).Name}>[{_length & 0x7FFFFFFF}]"; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory<T> Slice(int start) { int length = _length; int num = length & 0x7FFFFFFF; if ((uint)start > (uint)num) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new ReadOnlyMemory<T>(_object, _index + start, length - start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory<T> Slice(int start, int length) { int length2 = _length; int num = _length & 0x7FFFFFFF; if ((uint)start > (uint)num || (uint)length > (uint)(num - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new ReadOnlyMemory<T>(_object, _index + start, length | (length2 & int.MinValue)); } public void CopyTo(Memory<T> destination) { Span.CopyTo(destination.Span); } public bool TryCopyTo(Memory<T> destination) { return Span.TryCopyTo(destination.Span); } public unsafe MemoryHandle Pin() { if (_index < 0) { return ((MemoryManager<T>)_object).Pin(_index & 0x7FFFFFFF); } if (typeof(T) == typeof(char) && _object is string value) { GCHandle handle = GCHandle.Alloc(value, GCHandleType.Pinned); void* pointer = Unsafe.Add<T>((void*)handle.AddrOfPinnedObject(), _index); return new MemoryHandle(pointer, handle); } if (_object is T[] array) { if (_length < 0) { void* pointer2 = Unsafe.Add<T>(Unsafe.AsPointer(ref MemoryMarshal.GetReference<T>(array)), _index); return new MemoryHandle(pointer2); } GCHandle handle2 = GCHandle.Alloc(array, GCHandleType.Pinned); void* pointer3 = Unsafe.Add<T>((void*)handle2.AddrOfPinnedObject(), _index); return new MemoryHandle(pointer3, handle2); } return default(MemoryHandle); } public T[] ToArray() { return Span.ToArray(); } [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { if (obj is ReadOnlyMemory<T> other) { return Equals(other); } if (obj is Memory<T> memory) { return Equals(memory); } return false; } public bool Equals(ReadOnlyMemory<T> other) { if (_object == other._object && _index == other._index) { return _length == other._length; } return false; } [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { if (_object == null) { return 0; } int hashCode = _object.GetHashCode(); int index = _index; int hashCode2 = index.GetHashCode(); index = _length; return CombineHashCodes(hashCode, hashCode2, index.GetHashCode()); } private static int CombineHashCodes(int left, int right) { return ((left << 5) + left) ^ right; } private static int CombineHashCodes(int h1, int h2, int h3) { return CombineHashCodes(CombineHashCodes(h1, h2), h3); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal object GetObjectStartLength(out int start, out int length) { start = _index; length = _length; return _object; } } [DebuggerTypeProxy(typeof(System.SpanDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] [DebuggerTypeProxy(typeof(System.SpanDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] public readonly ref struct ReadOnlySpan<T> { public ref struct Enumerator { private readonly ReadOnlySpan<T> _span; private int _index; public ref readonly T Current { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return ref _span[_index]; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Enumerator(ReadOnlySpan<T> span) { _span = span; _index = -1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool MoveNext() { int num = _index + 1; if (num < _span.Length) { _index = num; return true; } return false; } } private readonly Pinnable<T> _pinnable; private readonly IntPtr _byteOffset; private readonly int _length; public int Length => _length; public bool IsEmpty => _length == 0; public static ReadOnlySpan<T> Empty => default(ReadOnlySpan<T>); public unsafe ref readonly T this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if ((uint)index >= (uint)_length) { System.ThrowHelper.ThrowIndexOutOfRangeException(); } if (_pinnable == null) { IntPtr byteOffset = _byteOffset; return ref Unsafe.Add(ref Unsafe.AsRef<T>(byteOffset.ToPointer()), index); } return ref Unsafe.Add(ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset), index); } } internal Pinnable<T> Pinnable => _pinnable; internal IntPtr ByteOffset => _byteOffset; public static bool operator !=(ReadOnlySpan<T> left, ReadOnlySpan<T> right) { return !(left == right); } [Obsolete("Equals() on ReadOnlySpan will always throw an exception. Use == instead.")] [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { throw new NotSupportedException(System.SR.NotSupported_CannotCallEqualsOnSpan); } [Obsolete("GetHashCode() on ReadOnlySpan will always throw an exception.")] [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { throw new NotSupportedException(System.SR.NotSupported_CannotCallGetHashCodeOnSpan); } public static implicit operator ReadOnlySpan<T>(T[] array) { return new ReadOnlySpan<T>(array); } public static implicit operator ReadOnlySpan<T>(ArraySegment<T> segment) { return new ReadOnlySpan<T>(segment.Array, segment.Offset, segment.Count); } public Enumerator GetEnumerator() { return new Enumerator(this); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan(T[] array) { if (array == null) { this = default(ReadOnlySpan<T>); return; } _length = array.Length; _pinnable = Unsafe.As<Pinnable<T>>(array); _byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan(T[] array, int start, int length) { if (array == null) { if (start != 0 || length != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } this = default(ReadOnlySpan<T>); return; } if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } _length = length; _pinnable = Unsafe.As<Pinnable<T>>(array); _byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public unsafe ReadOnlySpan(void* pointer, int length) { if (System.SpanHelpers.IsReferenceOrContainsReferences<T>()) { System.ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T)); } if (length < 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } _length = length; _pinnable = null; _byteOffset = new IntPtr(pointer); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ReadOnlySpan(Pinnable<T> pinnable, IntPtr byteOffset, int length) { _length = length; _pinnable = pinnable; _byteOffset = byteOffset; } [EditorBrowsable(EditorBrowsableState.Never)] public unsafe ref readonly T GetPinnableReference() { if (_length != 0) { if (_pinnable == null) { IntPtr byteOffset = _byteOffset; return ref Unsafe.AsRef<T>(byteOffset.ToPointer()); } return ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset); } return ref Unsafe.AsRef<T>(null); } public void CopyTo(Span<T> destination) { if (!TryCopyTo(destination)) { System.ThrowHelper.ThrowArgumentException_DestinationTooShort(); } } public bool TryCopyTo(Span<T> destination) { int length = _length; int length2 = destination.Length; if (length == 0) { return true; } if ((uint)length > (uint)length2) { return false; } ref T src = ref DangerousGetPinnableReference(); System.SpanHelpers.CopyTo(ref destination.DangerousGetPinnableReference(), length2, ref src, length); return true; } public static bool operator ==(ReadOnlySpan<T> left, ReadOnlySpan<T> right) { if (left._length == right._length) { return Unsafe.AreSame(ref left.DangerousGetPinnableReference(), ref right.DangerousGetPinnableReference()); } return false; } public unsafe override string ToString() { if (typeof(T) == typeof(char)) { if (_byteOffset == MemoryExtensions.StringAdjustment) { object obj = Unsafe.As<object>(_pinnable); if (obj is string text && _length == text.Length) { return text; } } fixed (char* value = &Unsafe.As<T, char>(ref DangerousGetPinnableReference())) { return new string(value, 0, _length); } } return $"System.ReadOnlySpan<{typeof(T).Name}>[{_length}]"; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan<T> Slice(int start) { if ((uint)start > (uint)_length) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } IntPtr byteOffset = _byteOffset.Add<T>(start); int length = _length - start; return new ReadOnlySpan<T>(_pinnable, byteOffset, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan<T> Slice(int start, int length) { if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } IntPtr byteOffset = _byteOffset.Add<T>(start); return new ReadOnlySpan<T>(_pinnable, byteOffset, length); } public T[] ToArray() { if (_length == 0) { return System.SpanHelpers.PerTypeValues<T>.EmptyArray; } T[] array = new T[_length]; CopyTo(array); return array; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [EditorBrowsable(EditorBrowsableState.Never)] internal unsafe ref T DangerousGetPinnableReference() { if (_pinnable == null) { IntPtr byteOffset = _byteOffset; return ref Unsafe.AsRef<T>(byteOffset.ToPointer()); } return ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset); } } [DebuggerTypeProxy(typeof(System.SpanDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] [DebuggerTypeProxy(typeof(System.SpanDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] public readonly ref struct Span<T> { public ref struct Enumerator { private readonly Span<T> _span; private int _index; public ref T Current { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return ref _span[_index]; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Enumerator(Span<T> span) { _span = span; _index = -1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool MoveNext() { int num = _index + 1; if (num < _span.Length) { _index = num; return true; } return false; } } private readonly Pinnable<T> _pinnable; private readonly IntPtr _byteOffset; private readonly int _length; public int Length => _length; public bool IsEmpty => _length == 0; public static Span<T> Empty => default(Span<T>); public unsafe ref T this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if ((uint)index >= (uint)_length) { System.ThrowHelper.ThrowIndexOutOfRangeException(); } if (_pinnable == null) { IntPtr byteOffset = _byteOffset; return ref Unsafe.Add(ref Unsafe.AsRef<T>(byteOffset.ToPointer()), index); } return ref Unsafe.Add(ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset), index); } } internal Pinnable<T> Pinnable => _pinnable; internal IntPtr ByteOffset => _byteOffset; public static bool operator !=(Span<T> left, Span<T> right) { return !(left == right); } [Obsolete("Equals() on Span will always throw an exception. Use == instead.")] [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { throw new NotSupportedException(System.SR.NotSupported_CannotCallEqualsOnSpan); } [Obsolete("GetHashCode() on Span will always throw an exception.")] [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { throw new NotSupportedException(System.SR.NotSupported_CannotCallGetHashCodeOnSpan); } public static implicit operator Span<T>(T[] array) { return new Span<T>(array); } public static implicit operator Span<T>(ArraySegment<T> segment) { return new Span<T>(segment.Array, segment.Offset, segment.Count); } public Enumerator GetEnumerator() { return new Enumerator(this); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span(T[] array) { if (array == null) { this = default(Span<T>); return; } if (default(T) == null && array.GetType() != typeof(T[])) { System.ThrowHelper.ThrowArrayTypeMismatchException(); } _length = array.Length; _pinnable = Unsafe.As<Pinnable<T>>(array); _byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static Span<T> Create(T[] array, int start) { if (array == null) { if (start != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return default(Span<T>); } if (default(T) == null && array.GetType() != typeof(T[])) { System.ThrowHelper.ThrowArrayTypeMismatchException(); } if ((uint)start > (uint)array.Length) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } IntPtr byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start); int length = array.Length - start; return new Span<T>(Unsafe.As<Pinnable<T>>(array), byteOffset, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span(T[] array, int start, int length) { if (array == null) { if (start != 0 || length != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } this = default(Span<T>); return; } if (default(T) == null && array.GetType() != typeof(T[])) { System.ThrowHelper.ThrowArrayTypeMismatchException(); } if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } _length = length; _pinnable = Unsafe.As<Pinnable<T>>(array); _byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public unsafe Span(void* pointer, int length) { if (System.SpanHelpers.IsReferenceOrContainsReferences<T>()) { System.ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T)); } if (length < 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } _length = length; _pinnable = null; _byteOffset = new IntPtr(pointer); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Span(Pinnable<T> pinnable, IntPtr byteOffset, int length) { _length = length; _pinnable = pinnable; _byteOffset = byteOffset; } [EditorBrowsable(EditorBrowsableState.Never)] public unsafe ref T GetPinnableReference() { if (_length != 0) { if (_pinnable == null) { IntPtr byteOffset = _byteOffset; return ref Unsafe.AsRef<T>(byteOffset.ToPointer()); } return ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset); } return ref Unsafe.AsRef<T>(null); } public unsafe void Clear() { int length = _length; if (length == 0) { return; } UIntPtr byteLength = (UIntPtr)(ulong)((uint)length * Unsafe.SizeOf<T>()); if ((Unsafe.SizeOf<T>() & (sizeof(IntPtr) - 1)) != 0) { if (_pinnable == null) { IntPtr byteOffset = _byteOffset; byte* ptr = (byte*)byteOffset.ToPointer(); System.SpanHelpers.ClearLessThanPointerSized(ptr, byteLength); } else { System.SpanHelpers.ClearLessThanPointerSized(ref Unsafe.As<T, byte>(ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset)), byteLength); } } else if (System.SpanHelpers.IsReferenceOrContainsReferences<T>()) { UIntPtr pointerSizeLength = (UIntPtr)(ulong)(length * Unsafe.SizeOf<T>() / sizeof(IntPtr)); System.SpanHelpers.ClearPointerSizedWithReferences(ref Unsafe.As<T, IntPtr>(ref DangerousGetPinnableReference()), pointerSizeLength); } else { System.SpanHelpers.ClearPointerSizedWithoutReferences(ref Unsafe.As<T, byte>(ref DangerousGetPinnableReference()), byteLength); } } public unsafe void Fill(T value) { int length = _length; if (length == 0) { return; } if (Unsafe.SizeOf<T>() == 1) { byte value2 = Unsafe.As<T, byte>(ref value); if (_pinnable == null) { IntPtr byteOffset = _byteOffset; Unsafe.InitBlockUnaligned(byteOffset.ToPointer(), value2, (uint)length); } else { Unsafe.InitBlockUnaligned(ref Unsafe.As<T, byte>(ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset)), value2, (uint)length); } return; } ref T source = ref DangerousGetPinnableReference(); int i; for (i = 0; i < (length & -8); i += 8) { Unsafe.Add(ref source, i) = value; Unsafe.Add(ref source, i + 1) = value; Unsafe.Add(ref source, i + 2) = value; Unsafe.Add(ref source, i + 3) = value; Unsafe.Add(ref source, i + 4) = value; Unsafe.Add(ref source, i + 5) = value; Unsafe.Add(ref source, i + 6) = value; Unsafe.Add(ref source, i + 7) = value; } if (i < (length & -4)) { Unsafe.Add(ref source, i) = value; Unsafe.Add(ref source, i + 1) = value; Unsafe.Add(ref source, i + 2) = value; Unsafe.Add(ref source, i + 3) = value; i += 4; } for (; i < length; i++) { Unsafe.Add(ref source, i) = value; } } public void CopyTo(Span<T> destination) { if (!TryCopyTo(destination)) { System.ThrowHelper.ThrowArgumentException_DestinationTooShort(); } } public bool TryCopyTo(Span<T> destination) { int length = _length; int length2 = destination._length; if (length == 0) { return true; } if ((uint)length > (uint)length2) { return false; } ref T src = ref DangerousGetPinnableReference(); System.SpanHelpers.CopyTo(ref destination.DangerousGetPinnableReference(), length2, ref src, length); return true; } public static bool operator ==(Span<T> left, Span<T> right) { if (left._length == right._length) { return Unsafe.AreSame(ref left.DangerousGetPinnableReference(), ref right.DangerousGetPinnableReference()); } return false; } public static implicit operator ReadOnlySpan<T>(Span<T> span) { return new ReadOnlySpan<T>(span._pinnable, span._byteOffset, span._length); } public unsafe override string ToString() { if (typeof(T) == typeof(char)) { fixed (char* value = &Unsafe.As<T, char>(ref DangerousGetPinnableReference())) { return new string(value, 0, _length); } } return $"System.Span<{typeof(T).Name}>[{_length}]"; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<T> Slice(int start) { if ((uint)start > (uint)_length) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } IntPtr byteOffset = _byteOffset.Add<T>(start); int length = _length - start; return new Span<T>(_pinnable, byteOffset, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<T> Slice(int start, int length) { if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } IntPtr byteOffset = _byteOffset.Add<T>(start); return new Span<T>(_pinnable, byteOffset, length); } public T[] ToArray() { if (_length == 0) { return System.SpanHelpers.PerTypeValues<T>.EmptyArray; } T[] array = new T[_length]; CopyTo(array); return array; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [EditorBrowsable(EditorBrowsableState.Never)] internal unsafe ref T DangerousGetPinnableReference() { if (_pinnable == null) { IntPtr byteOffset = _byteOffset; return ref Unsafe.AsRef<T>(byteOffset.ToPointer()); } return ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset); } } internal sealed class SpanDebugView<T> { private readonly T[] _array; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items => _array; public SpanDebugView(Span<T> span) { _array = span.ToArray(); } public SpanDebugView(ReadOnlySpan<T> span) { _array = span.ToArray(); } } internal static class SpanHelpers { internal struct ComparerComparable<T, TComparer> : IComparable<T> where TComparer : IComparer<T> { private readonly T _value; private readonly TComparer _comparer; public ComparerComparable(T value, TComparer comparer) { _value = value; _comparer = comparer; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public int CompareTo(T other) { return _comparer.Compare(_value, other); } } [StructLayout(LayoutKind.Sequential, Size = 64)] private struct Reg64 { } [StructLayout(LayoutKind.Sequential, Size = 32)] private struct Reg32 { } [StructLayout(LayoutKind.Sequential, Size = 16)] private struct Reg16 { } public static class PerTypeValues<T> { public static readonly bool IsReferenceOrContainsReferences = IsReferenceOrContainsReferencesCore(typeof(T)); public static readonly T[] EmptyArray = new T[0]; public static readonly IntPtr ArrayAdjustment = MeasureArrayAdjustment(); private static IntPtr MeasureArrayAdjustment() { T[] array = new T[1]; return Unsafe.ByteOffset(ref Unsafe.As<Pinnable<T>>(array).Data, ref array[0]); } } private const ulong XorPowerOfTwoToHighByte = 283686952306184uL; private const ulong XorPowerOfTwoToHighChar = 4295098372uL; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T, TComparable>(this ReadOnlySpan<T> span, TComparable comparable) where TComparable : IComparable<T> { if (comparable == null) { System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.comparable); } return BinarySearch(ref MemoryMarshal.GetReference(span), span.Length, comparable); } public static int BinarySearch<T, TComparable>(ref T spanStart, int length, TComparable comparable) where TComparable : IComparable<T> { int num = 0; int num2 = length - 1; while (num <= num2) { int num3 = num2 + num >>> 1; int num4 = comparable.CompareTo(Unsafe.Add(ref spanStart, num3)); if (num4 == 0) { return num3; } if (num4 > 0) { num = num3 + 1; } else { num2 = num3 - 1; } } return ~num; } public static int IndexOf(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength) { if (valueLength == 0) { return 0; } byte value2 = value; ref byte second = ref Unsafe.Add(ref value, 1); int num = valueLength - 1; int num2 = 0; while (true) { int num3 = searchSpaceLength - num2 - num; if (num3 <= 0) { break; } int num4 = IndexOf(ref Unsafe.Add(ref searchSpace, num2), value2, num3); if (num4 == -1) { break; } num2 += num4; if (SequenceEqual(ref Unsafe.Add(ref searchSpace, num2 + 1), ref second, num)) { return num2; } num2++; } return -1; } public static int IndexOfAny(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength) { if (valueLength == 0) { return 0; } int num = -1; for (int i = 0; i < valueLength; i++) { int num2 = IndexOf(ref searchSpace, Unsafe.Add(ref value, i), searchSpaceLength); if ((uint)num2 < (uint)num) { num = num2; searchSpaceLength = num2; if (num == 0) { break; } } } return num; } public static int LastIndexOfAny(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength) { if (valueLength == 0) { return 0; } int num = -1; for (int i = 0; i < valueLength; i++) { int num2 = LastIndexOf(ref searchSpace, Unsafe.Add(ref value, i), searchSpaceLength); if (num2 > num) { num = num2; } } return num; } public unsafe static int IndexOf(ref byte searchSpace, byte value, int length) { IntPtr intPtr = (IntPtr)0; IntPtr intPtr2 = (IntPtr)length; if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2) { int num = (int)Unsafe.AsPointer(ref searchSpace) & (Vector<byte>.Count - 1); intPtr2 = (IntPtr)((Vector<byte>.Count - num) & (Vector<byte>.Count - 1)); } while (true) { if ((nuint)(void*)intPtr2 >= (nuint)8u) { intPtr2 -= 8; if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr)) { goto IL_0242; } if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 1)) { goto IL_024a; } if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 2)) { goto IL_0258; } if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 3)) { if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 4)) { if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 5)) { if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 6)) { if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 7)) { break; } intPtr += 8; continue; } return (int)(void*)(intPtr + 6); } return (int)(void*)(intPtr + 5); } return (int)(void*)(intPtr + 4); } goto IL_0266; } if ((nuint)(void*)intPtr2 >= (nuint)4u) { intPtr2 -= 4; if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr)) { goto IL_0242; } if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 1)) { goto IL_024a; } if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 2)) { goto IL_0258; } if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 3)) { goto IL_0266; } intPtr += 4; } while ((void*)intPtr2 != null) { intPtr2 -= 1; if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr)) { intPtr += 1; continue; } goto IL_0242; } if (Vector.IsHardwareAccelerated && (int)(void*)intPtr < length) { intPtr2 = (IntPtr)((length - (int)(void*)intPtr) & ~(Vector<byte>.Count - 1)); Vector<byte> vector = GetVector(value); for (; (void*)intPtr2 > (void*)intPtr; intPtr += Vector<byte>.Count) { Vector<byte> vector2 = Vector.Equals(vector, Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref searchSpace, intPtr))); if (!Vector<byte>.Zero.Equals(vector2)) { return (int)(void*)intPtr + LocateFirstFoundByte(vector2); } } if ((int)(void*)intPtr < length) { intPtr2 = (IntPtr)(length - (int)(void*)intPtr); continue; } } return -1; IL_0266: return (int)(void*)(intPtr + 3); IL_0242: return (int)(void*)intPtr; IL_0258: return (int)(void*)(intPtr + 2); IL_024a: return (int)(void*)(intPtr + 1); } return (int)(void*)(intPtr + 7); } public static int LastIndexOf(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength) { if (valueLength == 0) { return 0; } byte value2 = value; ref byte second = ref Unsafe.Add(ref value, 1); int num = valueLength - 1; int num2 = 0; while (true) { int num3 = searchSpaceLength - num2 - num; if (num3 <= 0) { break; } int num4 = LastIndexOf(ref searchSpace, value2, num3); if (num4 == -1) { break; } if (SequenceEqual(ref Unsafe.Add(ref searchSpace, num4 + 1), ref second, num)) { return num4; } num2 += num3 - num4; } return -1; } public unsafe static int LastIndexOf(ref byte searchSpace, byte value, int length) { IntPtr intPtr = (IntPtr)length; IntPtr intPtr2 = (IntPtr)length; if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2) { int num = (int)Unsafe.AsPointer(ref searchSpace) & (Vector<byte>.Count - 1); intPtr2 = (IntPtr)(((length & (Vector<byte>.Count - 1)) + num) & (Vector<byte>.Count - 1)); } while (true) { if ((nuint)(void*)intPtr2 >= (nuint)8u) { intPtr2 -= 8; intPtr -= 8; if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 7)) { break; } if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 6)) { if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 5)) { if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 4)) { if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 3)) { if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 2)) { if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 1)) { if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr)) { continue; } goto IL_0254; } goto IL_025c; } goto IL_026a; } goto IL_0278; } return (int)(void*)(intPtr + 4); } return (int)(void*)(intPtr + 5); } return (int)(void*)(intPtr + 6); } if ((nuint)(void*)intPtr2 >= (nuint)4u) { intPtr2 -= 4; intPtr -= 4; if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 3)) { goto IL_0278; } if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 2)) { goto IL_026a; } if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 1)) { goto IL_025c; } if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr)) { goto IL_0254; } } while ((void*)intPtr2 != null) { intPtr2 -= 1; intPtr -= 1; if (val
System.Numerics.Vectors.dll
Decompiled 5 days ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Diagnostics; using System.Globalization; using System.Numerics.Hashing; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Text; using FxResources.System.Numerics.Vectors; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyTitle("System.Numerics.Vectors")] [assembly: AssemblyDescription("System.Numerics.Vectors")] [assembly: AssemblyDefaultAlias("System.Numerics.Vectors")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyProduct("Microsoft® .NET Framework")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyFileVersion("4.6.25519.03")] [assembly: AssemblyInformationalVersion("4.6.25519.03 built by: dlab-DDVSOWINAGE013. Commit Hash: 8321c729934c0f8be754953439b88e6e1c120c24")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.1.3.0")] [module: UnverifiableCode] namespace FxResources.System.Numerics.Vectors { internal static class SR { } } namespace System { internal static class MathF { public const float PI = 3.1415927f; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Abs(float x) { return Math.Abs(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Acos(float x) { return (float)Math.Acos(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Cos(float x) { return (float)Math.Cos(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float IEEERemainder(float x, float y) { return (float)Math.IEEERemainder(x, y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Sin(float x) { return (float)Math.Sin(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Sqrt(float x) { return (float)Math.Sqrt(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Tan(float x) { return (float)Math.Tan(x); } } internal static class SR { private static ResourceManager s_resourceManager; private const string s_resourcesName = "FxResources.System.Numerics.Vectors.SR"; private static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(ResourceType)); internal static string Arg_ArgumentOutOfRangeException => GetResourceString("Arg_ArgumentOutOfRangeException", null); internal static string Arg_ElementsInSourceIsGreaterThanDestination => GetResourceString("Arg_ElementsInSourceIsGreaterThanDestination", null); internal static string Arg_NullArgumentNullRef => GetResourceString("Arg_NullArgumentNullRef", null); internal static string Arg_TypeNotSupported => GetResourceString("Arg_TypeNotSupported", null); internal static Type ResourceType => typeof(SR); [MethodImpl(MethodImplOptions.NoInlining)] private static bool UsingResourceKeys() { return false; } internal static string GetResourceString(string resourceKey, string defaultString) { string text = null; try { text = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } if (defaultString != null && resourceKey.Equals(text, StringComparison.Ordinal)) { return defaultString; } return text; } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.All)] internal class __BlockReflectionAttribute : Attribute { } } namespace System.Numerics { internal class ConstantHelper { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static byte GetByteWithAllBitsSet() { byte result = 0; result = byte.MaxValue; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static sbyte GetSByteWithAllBitsSet() { sbyte result = 0; result = -1; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ushort GetUInt16WithAllBitsSet() { ushort result = 0; result = ushort.MaxValue; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static short GetInt16WithAllBitsSet() { short result = 0; result = -1; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint GetUInt32WithAllBitsSet() { uint result = 0u; result = uint.MaxValue; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int GetInt32WithAllBitsSet() { int result = 0; result = -1; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong GetUInt64WithAllBitsSet() { ulong result = 0uL; result = ulong.MaxValue; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static long GetInt64WithAllBitsSet() { long result = 0L; result = -1L; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static float GetSingleWithAllBitsSet() { float result = 0f; *(int*)(&result) = -1; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static double GetDoubleWithAllBitsSet() { double result = 0.0; *(long*)(&result) = -1L; return result; } } [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property)] internal class JitIntrinsicAttribute : Attribute { } [StructLayout(LayoutKind.Explicit)] internal struct Register { [FieldOffset(0)] internal byte byte_0; [FieldOffset(1)] internal byte byte_1; [FieldOffset(2)] internal byte byte_2; [FieldOffset(3)] internal byte byte_3; [FieldOffset(4)] internal byte byte_4; [FieldOffset(5)] internal byte byte_5; [FieldOffset(6)] internal byte byte_6; [FieldOffset(7)] internal byte byte_7; [FieldOffset(8)] internal byte byte_8; [FieldOffset(9)] internal byte byte_9; [FieldOffset(10)] internal byte byte_10; [FieldOffset(11)] internal byte byte_11; [FieldOffset(12)] internal byte byte_12; [FieldOffset(13)] internal byte byte_13; [FieldOffset(14)] internal byte byte_14; [FieldOffset(15)] internal byte byte_15; [FieldOffset(0)] internal sbyte sbyte_0; [FieldOffset(1)] internal sbyte sbyte_1; [FieldOffset(2)] internal sbyte sbyte_2; [FieldOffset(3)] internal sbyte sbyte_3; [FieldOffset(4)] internal sbyte sbyte_4; [FieldOffset(5)] internal sbyte sbyte_5; [FieldOffset(6)] internal sbyte sbyte_6; [FieldOffset(7)] internal sbyte sbyte_7; [FieldOffset(8)] internal sbyte sbyte_8; [FieldOffset(9)] internal sbyte sbyte_9; [FieldOffset(10)] internal sbyte sbyte_10; [FieldOffset(11)] internal sbyte sbyte_11; [FieldOffset(12)] internal sbyte sbyte_12; [FieldOffset(13)] internal sbyte sbyte_13; [FieldOffset(14)] internal sbyte sbyte_14; [FieldOffset(15)] internal sbyte sbyte_15; [FieldOffset(0)] internal ushort uint16_0; [FieldOffset(2)] internal ushort uint16_1; [FieldOffset(4)] internal ushort uint16_2; [FieldOffset(6)] internal ushort uint16_3; [FieldOffset(8)] internal ushort uint16_4; [FieldOffset(10)] internal ushort uint16_5; [FieldOffset(12)] internal ushort uint16_6; [FieldOffset(14)] internal ushort uint16_7; [FieldOffset(0)] internal short int16_0; [FieldOffset(2)] internal short int16_1; [FieldOffset(4)] internal short int16_2; [FieldOffset(6)] internal short int16_3; [FieldOffset(8)] internal short int16_4; [FieldOffset(10)] internal short int16_5; [FieldOffset(12)] internal short int16_6; [FieldOffset(14)] internal short int16_7; [FieldOffset(0)] internal uint uint32_0; [FieldOffset(4)] internal uint uint32_1; [FieldOffset(8)] internal uint uint32_2; [FieldOffset(12)] internal uint uint32_3; [FieldOffset(0)] internal int int32_0; [FieldOffset(4)] internal int int32_1; [FieldOffset(8)] internal int int32_2; [FieldOffset(12)] internal int int32_3; [FieldOffset(0)] internal ulong uint64_0; [FieldOffset(8)] internal ulong uint64_1; [FieldOffset(0)] internal long int64_0; [FieldOffset(8)] internal long int64_1; [FieldOffset(0)] internal float single_0; [FieldOffset(4)] internal float single_1; [FieldOffset(8)] internal float single_2; [FieldOffset(12)] internal float single_3; [FieldOffset(0)] internal double double_0; [FieldOffset(8)] internal double double_1; } public struct Vector<T> : IEquatable<Vector<T>>, IFormattable where T : struct { private struct VectorSizeHelper { internal Vector<T> _placeholder; internal byte _byte; } private System.Numerics.Register register; private static readonly int s_count = InitializeCount(); private static readonly Vector<T> zero = new Vector<T>(GetZeroValue()); private static readonly Vector<T> one = new Vector<T>(GetOneValue()); private static readonly Vector<T> allOnes = new Vector<T>(GetAllBitsSetValue()); [JitIntrinsic] public static int Count => s_count; [JitIntrinsic] public static Vector<T> Zero => zero; [JitIntrinsic] public static Vector<T> One => one; internal static Vector<T> AllOnes => allOnes; [JitIntrinsic] public unsafe T this[int index] { get { if (index >= Count || index < 0) { throw new IndexOutOfRangeException(System.SR.Format(System.SR.Arg_ArgumentOutOfRangeException, index)); } if (typeof(T) == typeof(byte)) { fixed (byte* ptr = ®ister.byte_0) { return (T)(object)ptr[index]; } } if (typeof(T) == typeof(sbyte)) { fixed (sbyte* ptr2 = ®ister.sbyte_0) { return (T)(object)ptr2[index]; } } if (typeof(T) == typeof(ushort)) { fixed (ushort* ptr3 = ®ister.uint16_0) { return (T)(object)ptr3[index]; } } if (typeof(T) == typeof(short)) { fixed (short* ptr4 = ®ister.int16_0) { return (T)(object)ptr4[index]; } } if (typeof(T) == typeof(uint)) { fixed (uint* ptr5 = ®ister.uint32_0) { return (T)(object)ptr5[index]; } } if (typeof(T) == typeof(int)) { fixed (int* ptr6 = ®ister.int32_0) { return (T)(object)ptr6[index]; } } if (typeof(T) == typeof(ulong)) { fixed (ulong* ptr7 = ®ister.uint64_0) { return (T)(object)ptr7[index]; } } if (typeof(T) == typeof(long)) { fixed (long* ptr8 = ®ister.int64_0) { return (T)(object)ptr8[index]; } } if (typeof(T) == typeof(float)) { fixed (float* ptr9 = ®ister.single_0) { return (T)(object)ptr9[index]; } } if (typeof(T) == typeof(double)) { fixed (double* ptr10 = ®ister.double_0) { return (T)(object)ptr10[index]; } } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } } private unsafe static int InitializeCount() { VectorSizeHelper vectorSizeHelper = default(VectorSizeHelper); byte* ptr = &vectorSizeHelper._placeholder.register.byte_0; byte* ptr2 = &vectorSizeHelper._byte; int num = (int)(ptr2 - ptr); int num2 = -1; if (typeof(T) == typeof(byte)) { num2 = 1; } else if (typeof(T) == typeof(sbyte)) { num2 = 1; } else if (typeof(T) == typeof(ushort)) { num2 = 2; } else if (typeof(T) == typeof(short)) { num2 = 2; } else if (typeof(T) == typeof(uint)) { num2 = 4; } else if (typeof(T) == typeof(int)) { num2 = 4; } else if (typeof(T) == typeof(ulong)) { num2 = 8; } else if (typeof(T) == typeof(long)) { num2 = 8; } else if (typeof(T) == typeof(float)) { num2 = 4; } else { if (!(typeof(T) == typeof(double))) { throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } num2 = 8; } return num / num2; } [JitIntrinsic] public unsafe Vector(T value) { this = default(Vector<T>); if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { fixed (byte* ptr = ®ister.byte_0) { for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)value; } } } else if (typeof(T) == typeof(sbyte)) { fixed (sbyte* ptr2 = ®ister.sbyte_0) { for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)value; } } } else if (typeof(T) == typeof(ushort)) { fixed (ushort* ptr3 = ®ister.uint16_0) { for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(object)value; } } } else if (typeof(T) == typeof(short)) { fixed (short* ptr4 = ®ister.int16_0) { for (int l = 0; l < Count; l++) { ptr4[l] = (short)(object)value; } } } else if (typeof(T) == typeof(uint)) { fixed (uint* ptr5 = ®ister.uint32_0) { for (int m = 0; m < Count; m++) { ptr5[m] = (uint)(object)value; } } } else if (typeof(T) == typeof(int)) { fixed (int* ptr6 = ®ister.int32_0) { for (int n = 0; n < Count; n++) { ptr6[n] = (int)(object)value; } } } else if (typeof(T) == typeof(ulong)) { fixed (ulong* ptr7 = ®ister.uint64_0) { for (int num = 0; num < Count; num++) { ptr7[num] = (ulong)(object)value; } } } else if (typeof(T) == typeof(long)) { fixed (long* ptr8 = ®ister.int64_0) { for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (long)(object)value; } } } else if (typeof(T) == typeof(float)) { fixed (float* ptr9 = ®ister.single_0) { for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (float)(object)value; } } } else { if (!(typeof(T) == typeof(double))) { return; } fixed (double* ptr10 = ®ister.double_0) { for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (double)(object)value; } } } } else if (typeof(T) == typeof(byte)) { register.byte_0 = (byte)(object)value; register.byte_1 = (byte)(object)value; register.byte_2 = (byte)(object)value; register.byte_3 = (byte)(object)value; register.byte_4 = (byte)(object)value; register.byte_5 = (byte)(object)value; register.byte_6 = (byte)(object)value; register.byte_7 = (byte)(object)value; register.byte_8 = (byte)(object)value; register.byte_9 = (byte)(object)value; register.byte_10 = (byte)(object)value; register.byte_11 = (byte)(object)value; register.byte_12 = (byte)(object)value; register.byte_13 = (byte)(object)value; register.byte_14 = (byte)(object)value; register.byte_15 = (byte)(object)value; } else if (typeof(T) == typeof(sbyte)) { register.sbyte_0 = (sbyte)(object)value; register.sbyte_1 = (sbyte)(object)value; register.sbyte_2 = (sbyte)(object)value; register.sbyte_3 = (sbyte)(object)value; register.sbyte_4 = (sbyte)(object)value; register.sbyte_5 = (sbyte)(object)value; register.sbyte_6 = (sbyte)(object)value; register.sbyte_7 = (sbyte)(object)value; register.sbyte_8 = (sbyte)(object)value; register.sbyte_9 = (sbyte)(object)value; register.sbyte_10 = (sbyte)(object)value; register.sbyte_11 = (sbyte)(object)value; register.sbyte_12 = (sbyte)(object)value; register.sbyte_13 = (sbyte)(object)value; register.sbyte_14 = (sbyte)(object)value; register.sbyte_15 = (sbyte)(object)value; } else if (typeof(T) == typeof(ushort)) { register.uint16_0 = (ushort)(object)value; register.uint16_1 = (ushort)(object)value; register.uint16_2 = (ushort)(object)value; register.uint16_3 = (ushort)(object)value; register.uint16_4 = (ushort)(object)value; register.uint16_5 = (ushort)(object)value; register.uint16_6 = (ushort)(object)value; register.uint16_7 = (ushort)(object)value; } else if (typeof(T) == typeof(short)) { register.int16_0 = (short)(object)value; register.int16_1 = (short)(object)value; register.int16_2 = (short)(object)value; register.int16_3 = (short)(object)value; register.int16_4 = (short)(object)value; register.int16_5 = (short)(object)value; register.int16_6 = (short)(object)value; register.int16_7 = (short)(object)value; } else if (typeof(T) == typeof(uint)) { register.uint32_0 = (uint)(object)value; register.uint32_1 = (uint)(object)value; register.uint32_2 = (uint)(object)value; register.uint32_3 = (uint)(object)value; } else if (typeof(T) == typeof(int)) { register.int32_0 = (int)(object)value; register.int32_1 = (int)(object)value; register.int32_2 = (int)(object)value; register.int32_3 = (int)(object)value; } else if (typeof(T) == typeof(ulong)) { register.uint64_0 = (ulong)(object)value; register.uint64_1 = (ulong)(object)value; } else if (typeof(T) == typeof(long)) { register.int64_0 = (long)(object)value; register.int64_1 = (long)(object)value; } else if (typeof(T) == typeof(float)) { register.single_0 = (float)(object)value; register.single_1 = (float)(object)value; register.single_2 = (float)(object)value; register.single_3 = (float)(object)value; } else if (typeof(T) == typeof(double)) { register.double_0 = (double)(object)value; register.double_1 = (double)(object)value; } } [JitIntrinsic] public Vector(T[] values) : this(values, 0) { } public unsafe Vector(T[] values, int index) { this = default(Vector<T>); if (values == null) { throw new NullReferenceException(System.SR.Arg_NullArgumentNullRef); } if (index < 0 || values.Length - index < Count) { throw new IndexOutOfRangeException(); } if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { fixed (byte* ptr = ®ister.byte_0) { for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)values[i + index]; } } } else if (typeof(T) == typeof(sbyte)) { fixed (sbyte* ptr2 = ®ister.sbyte_0) { for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)values[j + index]; } } } else if (typeof(T) == typeof(ushort)) { fixed (ushort* ptr3 = ®ister.uint16_0) { for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(object)values[k + index]; } } } else if (typeof(T) == typeof(short)) { fixed (short* ptr4 = ®ister.int16_0) { for (int l = 0; l < Count; l++) { ptr4[l] = (short)(object)values[l + index]; } } } else if (typeof(T) == typeof(uint)) { fixed (uint* ptr5 = ®ister.uint32_0) { for (int m = 0; m < Count; m++) { ptr5[m] = (uint)(object)values[m + index]; } } } else if (typeof(T) == typeof(int)) { fixed (int* ptr6 = ®ister.int32_0) { for (int n = 0; n < Count; n++) { ptr6[n] = (int)(object)values[n + index]; } } } else if (typeof(T) == typeof(ulong)) { fixed (ulong* ptr7 = ®ister.uint64_0) { for (int num = 0; num < Count; num++) { ptr7[num] = (ulong)(object)values[num + index]; } } } else if (typeof(T) == typeof(long)) { fixed (long* ptr8 = ®ister.int64_0) { for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (long)(object)values[num2 + index]; } } } else if (typeof(T) == typeof(float)) { fixed (float* ptr9 = ®ister.single_0) { for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (float)(object)values[num3 + index]; } } } else { if (!(typeof(T) == typeof(double))) { return; } fixed (double* ptr10 = ®ister.double_0) { for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (double)(object)values[num4 + index]; } } } } else if (typeof(T) == typeof(byte)) { fixed (byte* ptr11 = ®ister.byte_0) { *ptr11 = (byte)(object)values[index]; ptr11[1] = (byte)(object)values[1 + index]; ptr11[2] = (byte)(object)values[2 + index]; ptr11[3] = (byte)(object)values[3 + index]; ptr11[4] = (byte)(object)values[4 + index]; ptr11[5] = (byte)(object)values[5 + index]; ptr11[6] = (byte)(object)values[6 + index]; ptr11[7] = (byte)(object)values[7 + index]; ptr11[8] = (byte)(object)values[8 + index]; ptr11[9] = (byte)(object)values[9 + index]; ptr11[10] = (byte)(object)values[10 + index]; ptr11[11] = (byte)(object)values[11 + index]; ptr11[12] = (byte)(object)values[12 + index]; ptr11[13] = (byte)(object)values[13 + index]; ptr11[14] = (byte)(object)values[14 + index]; ptr11[15] = (byte)(object)values[15 + index]; } } else if (typeof(T) == typeof(sbyte)) { fixed (sbyte* ptr12 = ®ister.sbyte_0) { *ptr12 = (sbyte)(object)values[index]; ptr12[1] = (sbyte)(object)values[1 + index]; ptr12[2] = (sbyte)(object)values[2 + index]; ptr12[3] = (sbyte)(object)values[3 + index]; ptr12[4] = (sbyte)(object)values[4 + index]; ptr12[5] = (sbyte)(object)values[5 + index]; ptr12[6] = (sbyte)(object)values[6 + index]; ptr12[7] = (sbyte)(object)values[7 + index]; ptr12[8] = (sbyte)(object)values[8 + index]; ptr12[9] = (sbyte)(object)values[9 + index]; ptr12[10] = (sbyte)(object)values[10 + index]; ptr12[11] = (sbyte)(object)values[11 + index]; ptr12[12] = (sbyte)(object)values[12 + index]; ptr12[13] = (sbyte)(object)values[13 + index]; ptr12[14] = (sbyte)(object)values[14 + index]; ptr12[15] = (sbyte)(object)values[15 + index]; } } else if (typeof(T) == typeof(ushort)) { fixed (ushort* ptr13 = ®ister.uint16_0) { *ptr13 = (ushort)(object)values[index]; ptr13[1] = (ushort)(object)values[1 + index]; ptr13[2] = (ushort)(object)values[2 + index]; ptr13[3] = (ushort)(object)values[3 + index]; ptr13[4] = (ushort)(object)values[4 + index]; ptr13[5] = (ushort)(object)values[5 + index]; ptr13[6] = (ushort)(object)values[6 + index]; ptr13[7] = (ushort)(object)values[7 + index]; } } else if (typeof(T) == typeof(short)) { fixed (short* ptr14 = ®ister.int16_0) { *ptr14 = (short)(object)values[index]; ptr14[1] = (short)(object)values[1 + index]; ptr14[2] = (short)(object)values[2 + index]; ptr14[3] = (short)(object)values[3 + index]; ptr14[4] = (short)(object)values[4 + index]; ptr14[5] = (short)(object)values[5 + index]; ptr14[6] = (short)(object)values[6 + index]; ptr14[7] = (short)(object)values[7 + index]; } } else if (typeof(T) == typeof(uint)) { fixed (uint* ptr15 = ®ister.uint32_0) { *ptr15 = (uint)(object)values[index]; ptr15[1] = (uint)(object)values[1 + index]; ptr15[2] = (uint)(object)values[2 + index]; ptr15[3] = (uint)(object)values[3 + index]; } } else if (typeof(T) == typeof(int)) { fixed (int* ptr16 = ®ister.int32_0) { *ptr16 = (int)(object)values[index]; ptr16[1] = (int)(object)values[1 + index]; ptr16[2] = (int)(object)values[2 + index]; ptr16[3] = (int)(object)values[3 + index]; } } else if (typeof(T) == typeof(ulong)) { fixed (ulong* ptr17 = ®ister.uint64_0) { *ptr17 = (ulong)(object)values[index]; ptr17[1] = (ulong)(object)values[1 + index]; } } else if (typeof(T) == typeof(long)) { fixed (long* ptr18 = ®ister.int64_0) { *ptr18 = (long)(object)values[index]; ptr18[1] = (long)(object)values[1 + index]; } } else if (typeof(T) == typeof(float)) { fixed (float* ptr19 = ®ister.single_0) { *ptr19 = (float)(object)values[index]; ptr19[1] = (float)(object)values[1 + index]; ptr19[2] = (float)(object)values[2 + index]; ptr19[3] = (float)(object)values[3 + index]; } } else if (typeof(T) == typeof(double)) { fixed (double* ptr20 = ®ister.double_0) { *ptr20 = (double)(object)values[index]; ptr20[1] = (double)(object)values[1 + index]; } } } internal unsafe Vector(void* dataPointer) : this(dataPointer, 0) { } internal unsafe Vector(void* dataPointer, int offset) { this = default(Vector<T>); if (typeof(T) == typeof(byte)) { byte* ptr = (byte*)dataPointer; ptr += offset; fixed (byte* ptr2 = ®ister.byte_0) { for (int i = 0; i < Count; i++) { ptr2[i] = ptr[i]; } } return; } if (typeof(T) == typeof(sbyte)) { sbyte* ptr3 = (sbyte*)dataPointer; ptr3 += offset; fixed (sbyte* ptr4 = ®ister.sbyte_0) { for (int j = 0; j < Count; j++) { ptr4[j] = ptr3[j]; } } return; } if (typeof(T) == typeof(ushort)) { ushort* ptr5 = (ushort*)dataPointer; ptr5 += offset; fixed (ushort* ptr6 = ®ister.uint16_0) { for (int k = 0; k < Count; k++) { ptr6[k] = ptr5[k]; } } return; } if (typeof(T) == typeof(short)) { short* ptr7 = (short*)dataPointer; ptr7 += offset; fixed (short* ptr8 = ®ister.int16_0) { for (int l = 0; l < Count; l++) { ptr8[l] = ptr7[l]; } } return; } if (typeof(T) == typeof(uint)) { uint* ptr9 = (uint*)dataPointer; ptr9 += offset; fixed (uint* ptr10 = ®ister.uint32_0) { for (int m = 0; m < Count; m++) { ptr10[m] = ptr9[m]; } } return; } if (typeof(T) == typeof(int)) { int* ptr11 = (int*)dataPointer; ptr11 += offset; fixed (int* ptr12 = ®ister.int32_0) { for (int n = 0; n < Count; n++) { ptr12[n] = ptr11[n]; } } return; } if (typeof(T) == typeof(ulong)) { ulong* ptr13 = (ulong*)dataPointer; ptr13 += offset; fixed (ulong* ptr14 = ®ister.uint64_0) { for (int num = 0; num < Count; num++) { ptr14[num] = ptr13[num]; } } return; } if (typeof(T) == typeof(long)) { long* ptr15 = (long*)dataPointer; ptr15 += offset; fixed (long* ptr16 = ®ister.int64_0) { for (int num2 = 0; num2 < Count; num2++) { ptr16[num2] = ptr15[num2]; } } return; } if (typeof(T) == typeof(float)) { float* ptr17 = (float*)dataPointer; ptr17 += offset; fixed (float* ptr18 = ®ister.single_0) { for (int num3 = 0; num3 < Count; num3++) { ptr18[num3] = ptr17[num3]; } } return; } if (typeof(T) == typeof(double)) { double* ptr19 = (double*)dataPointer; ptr19 += offset; fixed (double* ptr20 = ®ister.double_0) { for (int num4 = 0; num4 < Count; num4++) { ptr20[num4] = ptr19[num4]; } } return; } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } private Vector(ref System.Numerics.Register existingRegister) { register = existingRegister; } [JitIntrinsic] public void CopyTo(T[] destination) { CopyTo(destination, 0); } [JitIntrinsic] public unsafe void CopyTo(T[] destination, int startIndex) { if (destination == null) { throw new NullReferenceException(System.SR.Arg_NullArgumentNullRef); } if (startIndex < 0 || startIndex >= destination.Length) { throw new ArgumentOutOfRangeException("startIndex", System.SR.Format(System.SR.Arg_ArgumentOutOfRangeException, startIndex)); } if (destination.Length - startIndex < Count) { throw new ArgumentException(System.SR.Format(System.SR.Arg_ElementsInSourceIsGreaterThanDestination, startIndex)); } if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { fixed (byte* ptr = (byte[])(object)destination) { for (int i = 0; i < Count; i++) { ptr[startIndex + i] = (byte)(object)this[i]; } } } else if (typeof(T) == typeof(sbyte)) { fixed (sbyte* ptr2 = (sbyte[])(object)destination) { for (int j = 0; j < Count; j++) { ptr2[startIndex + j] = (sbyte)(object)this[j]; } } } else if (typeof(T) == typeof(ushort)) { fixed (ushort* ptr3 = (ushort[])(object)destination) { for (int k = 0; k < Count; k++) { ptr3[startIndex + k] = (ushort)(object)this[k]; } } } else if (typeof(T) == typeof(short)) { fixed (short* ptr4 = (short[])(object)destination) { for (int l = 0; l < Count; l++) { ptr4[startIndex + l] = (short)(object)this[l]; } } } else if (typeof(T) == typeof(uint)) { fixed (uint* ptr5 = (uint[])(object)destination) { for (int m = 0; m < Count; m++) { ptr5[startIndex + m] = (uint)(object)this[m]; } } } else if (typeof(T) == typeof(int)) { fixed (int* ptr6 = (int[])(object)destination) { for (int n = 0; n < Count; n++) { ptr6[startIndex + n] = (int)(object)this[n]; } } } else if (typeof(T) == typeof(ulong)) { fixed (ulong* ptr7 = (ulong[])(object)destination) { for (int num = 0; num < Count; num++) { ptr7[startIndex + num] = (ulong)(object)this[num]; } } } else if (typeof(T) == typeof(long)) { fixed (long* ptr8 = (long[])(object)destination) { for (int num2 = 0; num2 < Count; num2++) { ptr8[startIndex + num2] = (long)(object)this[num2]; } } } else if (typeof(T) == typeof(float)) { fixed (float* ptr9 = (float[])(object)destination) { for (int num3 = 0; num3 < Count; num3++) { ptr9[startIndex + num3] = (float)(object)this[num3]; } } } else { if (!(typeof(T) == typeof(double))) { return; } fixed (double* ptr10 = (double[])(object)destination) { for (int num4 = 0; num4 < Count; num4++) { ptr10[startIndex + num4] = (double)(object)this[num4]; } } } } else if (typeof(T) == typeof(byte)) { fixed (byte* ptr11 = (byte[])(object)destination) { ptr11[startIndex] = register.byte_0; ptr11[startIndex + 1] = register.byte_1; ptr11[startIndex + 2] = register.byte_2; ptr11[startIndex + 3] = register.byte_3; ptr11[startIndex + 4] = register.byte_4; ptr11[startIndex + 5] = register.byte_5; ptr11[startIndex + 6] = register.byte_6; ptr11[startIndex + 7] = register.byte_7; ptr11[startIndex + 8] = register.byte_8; ptr11[startIndex + 9] = register.byte_9; ptr11[startIndex + 10] = register.byte_10; ptr11[startIndex + 11] = register.byte_11; ptr11[startIndex + 12] = register.byte_12; ptr11[startIndex + 13] = register.byte_13; ptr11[startIndex + 14] = register.byte_14; ptr11[startIndex + 15] = register.byte_15; } } else if (typeof(T) == typeof(sbyte)) { fixed (sbyte* ptr12 = (sbyte[])(object)destination) { ptr12[startIndex] = register.sbyte_0; ptr12[startIndex + 1] = register.sbyte_1; ptr12[startIndex + 2] = register.sbyte_2; ptr12[startIndex + 3] = register.sbyte_3; ptr12[startIndex + 4] = register.sbyte_4; ptr12[startIndex + 5] = register.sbyte_5; ptr12[startIndex + 6] = register.sbyte_6; ptr12[startIndex + 7] = register.sbyte_7; ptr12[startIndex + 8] = register.sbyte_8; ptr12[startIndex + 9] = register.sbyte_9; ptr12[startIndex + 10] = register.sbyte_10; ptr12[startIndex + 11] = register.sbyte_11; ptr12[startIndex + 12] = register.sbyte_12; ptr12[startIndex + 13] = register.sbyte_13; ptr12[startIndex + 14] = register.sbyte_14; ptr12[startIndex + 15] = register.sbyte_15; } } else if (typeof(T) == typeof(ushort)) { fixed (ushort* ptr13 = (ushort[])(object)destination) { ptr13[startIndex] = register.uint16_0; ptr13[startIndex + 1] = register.uint16_1; ptr13[startIndex + 2] = register.uint16_2; ptr13[startIndex + 3] = register.uint16_3; ptr13[startIndex + 4] = register.uint16_4; ptr13[startIndex + 5] = register.uint16_5; ptr13[startIndex + 6] = register.uint16_6; ptr13[startIndex + 7] = register.uint16_7; } } else if (typeof(T) == typeof(short)) { fixed (short* ptr14 = (short[])(object)destination) { ptr14[startIndex] = register.int16_0; ptr14[startIndex + 1] = register.int16_1; ptr14[startIndex + 2] = register.int16_2; ptr14[startIndex + 3] = register.int16_3; ptr14[startIndex + 4] = register.int16_4; ptr14[startIndex + 5] = register.int16_5; ptr14[startIndex + 6] = register.int16_6; ptr14[startIndex + 7] = register.int16_7; } } else if (typeof(T) == typeof(uint)) { fixed (uint* ptr15 = (uint[])(object)destination) { ptr15[startIndex] = register.uint32_0; ptr15[startIndex + 1] = register.uint32_1; ptr15[startIndex + 2] = register.uint32_2; ptr15[startIndex + 3] = register.uint32_3; } } else if (typeof(T) == typeof(int)) { fixed (int* ptr16 = (int[])(object)destination) { ptr16[startIndex] = register.int32_0; ptr16[startIndex + 1] = register.int32_1; ptr16[startIndex + 2] = register.int32_2; ptr16[startIndex + 3] = register.int32_3; } } else if (typeof(T) == typeof(ulong)) { fixed (ulong* ptr17 = (ulong[])(object)destination) { ptr17[startIndex] = register.uint64_0; ptr17[startIndex + 1] = register.uint64_1; } } else if (typeof(T) == typeof(long)) { fixed (long* ptr18 = (long[])(object)destination) { ptr18[startIndex] = register.int64_0; ptr18[startIndex + 1] = register.int64_1; } } else if (typeof(T) == typeof(float)) { fixed (float* ptr19 = (float[])(object)destination) { ptr19[startIndex] = register.single_0; ptr19[startIndex + 1] = register.single_1; ptr19[startIndex + 2] = register.single_2; ptr19[startIndex + 3] = register.single_3; } } else if (typeof(T) == typeof(double)) { fixed (double* ptr20 = (double[])(object)destination) { ptr20[startIndex] = register.double_0; ptr20[startIndex + 1] = register.double_1; } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object obj) { if (!(obj is Vector<T>)) { return false; } return Equals((Vector<T>)obj); } [JitIntrinsic] public bool Equals(Vector<T> other) { if (Vector.IsHardwareAccelerated) { for (int i = 0; i < Count; i++) { if (!ScalarEquals(this[i], other[i])) { return false; } } return true; } if (typeof(T) == typeof(byte)) { if (register.byte_0 == other.register.byte_0 && register.byte_1 == other.register.byte_1 && register.byte_2 == other.register.byte_2 && register.byte_3 == other.register.byte_3 && register.byte_4 == other.register.byte_4 && register.byte_5 == other.register.byte_5 && register.byte_6 == other.register.byte_6 && register.byte_7 == other.register.byte_7 && register.byte_8 == other.register.byte_8 && register.byte_9 == other.register.byte_9 && register.byte_10 == other.register.byte_10 && register.byte_11 == other.register.byte_11 && register.byte_12 == other.register.byte_12 && register.byte_13 == other.register.byte_13 && register.byte_14 == other.register.byte_14) { return register.byte_15 == other.register.byte_15; } return false; } if (typeof(T) == typeof(sbyte)) { if (register.sbyte_0 == other.register.sbyte_0 && register.sbyte_1 == other.register.sbyte_1 && register.sbyte_2 == other.register.sbyte_2 && register.sbyte_3 == other.register.sbyte_3 && register.sbyte_4 == other.register.sbyte_4 && register.sbyte_5 == other.register.sbyte_5 && register.sbyte_6 == other.register.sbyte_6 && register.sbyte_7 == other.register.sbyte_7 && register.sbyte_8 == other.register.sbyte_8 && register.sbyte_9 == other.register.sbyte_9 && register.sbyte_10 == other.register.sbyte_10 && register.sbyte_11 == other.register.sbyte_11 && register.sbyte_12 == other.register.sbyte_12 && register.sbyte_13 == other.register.sbyte_13 && register.sbyte_14 == other.register.sbyte_14) { return register.sbyte_15 == other.register.sbyte_15; } return false; } if (typeof(T) == typeof(ushort)) { if (register.uint16_0 == other.register.uint16_0 && register.uint16_1 == other.register.uint16_1 && register.uint16_2 == other.register.uint16_2 && register.uint16_3 == other.register.uint16_3 && register.uint16_4 == other.register.uint16_4 && register.uint16_5 == other.register.uint16_5 && register.uint16_6 == other.register.uint16_6) { return register.uint16_7 == other.register.uint16_7; } return false; } if (typeof(T) == typeof(short)) { if (register.int16_0 == other.register.int16_0 && register.int16_1 == other.register.int16_1 && register.int16_2 == other.register.int16_2 && register.int16_3 == other.register.int16_3 && register.int16_4 == other.register.int16_4 && register.int16_5 == other.register.int16_5 && register.int16_6 == other.register.int16_6) { return register.int16_7 == other.register.int16_7; } return false; } if (typeof(T) == typeof(uint)) { if (register.uint32_0 == other.register.uint32_0 && register.uint32_1 == other.register.uint32_1 && register.uint32_2 == other.register.uint32_2) { return register.uint32_3 == other.register.uint32_3; } return false; } if (typeof(T) == typeof(int)) { if (register.int32_0 == other.register.int32_0 && register.int32_1 == other.register.int32_1 && register.int32_2 == other.register.int32_2) { return register.int32_3 == other.register.int32_3; } return false; } if (typeof(T) == typeof(ulong)) { if (register.uint64_0 == other.register.uint64_0) { return register.uint64_1 == other.register.uint64_1; } return false; } if (typeof(T) == typeof(long)) { if (register.int64_0 == other.register.int64_0) { return register.int64_1 == other.register.int64_1; } return false; } if (typeof(T) == typeof(float)) { if (register.single_0 == other.register.single_0 && register.single_1 == other.register.single_1 && register.single_2 == other.register.single_2) { return register.single_3 == other.register.single_3; } return false; } if (typeof(T) == typeof(double)) { if (register.double_0 == other.register.double_0) { return register.double_1 == other.register.double_1; } return false; } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } public override int GetHashCode() { int num = 0; if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { for (int i = 0; i < Count; i++) { num = HashHelpers.Combine(num, ((byte)(object)this[i]).GetHashCode()); } return num; } if (typeof(T) == typeof(sbyte)) { for (int j = 0; j < Count; j++) { num = HashHelpers.Combine(num, ((sbyte)(object)this[j]).GetHashCode()); } return num; } if (typeof(T) == typeof(ushort)) { for (int k = 0; k < Count; k++) { num = HashHelpers.Combine(num, ((ushort)(object)this[k]).GetHashCode()); } return num; } if (typeof(T) == typeof(short)) { for (int l = 0; l < Count; l++) { num = HashHelpers.Combine(num, ((short)(object)this[l]).GetHashCode()); } return num; } if (typeof(T) == typeof(uint)) { for (int m = 0; m < Count; m++) { num = HashHelpers.Combine(num, ((uint)(object)this[m]).GetHashCode()); } return num; } if (typeof(T) == typeof(int)) { for (int n = 0; n < Count; n++) { num = HashHelpers.Combine(num, ((int)(object)this[n]).GetHashCode()); } return num; } if (typeof(T) == typeof(ulong)) { for (int num2 = 0; num2 < Count; num2++) { num = HashHelpers.Combine(num, ((ulong)(object)this[num2]).GetHashCode()); } return num; } if (typeof(T) == typeof(long)) { for (int num3 = 0; num3 < Count; num3++) { num = HashHelpers.Combine(num, ((long)(object)this[num3]).GetHashCode()); } return num; } if (typeof(T) == typeof(float)) { for (int num4 = 0; num4 < Count; num4++) { num = HashHelpers.Combine(num, ((float)(object)this[num4]).GetHashCode()); } return num; } if (typeof(T) == typeof(double)) { for (int num5 = 0; num5 < Count; num5++) { num = HashHelpers.Combine(num, ((double)(object)this[num5]).GetHashCode()); } return num; } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } if (typeof(T) == typeof(byte)) { num = HashHelpers.Combine(num, register.byte_0.GetHashCode()); num = HashHelpers.Combine(num, register.byte_1.GetHashCode()); num = HashHelpers.Combine(num, register.byte_2.GetHashCode()); num = HashHelpers.Combine(num, register.byte_3.GetHashCode()); num = HashHelpers.Combine(num, register.byte_4.GetHashCode()); num = HashHelpers.Combine(num, register.byte_5.GetHashCode()); num = HashHelpers.Combine(num, register.byte_6.GetHashCode()); num = HashHelpers.Combine(num, register.byte_7.GetHashCode()); num = HashHelpers.Combine(num, register.byte_8.GetHashCode()); num = HashHelpers.Combine(num, register.byte_9.GetHashCode()); num = HashHelpers.Combine(num, register.byte_10.GetHashCode()); num = HashHelpers.Combine(num, register.byte_11.GetHashCode()); num = HashHelpers.Combine(num, register.byte_12.GetHashCode()); num = HashHelpers.Combine(num, register.byte_13.GetHashCode()); num = HashHelpers.Combine(num, register.byte_14.GetHashCode()); return HashHelpers.Combine(num, register.byte_15.GetHashCode()); } if (typeof(T) == typeof(sbyte)) { num = HashHelpers.Combine(num, register.sbyte_0.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_1.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_2.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_3.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_4.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_5.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_6.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_7.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_8.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_9.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_10.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_11.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_12.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_13.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_14.GetHashCode()); return HashHelpers.Combine(num, register.sbyte_15.GetHashCode()); } if (typeof(T) == typeof(ushort)) { num = HashHelpers.Combine(num, register.uint16_0.GetHashCode()); num = HashHelpers.Combine(num, register.uint16_1.GetHashCode()); num = HashHelpers.Combine(num, register.uint16_2.GetHashCode()); num = HashHelpers.Combine(num, register.uint16_3.GetHashCode()); num = HashHelpers.Combine(num, register.uint16_4.GetHashCode()); num = HashHelpers.Combine(num, register.uint16_5.GetHashCode()); num = HashHelpers.Combine(num, register.uint16_6.GetHashCode()); return HashHelpers.Combine(num, register.uint16_7.GetHashCode()); } if (typeof(T) == typeof(short)) { num = HashHelpers.Combine(num, register.int16_0.GetHashCode()); num = HashHelpers.Combine(num, register.int16_1.GetHashCode()); num = HashHelpers.Combine(num, register.int16_2.GetHashCode()); num = HashHelpers.Combine(num, register.int16_3.GetHashCode()); num = HashHelpers.Combine(num, register.int16_4.GetHashCode()); num = HashHelpers.Combine(num, register.int16_5.GetHashCode()); num = HashHelpers.Combine(num, register.int16_6.GetHashCode()); return HashHelpers.Combine(num, register.int16_7.GetHashCode()); } if (typeof(T) == typeof(uint)) { num = HashHelpers.Combine(num, register.uint32_0.GetHashCode()); num = HashHelpers.Combine(num, register.uint32_1.GetHashCode()); num = HashHelpers.Combine(num, register.uint32_2.GetHashCode()); return HashHelpers.Combine(num, register.uint32_3.GetHashCode()); } if (typeof(T) == typeof(int)) { num = HashHelpers.Combine(num, register.int32_0.GetHashCode()); num = HashHelpers.Combine(num, register.int32_1.GetHashCode()); num = HashHelpers.Combine(num, register.int32_2.GetHashCode()); return HashHelpers.Combine(num, register.int32_3.GetHashCode()); } if (typeof(T) == typeof(ulong)) { num = HashHelpers.Combine(num, register.uint64_0.GetHashCode()); return HashHelpers.Combine(num, register.uint64_1.GetHashCode()); } if (typeof(T) == typeof(long)) { num = HashHelpers.Combine(num, register.int64_0.GetHashCode()); return HashHelpers.Combine(num, register.int64_1.GetHashCode()); } if (typeof(T) == typeof(float)) { num = HashHelpers.Combine(num, register.single_0.GetHashCode()); num = HashHelpers.Combine(num, register.single_1.GetHashCode()); num = HashHelpers.Combine(num, register.single_2.GetHashCode()); return HashHelpers.Combine(num, register.single_3.GetHashCode()); } if (typeof(T) == typeof(double)) { num = HashHelpers.Combine(num, register.double_0.GetHashCode()); return HashHelpers.Combine(num, register.double_1.GetHashCode()); } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } public override string ToString() { return ToString("G", CultureInfo.CurrentCulture); } public string ToString(string format) { return ToString(format, CultureInfo.CurrentCulture); } public string ToString(string format, IFormatProvider formatProvider) { StringBuilder stringBuilder = new StringBuilder(); string numberGroupSeparator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator; stringBuilder.Append('<'); for (int i = 0; i < Count - 1; i++) { stringBuilder.Append(((IFormattable)(object)this[i]).ToString(format, formatProvider)); stringBuilder.Append(numberGroupSeparator); stringBuilder.Append(' '); } stringBuilder.Append(((IFormattable)(object)this[Count - 1]).ToString(format, formatProvider)); stringBuilder.Append('>'); return stringBuilder.ToString(); } public unsafe static Vector<T>operator +(Vector<T> left, Vector<T> right) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)]; for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)ScalarAdd(left[i], right[i]); } return new Vector<T>(ptr); } if (typeof(T) == typeof(sbyte)) { sbyte* ptr2 = stackalloc sbyte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)]; for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)ScalarAdd(left[j], right[j]); } return new Vector<T>(ptr2); } if (typeof(T) == typeof(ushort)) { ushort* ptr3 = stackalloc ushort[Count]; for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(object)ScalarAdd(left[k], right[k]); } return new Vector<T>(ptr3); } if (typeof(T) == typeof(short)) { short* ptr4 = stackalloc short[Count]; for (int l = 0; l < Count; l++) { ptr4[l] = (short)(object)ScalarAdd(left[l], right[l]); } return new Vector<T>(ptr4); } if (typeof(T) == typeof(uint)) { uint* ptr5 = stackalloc uint[Count]; for (int m = 0; m < Count; m++) { ptr5[m] = (uint)(object)ScalarAdd(left[m], right[m]); } return new Vector<T>(ptr5); } if (typeof(T) == typeof(int)) { int* ptr6 = stackalloc int[Count]; for (int n = 0; n < Count; n++) { ptr6[n] = (int)(object)ScalarAdd(left[n], right[n]); } return new Vector<T>(ptr6); } if (typeof(T) == typeof(ulong)) { ulong* ptr7 = stackalloc ulong[Count]; for (int num = 0; num < Count; num++) { ptr7[num] = (ulong)(object)ScalarAdd(left[num], right[num]); } return new Vector<T>(ptr7); } if (typeof(T) == typeof(long)) { long* ptr8 = stackalloc long[Count]; for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (long)(object)ScalarAdd(left[num2], right[num2]); } return new Vector<T>(ptr8); } if (typeof(T) == typeof(float)) { float* ptr9 = stackalloc float[Count]; for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (float)(object)ScalarAdd(left[num3], right[num3]); } return new Vector<T>(ptr9); } if (typeof(T) == typeof(double)) { double* ptr10 = stackalloc double[Count]; for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (double)(object)ScalarAdd(left[num4], right[num4]); } return new Vector<T>(ptr10); } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } Vector<T> result = default(Vector<T>); if (typeof(T) == typeof(byte)) { result.register.byte_0 = (byte)(left.register.byte_0 + right.register.byte_0); result.register.byte_1 = (byte)(left.register.byte_1 + right.register.byte_1); result.register.byte_2 = (byte)(left.register.byte_2 + right.register.byte_2); result.register.byte_3 = (byte)(left.register.byte_3 + right.register.byte_3); result.register.byte_4 = (byte)(left.register.byte_4 + right.register.byte_4); result.register.byte_5 = (byte)(left.register.byte_5 + right.register.byte_5); result.register.byte_6 = (byte)(left.register.byte_6 + right.register.byte_6); result.register.byte_7 = (byte)(left.register.byte_7 + right.register.byte_7); result.register.byte_8 = (byte)(left.register.byte_8 + right.register.byte_8); result.register.byte_9 = (byte)(left.register.byte_9 + right.register.byte_9); result.register.byte_10 = (byte)(left.register.byte_10 + right.register.byte_10); result.register.byte_11 = (byte)(left.register.byte_11 + right.register.byte_11); result.register.byte_12 = (byte)(left.register.byte_12 + right.register.byte_12); result.register.byte_13 = (byte)(left.register.byte_13 + right.register.byte_13); result.register.byte_14 = (byte)(left.register.byte_14 + right.register.byte_14); result.register.byte_15 = (byte)(left.register.byte_15 + right.register.byte_15); } else if (typeof(T) == typeof(sbyte)) { result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 + right.register.sbyte_0); result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 + right.register.sbyte_1); result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 + right.register.sbyte_2); result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 + right.register.sbyte_3); result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 + right.register.sbyte_4); result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 + right.register.sbyte_5); result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 + right.register.sbyte_6); result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 + right.register.sbyte_7); result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 + right.register.sbyte_8); result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 + right.register.sbyte_9); result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 + right.register.sbyte_10); result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 + right.register.sbyte_11); result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 + right.register.sbyte_12); result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 + right.register.sbyte_13); result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 + right.register.sbyte_14); result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 + right.register.sbyte_15); } else if (typeof(T) == typeof(ushort)) { result.register.uint16_0 = (ushort)(left.register.uint16_0 + right.register.uint16_0); result.register.uint16_1 = (ushort)(left.register.uint16_1 + right.register.uint16_1); result.register.uint16_2 = (ushort)(left.register.uint16_2 + right.register.uint16_2); result.register.uint16_3 = (ushort)(left.register.uint16_3 + right.register.uint16_3); result.register.uint16_4 = (ushort)(left.register.uint16_4 + right.register.uint16_4); result.register.uint16_5 = (ushort)(left.register.uint16_5 + right.register.uint16_5); result.register.uint16_6 = (ushort)(left.register.uint16_6 + right.register.uint16_6); result.register.uint16_7 = (ushort)(left.register.uint16_7 + right.register.uint16_7); } else if (typeof(T) == typeof(short)) { result.register.int16_0 = (short)(left.register.int16_0 + right.register.int16_0); result.register.int16_1 = (short)(left.register.int16_1 + right.register.int16_1); result.register.int16_2 = (short)(left.register.int16_2 + right.register.int16_2); result.register.int16_3 = (short)(left.register.int16_3 + right.register.int16_3); result.register.int16_4 = (short)(left.register.int16_4 + right.register.int16_4); result.register.int16_5 = (short)(left.register.int16_5 + right.register.int16_5); result.register.int16_6 = (short)(left.register.int16_6 + right.register.int16_6); result.register.int16_7 = (short)(left.register.int16_7 + right.register.int16_7); } else if (typeof(T) == typeof(uint)) { result.register.uint32_0 = left.register.uint32_0 + right.register.uint32_0; result.register.uint32_1 = left.register.uint32_1 + right.register.uint32_1; result.register.uint32_2 = left.register.uint32_2 + right.register.uint32_2; result.register.uint32_3 = left.register.uint32_3 + right.register.uint32_3; } else if (typeof(T) == typeof(int)) { result.register.int32_0 = left.register.int32_0 + right.register.int32_0; result.register.int32_1 = left.register.int32_1 + right.register.int32_1; result.register.int32_2 = left.register.int32_2 + right.register.int32_2; result.register.int32_3 = left.register.int32_3 + right.register.int32_3; } else if (typeof(T) == typeof(ulong)) { result.register.uint64_0 = left.register.uint64_0 + right.register.uint64_0; result.register.uint64_1 = left.register.uint64_1 + right.register.uint64_1; } else if (typeof(T) == typeof(long)) { result.register.int64_0 = left.register.int64_0 + right.register.int64_0; result.register.int64_1 = left.register.int64_1 + right.register.int64_1; } else if (typeof(T) == typeof(float)) { result.register.single_0 = left.register.single_0 + right.register.single_0; result.register.single_1 = left.register.single_1 + right.register.single_1; result.register.single_2 = left.register.single_2 + right.register.single_2; result.register.single_3 = left.register.single_3 + right.register.single_3; } else if (typeof(T) == typeof(double)) { result.register.double_0 = left.register.double_0 + right.register.double_0; result.register.double_1 = left.register.double_1 + right.register.double_1; } return result; } public unsafe static Vector<T>operator -(Vector<T> left, Vector<T> right) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)]; for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)ScalarSubtract(left[i], right[i]); } return new Vector<T>(ptr); } if (typeof(T) == typeof(sbyte)) { sbyte* ptr2 = stackalloc sbyte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)]; for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)ScalarSubtract(left[j], right[j]); } return new Vector<T>(ptr2); } if (typeof(T) == typeof(ushort)) { ushort* ptr3 = stackalloc ushort[Count]; for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(object)ScalarSubtract(left[k], right[k]); } return new Vector<T>(ptr3); } if (typeof(T) == typeof(short)) { short* ptr4 = stackalloc short[Count]; for (int l = 0; l < Count; l++) { ptr4[l] = (short)(object)ScalarSubtract(left[l], right[l]); } return new Vector<T>(ptr4); } if (typeof(T) == typeof(uint)) { uint* ptr5 = stackalloc uint[Count]; for (int m = 0; m < Count; m++) { ptr5[m] = (uint)(object)ScalarSubtract(left[m], right[m]); } return new Vector<T>(ptr5); } if (typeof(T) == typeof(int)) { int* ptr6 = stackalloc int[Count]; for (int n = 0; n < Count; n++) { ptr6[n] = (int)(object)ScalarSubtract(left[n], right[n]); } return new Vector<T>(ptr6); } if (typeof(T) == typeof(ulong)) { ulong* ptr7 = stackalloc ulong[Count]; for (int num = 0; num < Count; num++) { ptr7[num] = (ulong)(object)ScalarSubtract(left[num], right[num]); } return new Vector<T>(ptr7); } if (typeof(T) == typeof(long)) { long* ptr8 = stackalloc long[Count]; for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (long)(object)ScalarSubtract(left[num2], right[num2]); } return new Vector<T>(ptr8); } if (typeof(T) == typeof(float)) { float* ptr9 = stackalloc float[Count]; for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (float)(object)ScalarSubtract(left[num3], right[num3]); } return new Vector<T>(ptr9); } if (typeof(T) == typeof(double)) { double* ptr10 = stackalloc double[Count]; for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (double)(object)ScalarSubtract(left[num4], right[num4]); } return new Vector<T>(ptr10); } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } Vector<T> result = default(Vector<T>); if (typeof(T) == typeof(byte)) { result.register.byte_0 = (byte)(left.register.byte_0 - right.register.byte_0); result.register.byte_1 = (byte)(left.register.byte_1 - right.register.byte_1); result.register.byte_2 = (byte)(left.register.byte_2 - right.register.byte_2); result.register.byte_3 = (byte)(left.register.byte_3 - right.register.byte_3); result.register.byte_4 = (byte)(left.register.byte_4 - right.register.byte_4); result.register.byte_5 = (byte)(left.register.byte_5 - right.register.byte_5); result.register.byte_6 = (byte)(left.register.byte_6 - right.register.byte_6); result.register.byte_7 = (byte)(left.register.byte_7 - right.register.byte_7); result.register.byte_8 = (byte)(left.register.byte_8 - right.register.byte_8); result.register.byte_9 = (byte)(left.register.byte_9 - right.register.byte_9); result.register.byte_10 = (byte)(left.register.byte_10 - right.register.byte_10); result.register.byte_11 = (byte)(left.register.byte_11 - right.register.byte_11); result.register.byte_12 = (byte)(left.register.byte_12 - right.register.byte_12); result.register.byte_13 = (byte)(left.register.byte_13 - right.register.byte_13); result.register.byte_14 = (byte)(left.register.byte_14 - right.register.byte_14); result.register.byte_15 = (byte)(left.register.byte_15 - right.register.byte_15); } else if (typeof(T) == typeof(sbyte)) { result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 - right.register.sbyte_0); result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 - right.register.sbyte_1); result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 - right.register.sbyte_2); result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 - right.register.sbyte_3); result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 - right.register.sbyte_4); result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 - right.register.sbyte_5); result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 - right.register.sbyte_6); result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 - right.register.sbyte_7); result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 - right.register.sbyte_8); result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 - right.register.sbyte_9); result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 - right.register.sbyte_10); result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 - right.register.sbyte_11); result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 - right.register.sbyte_12); result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 - right.register.sbyte_13); result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 - right.register.sbyte_14); result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 - right.register.sbyte_15); } else if (typeof(T) == typeof(ushort)) { result.register.uint16_0 = (ushort)(left.register.uint16_0 - right.register.uint16_0); result.register.uint16_1 = (ushort)(left.register.uint16_1 - right.register.uint16_1); result.register.uint16_2 = (ushort)(left.register.uint16_2 - right.register.uint16_2); result.register.uint16_3 = (ushort)(left.register.uint16_3 - right.register.uint16_3); result.register.uint16_4 = (ushort)(left.register.uint16_4 - right.register.uint16_4); result.register.uint16_5 = (ushort)(left.register.uint16_5 - right.register.uint16_5); result.register.uint16_6 = (ushort)(left.register.uint16_6 - right.register.uint16_6); result.register.uint16_7 = (ushort)(left.register.uint16_7 - right.register.uint16_7); } else if (typeof(T) == typeof(short)) { result.register.int16_0 = (short)(left.register.int16_0 - right.register.int16_0); result.register.int16_1 = (short)(left.register.int16_1 - right.register.int16_1); result.register.int16_2 = (short)(left.register.int16_2 - right.register.int16_2); result.register.int16_3 = (short)(left.register.int16_3 - right.register.int16_3); result.register.int16_4 = (short)(left.register.int16_4 - right.register.int16_4); result.register.int16_5 = (short)(left.register.int16_5 - right.register.int16_5); result.register.int16_6 = (short)(left.register.int16_6 - right.register.int16_6); result.register.int16_7 = (short)(left.register.int16_7 - right.register.int16_7); } else if (typeof(T) == typeof(uint)) { result.register.uint32_0 = left.register.uint32_0 - right.register.uint32_0; result.register.uint32_1 = left.register.uint32_1 - right.register.uint32_1; result.register.uint32_2 = left.register.uint32_2 - right.register.uint32_2; result.register.uint32_3 = left.register.uint32_3 - right.register.uint32_3; } else if (typeof(T) == typeof(int)) { result.register.int32_0 = left.register.int32_0 - right.register.int32_0; result.register.int32_1 = left.register.int32_1 - right.register.int32_1; result.register.int32_2 = left.register.int32_2 - right.register.int32_2; result.register.int32_3 = left.register.int32_3 - right.register.int32_3; } else if (typeof(T) == typeof(ulong)) { result.register.uint64_0 = left.register.uint64_0 - right.register.uint64_0; result.register.uint64_1 = left.register.uint64_1 - right.register.uint64_1; } else if (typeof(T) == typeof(long)) { result.register.int64_0 = left.register.int64_0 - right.register.int64_0; result.register.int64_1 = left.register.int64_1 - right.register.int64_1; } else if (typeof(T) == typeof(float)) { result.register.single_0 = left.register.single_0 - right.register.single_0; result.register.single_1 = left.register.single_1 - right.register.single_1; result.register.single_2 = left.register.single_2 - right.register.single_2; result.register.single_3 = left.register.single_3 - right.register.single_3; } else if (typeof(T) == typeof(double)) { result.register.double_0 = left.register.double_0 - right.register.double_0; result.register.double_1 = left.register.double_1 - right.register.double_1; } return result; } public unsafe static Vector<T>operator *(Vector<T> left, Vector<T> right) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)]; for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)ScalarMultiply(left[i], right[i]); } return new Vector<T>(ptr); } if (typeof(T) == typeof(sbyte)) { sbyte* ptr2 = stackalloc sbyte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)]; for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)ScalarMultiply(left[j], right[j]); } return new Vector<T>(ptr2); } if (typeof(T) == typeof(ushort)) { ushort* ptr3 = stackalloc ushort[Count]; for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(object)ScalarMultiply(left[k], right[k]); } return new Vector<T>(ptr3); } if (typeof(T) == typeof(short)) { short* ptr4 = stackalloc short[Count]; for (int l = 0; l < Count; l++) { ptr4[l] = (short)(object)ScalarMultiply(left[l], right[l]); } return new Vector<T>(ptr4); } if (typeof(T) == typeof(uint)) { uint* ptr5 = stackalloc uint[Count]; for (int m = 0; m < Count; m++) { ptr5[m] = (uint)(object)ScalarMultiply(left[m], right[m]); } return new Vector<T>(ptr5); } if (typeof(T) == typeof(int)) { int* ptr6 = stackalloc int[Count]; for (int n = 0; n < Count; n++) { ptr6[n] = (int)(object)ScalarMultiply(left[n], right[n]); } return new Vector<T>(ptr6); } if (typeof(T) == typeof(ulong)) { ulong* ptr7 = stackalloc ulong[Count]; for (int num = 0; num < Count; num++) { ptr7[num] = (ulong)(object)ScalarMultiply(left[num], right[num]); } return new Vector<T>(ptr7); } if (typeof(T) == typeof(long)) { long* ptr8 = stackalloc long[Count]; for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (long)(object)ScalarMultiply(left[num2], right[num2]); } return new Vector<T>(ptr8); } if (typeof(T) == typeof(float)) { float* ptr9 = stackalloc float[Count]; for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (float)(object)ScalarMultiply(left[num3], right[num3]); } return new Vector<T>(ptr9); } if (typeof(T) == typeof(double)) { double* ptr10 = stackalloc double[Count]; for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (double)(object)ScalarMultiply(left[num4], right[num4]); } return new Vector<T>(ptr10); } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } Vector<T> result = default(Vector<T>); if (typeof(T) == typeof(byte)) { result.register.byte_0 = (byte)(left.register.byte_0 * right.register.byte_0); result.register.byte_1 = (byte)(left.register.byte_1 * right.register.byte_1); result.register.byte_2 = (byte)(left.register.byte_2 * right.register.byte_2); result.register.byte_3 = (byte)(left.register.byte_3 * right.register.byte_3); result.register.byte_4 = (byte)(left.register.byte_4 * right.register.byte_4); result.register.byte_5 = (byte)(left.register.byte_5 * right.register.byte_5); result.register.byte_6 = (byte)(left.register.byte_6 * right.register.byte_6); result.register.byte_7 = (byte)(left.register.byte_7 * right.register.byte_7); result.register.byte_8 = (byte)(left.register.byte_8 * right.register.byte_8); result.register.byte_9 = (byte)(left.register.byte_9 * right.register.byte_9); result.register.byte_10 = (byte)(left.register.byte_10 * right.register.byte_10); result.register.byte_11 = (byte)(left.register.byte_11 * right.register.byte_11); result.register.byte_12 = (byte)(left.register.byte_12 * right.register.byte_12); result.register.byte_13 = (byte)(left.register.byte_13 * right.register.byte_13); result.register.byte_14 = (byte)(left.register.byte_14 * right.register.byte_14); result.register.byte_15 = (byte)(left.register.byte_15 * right.register.byte_15); } else if (typeof(T) == typeof(sbyte)) { result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 * right.register.sbyte_0); result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 * right.register.sbyte_1); result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 * right.register.sbyte_2); result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 * right.register.sbyte_3); result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 * right.register.sbyte_4); result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 * right.register.sbyte_5); result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 * right.register.sbyte_6); result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 * right.register.sbyte_7); result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 * right.register.sbyte_8); result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 * right.register.sbyte_9); result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 * right.register.sbyte_10); result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 * right.register.sbyte_11); result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 * right.register.sbyte_12); result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 * right.register.sbyte_13); result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 * right.register.sbyte_14); result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 * right.register.sbyte_15); } else if (typeof(T) == typeof(ushort)) { result.register.uint16_0 = (ushort)(left.register.uint16_0 * right.register.uint16_0); result.register.uint16_1 = (ushort)(left.register.uint16_1 * right.register.uint16_1); result.register.uint16_2 = (ushort)(left.register.uint16_2 * right.register.uint16_2); result.register.uint16_3 = (ushort)(left.register.uint16_3 * right.register.uint16_3); result.register.uint16_4 = (ushort)(left.register.uint16_4 * right.register.uint16_4); result.register.uint16_5 = (ushort)(left.register.uint16_5 * right.register.uint16_5); result.register.uint16_6 = (ushort)(left.register.uint16_6 * right.register.uint16_6); result.register.uint16_7 = (ushort)(left.register.uint16_7 * right.register.uint16_7); } else if (typeof(T) == typeof(short)) { result.register.int16_0 = (short)(left.register.int16_0 * right.register.int16_0); result.register.int16_1 = (short)(left.register.int16_1 * right.register.int16_1); result.register.int16_2 = (short)(left.register.int16_2 * right.register.int16_2); result.register.int16_3 = (short)(left.register.int16_3 * right.register.int16_3); result.register.int16_4 = (short)(left.register.int16_4 * right.register.int16_4); result.register.int16_5 = (short)(left.register.int16_5 * right.register.int16_5); result.register.int16_6 = (short)(left.register.int16_6 * right.register.int16_6); result.register.int16_7 = (short)(left.register.int16_7 * right.register.int16_7); } else if (typeof(T) == typeof(uint)) { result.register.uint32_0 = left.register.uint32_0 * right.register.uint32_0; result.register.uint32_1 = left.register.uint32_1 * right.register.uint32_1; result.register.uint32_2 = left.register.uint32_2 * right.register.uint32_2; result.register.uint32_3 = left.register.uint32_3 * right.register.uint32_3; } else if (typeof(T) == typeof(int)) { result.register.int32_0 = left.register.int32_0 * right.register.int32_0; result.register.int32_1 = left.register.int32_1 * right.register.int32_1; result.register.int32_2 = left.register.int32_2 * right.register.int32_2; result.register.int32_3 = left.register.int32_3 * right.register.int32_3; } else if (typeof(T) == typeof(ulong)) { result.register.uint64_0 = left.register.uint64_0 * right.register.uint64_0; result.register.uint64_1 = left.register.uint64_1 * right.register.uint64_1; } else if (typeof(T) == typeof(long)) { result.register.int64_0 = left.register.int64_0 * right.register.int64_0; result.register.int64_1 = left.register.int64_1 * right.register.int64_1; } else if (typeof(T) == typeof(float)) { result.register.single_0 = left.register.single_0 * right.register.single_0; result.register.single_1 = left.register.single_1 * right.register.single_1; result.register.single_2 = left.register.single_2 * right.register.single_2; result.register.single_3 = left.register.single_3 * right.register.single_3; } else if (typeof(T) == typeof(double)) { result.register.double_0 = left.register.double_0 * right.register.double_0; result.register.double_1 = left.register.double_1 * right.register.double_1; } return result; } public static Vector<T>operator *(Vector<T> value, T factor) { if (Vector.IsHardwareAccelerated) { return new Vector<T>(factor) * value; } Vector<T> result = default(Vector<T>); if (typeof(T) == typeof(byte)) { result.register.byte_0 = (byte)(value.register.byte_0 * (byte)(object)factor); result.register.byte_1 = (byte)(value.register.byte_1 * (byte)(object)factor); result.register.byte_2 = (byte)(value.register.byte_2 * (byte)(object)factor); result.register.byte_3 = (byte)(value.register.byte_3 * (byte)(object)factor); result.register.byte_4 = (byte)(value.register.byte_4 * (byte)(object)factor); result.register.byte_5 = (byte)(value.register.byte_5 * (byte)(object)factor); result.register.byte_6 = (byte)(value.register.byte_6 * (byte)(object)factor); result.register.byte_7 = (byte)(value.register.byte_7 * (byte)(object)factor); result.register.byte_8 = (byte)(value.register.byte_8 * (byte)(object)factor); result.register.byte_9 = (byte)(value.register.byte_9 * (byte)(object)factor); result.register.byte_10 = (byte)(value.register.byte_10 * (byte)(object)factor); result.register.byte_11 = (byte)(value.register.byte_11 * (byte)(object)factor); result.register.byte_12 = (byte)(value.register.byte_12 * (byte)(object)factor); result.register.byte_13 = (byte)(value.register.byte_13 * (byte)(object)factor); result.register.byte_14 = (byte)(value.register.byte_14 * (byte)(object)factor); result.register.byte_15 = (byte)(value.register.byte_15 * (byte)(object)factor); } else if (typeof(T) == typeof(sbyte)) { result.register.sbyte_0 = (sbyte)(value.register.sbyte_0 * (sbyte)(object)factor); result.register.sbyte_1 = (sbyte)(value.register.sbyte_1 * (sbyte)(object)factor); result.register.sbyte_2 = (sbyte)(value.register.sbyte_2 * (sbyte)(object)factor); result.register.sbyte_3 = (sbyte)(value.register.sbyte_3 * (sbyte)(object)factor); result.register.sbyte_4 = (sbyte)(value.register.sbyte_4 * (sbyte)(object)factor); result.register.sbyte_5 = (sbyte)(value.register.sbyte_5 * (sbyte)(object)factor); result.register.sbyte_6 = (sbyte)(value.register.sbyte_6 * (sbyte)(object)factor); result.register.sbyte_7 = (sbyte)(value.register.sbyte_7 * (sbyte)(object)factor); result.register.sbyte_8 = (sbyte)(value.register.sbyte_8 * (sbyte)(object)factor); result.register.sbyte_9 = (sbyte)(value.register.sbyte_9 * (sbyte)(object)factor); result.register.sbyte_10 = (sbyte)(value.register.sbyte_10 * (sbyte)(object)factor); result.register.sbyte_11 = (sbyte)(value.register.sbyte_11 * (sbyte)(object)factor); result.register.sbyte_12 = (sbyte)(value.register.sbyte_12 * (sbyte)(object)factor); result.register.sbyte_13 = (sbyte)(value.register.sbyte_13 * (sbyte)(object)factor); result.register.sbyte_14 = (sbyte)(value.register.sbyte_14 * (sbyte)(object)factor); result.register.sbyte_15 = (sbyte)(value.register.sbyte_15 * (sbyte)(object)factor); } else if (typeof(T) == typeof(ushort)) { result.register.uint16_0 = (ushort)(value.register.uint16_0 * (ushort)(object)factor); result.register.uint16_1 = (ushort)(value.register.uint16_1 * (ushort)(object)factor); result.register.uint16_2 = (ushort)(value.register.uint16_2 * (ushort)(object)factor); result.register.uint16_3 = (ushort)(value.register.uint16_3 * (ushort)(object)factor); result.register.uint16_4 = (ushort)(value.register.uint16_4 * (ushort)(object)factor); result.register.uint16_5 = (ushort)(value.register.uint16_5 * (ushort)(object)factor); result.register.uint16_6 = (ushort)(value.register.uint16_6 * (ushort)(object)factor); result.register.uint16_7 = (ushort)(value.register.uint16_7 * (ushort)(object)factor); } else if (typeof(T) == typeof(short)) { result.register.int16_0 = (short)(value.register.int16_0 * (short)(object)factor); result.register.int16_1 = (short)(value.register.int16_1 * (short)(object)factor); result.register.int16_2 = (short)(value.register.int16_2 * (short)(object)factor); result.register.int16_3 = (short)(value.register.int16_3 * (short)(object)factor); result.register.int16_4 = (short)(value.register.int16_4 * (short)(object)factor); result.register.int16_5 = (short)(value.register.int16_5 * (short)(object)factor); result.register.int16_6 = (short)(value.register.int16_6 * (short)(object)factor); result.register.int16_7 = (short)(value.register.int16_7 * (short)(object)factor); } else if (typeof(T) == typeof(uint)) { result.register.uint32_0 = value.register.uint32_0 * (uint)(object)factor; result.register.uint32_1 = value.register.uint32_1 * (uint)(object)factor; result.register.uint32_2 = value.register.uint32_2 * (uint)(object)factor; result.register.uint32_3 = value.register.uint32_3 * (uint)(object)factor; } else if (typeof(T) == typeof(int)) { result.register.int32_0 = value.register.int32_0 * (int)(object)factor; result.register.int32_1 = value.register.int32_1 * (int)(object)factor; result.register.int32_2 = value.register.int32_2 * (int)(object)factor; result.register.int32_3 = value.register.int32_3 * (int)(object)factor; } else if (typeof(T) == typeof(ulong)) { result.register.uint64_0 = value.register.uint64_0 * (ulong)(object)factor; result.register.uint64_1 = value.register.uint64_1 * (ulong)(object)factor; } else if (typeof(T) == typeof(long)) { result.register.int64_0 = value.register.int64_0 * (long)(object)factor; result.register.int64_1 = value.register.int64_1 * (long)(object)factor; } else if (typeof(T) == typeof(float)) { result.register.single_0 = value.register.single_0 * (float)(object)factor; result.register.single_1 = value.register.single_1 * (float)(object)factor; result.register.single_2 = value.register.single_2 * (float)(object)factor; result.register.single_3 = value.register.single_3 * (float)(object)factor; } else if (typeof(T) == typeof(double)) { result.register.double_0 = value.register.double_0 * (double)(object)factor; result.register.double_1 = value.register.double_1 * (double)(object)factor; } return result; } public static Vector<T>operator *(T factor, Vector<T> value) { if (Vector.IsHardwareAccelerated) { return new Vector<T>(factor) * value; } Vector<T> result = default(Vector<T>); if (typeof(T) == typeof(byte)) { result.register.byte_0 = (byte)(value.register.byte_0 * (byte)(object)factor); result.register.byte_1 = (byte)(value.register.byte_1 * (byte)(object)factor); result.register.byte_2 = (byte)(value.register.byte_2 * (byte)(object)factor); result.register.byte_3 = (byte)(value.register.byte_3 * (byte)(object)factor); result.register.byte_4 = (byte)(value.register.byte_4 * (byte)(object)factor); result.register.byte_5 = (byte)(value.register.byte_5 * (byte)(object)factor); result.register.byte_6 = (byte)(value.register.byte_6 * (byte)(object)factor); result.register.byte_7 = (byte)(value.register.byte_7 * (byte)(object)factor); result.register.byte_8 = (byte)(value.register.byte_8 * (byte)(object)factor); result.register.byte_9 = (byte)(value.register.byte_9 * (byte)(object)factor); result.register.byte_10 = (byte)(value.register.byte_10 * (byte)(object)factor); result.register.byte_11 = (byte)(value.register.byte_11 * (byte)(object)factor); result.register.byte_12 = (byte)(value.register.byte_12 * (byte)(object)factor); result.register.byte_13 = (byte)(value.register.byte_13 * (byte)(object)factor); result.register.byte_14 = (byte)(value.register.byte_14 * (byte)(object)factor); result.register.byte_15 = (byte)(value.register.byte_15 * (byte)(object)factor); } else if (typeof(T) == typeof(sbyte)) { result.register.sbyte_0 = (sbyte)(value.register.sbyte_0 * (sbyte)(object)factor); result.register.sbyte_1 = (sbyte)(value.register.sbyte_1 * (sbyte)(object)factor); result.register.sbyte_2 = (sbyte)(value.register.sbyte_2 * (sbyte)(object)factor); result.register.sbyte_3 = (sbyte)(value.register.sbyte_3 * (sbyte)(object)factor); result.register.sbyte_4 = (sbyte)(value.register.sbyte_4 * (sbyte)(object)factor); result.register.sbyte_5 = (sbyte)(value.register.sbyte_5 * (sbyte)(object)factor); result.register.sbyte_6 = (sbyte)(value.register.sbyte_6 * (sbyte)(object)factor); result.register.sbyte_7 = (sbyte)(value.register.sbyte_7 * (sbyte)(object)factor); result.register.sbyte_8 = (sbyte)(value.register.sbyte_8 * (sbyte)(object)factor); result.register.sbyte_9 = (sbyte)(value.register.sbyte_9 * (sbyte)(object)factor); result.register.sbyte_10 = (sbyte)(value.register.sbyte_10 * (sbyte)(object)factor); result.register.sbyte_11 = (sbyte)(value.register.sbyte_11 * (sbyte)(object)factor); result.register.sbyte_12 = (sbyte)(value.register.sbyte_12 * (sbyte)(object)factor); result.register.sbyte_13 = (sbyte)(value.register.sbyte_13 * (sbyte)(object)factor); result.register.sbyte_14 = (sbyte)(value.register.sbyte_14 * (sbyte)(object)factor); result.register.sbyte_15 = (sbyte)(value.register.sbyte_15 * (sbyte)(object)factor); } else if (typeof(T) == typeof(ushort)) { result.register.uint16_0 = (ushort)(value.register.uint16_0 * (ushort)(object)factor); result.register.uint16_1 = (ushort)(value.register.uint16_1 * (ushort)(object)factor); result.register.uint16_2 = (ushort)(value.register.uint16_2 * (ushort)(object)factor); result.register.uint16_3 = (ushort)(value.register.uint16_3 * (ushort)(object)factor); result.register.uint16_4 = (ushort)(value.register.uint16_4 * (ushort)(object)factor); result.register.uint16_5 = (ushort)(value.register.uint16_5 * (ushort)(object)factor); result.register.uint16_6 = (ushort)(value.register.uint16_6 * (ushort)(object)factor); result.register.uint16_7 = (ushort)(value.register.uint16_7 * (ushort)(object)factor); } else if (typeof(T) == typeof(short)) { result.register.int16_0 = (short)(value.register.int16_0 * (short)(object)factor); result.register.int16_1 = (short)(value.register.int16_1 * (short)(object)factor); result.register.int16_2 = (short)(value.register.int16_2 * (short)(object)factor); result.register.int16_3 = (short)(value.register.int16_3 * (short)(object)factor); result.register.int16_4 = (short)(value.register.int16_4 * (short)(object)factor); result.register.int16_5 = (short)(value.register.int16_5 * (short)(object)factor); result.register.int16_6 = (short)(value.register.int16_6 * (short)(object)factor); result.register.int16_7 = (short)(value.register.int16_7 * (short)(object)factor); } else if (typeof(T) == typeof(uint)) { result.register.uint32_0 = value.register.uint32_0 * (uint)(object)factor; result.register.uint32_1 = value.register.uint32_1 * (uint)(object)factor; result.register.uint32_2 = value.register.uint32_2 * (uint)(object)factor; result.register.uint32_3 = value.register.uint32_3 * (uint)(object)factor; } else if (typeof(T) == typeof(int)) { result.register.int32_0 = value.register.int32_0 * (int)(object)factor; result.register.int32_1 = value.register.int32_1 * (int)(object)factor; result.register.int32_2 = value.register.int32_2 * (int)(object)factor; result.register.int32_3 = value.register.int32_3 * (int)(object)factor; } else if (typeof(T) == typeof(ulong)) { result.register.uint64_0 = value.register.uint64_0 * (ulong)(object)factor; result.register.uint64_1 = value.register.uint64_1 * (ulong)(object)factor; } else if (typeof(T) == typeof(long)) { result.register.int64_0 = value.register.int64_0 * (long)(object)factor; result.register.int64_1 = value.register.int64_1 * (long)(object)factor; } else if (typeof(T) == typeof(float)) { result.register.single_0 = value.register.single_0 * (float)(object)factor; result.register.single_1 = value.register.single_1 * (float)(object)factor; result.register.single_2 = value.register.single_2 * (float)(object)factor; result.register.single_3 = value.register.single_3 * (float)(object)factor; } else if (typeof(T) == typeof(double)) { result.register.double_0 = value.register.double_0 * (double)(object)factor; result.register.double_1 = value.register.double_1 * (double)(object)factor; } return result; } public unsafe static Vector<T>operator /(Vector<T> left, Vector<T> right) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)]; for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)ScalarDivide(left[i], right[i]); } return new Vector<T>(ptr); } if (typeof(T) == typeof(sbyte)) { sbyte* ptr2 = stackalloc sbyte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)]; for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)ScalarDivide(left[j], right[j]); } return new Vector<T>(ptr2); } if (typeof(T) == typeof(ushort)) { ushort* ptr3 = stackalloc ushort[Count]; for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(object)ScalarDivide(left[k], right[k]); } return new Vector<T>(ptr3); } if (typeof(T) == typeof(short)) { short* ptr4 = stackalloc short[Count]; for (int l = 0; l < Count; l++) { ptr4[l] = (short)(object)ScalarDivide(left[l], right[l]); } return new Vector<T>(ptr4); } if (typeof(T) == typeof(uint)) { uint* ptr5 = stackalloc uint[Count]; for (int m = 0; m < Count; m++) { ptr5[m] = (uint)(object)ScalarDivide(left[m], right[m]); } return new Vector<T>(ptr5); } if (typeof(T) == typeof(int)) { int* ptr6 = stackalloc int[Count]; for (int n = 0; n < Count; n++) { ptr6[n] = (int)(object)ScalarDivide(left[n], right[n]); } return new Vector<T>(ptr6); } if (typeof(T) == typeof(ulong)) { ulong* ptr7 = stackalloc ulong[Count]; for (int num = 0; num < Count; num++) { ptr7[num] = (ulong)(object)ScalarDivide(left[num], right[num]); } return new Vector<T>(ptr7); } if (typeof(T) == typeof(long)) { long* ptr8 = stackalloc long[Count]; for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (long)(object)ScalarDivide(left[num2], right[num2]); } return new Vector<T>(ptr8); } if (typeof(T) == typeof(float)) { float* ptr9 = stackalloc float[Count]; for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (float)(object)ScalarDivide(left[num3], right[num3]); } return new Vector<T>(ptr9); } if (typeof(T) == typeof(double)) { double* ptr10 = stackalloc double[Count]; for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (double)(object)ScalarDivide(left[num4], right[num4]); } return new Vector<T>(ptr10); } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } Vector<T> result = default(Vector<T>); if (typeof(T) == typeof(byte)) { result.register.byte_0 = (byte)(left.register.byte_0 / right.register.byte_0); result.register.byte_1 = (byte)(left.register.byte_1 / right.register.byte_1); result.register.byte_2 = (byte)(left.register.byte_2 / right.register.byte_2); result.register.byte_3 = (byte)(left.register.byte_3 / right.register.byte_3); result.register.byte_4 = (byte)(left.register.byte_4 / right.register.byte_4); result.register.byte_5 = (byte)(left.register.byte_5 / right.register.byte_5); result.register.byte_6 = (byte)(left.register.byte_6 / right.register.byte_6); result.register.byte_7 = (byte)(left.register.byte_7 / right.register.byte_7); result.register.byte_8 = (byte)(left.register.byte_8 / right.register.byte_8); result.register.byte_9 = (byte)(left.register.byte_9 / right.register.byte_9); result.register.byte_10 = (byte)(left.register.byte_10 / right.register.byte_10); result.register.byte_11 = (byte)(left.register.byte_11 / right.register.byte_11); result.register.byte_12 = (byte)(left.register.byte_12 / right.register.byte_12); result.register.byte_13 = (byte)(left.register.byte_13 / right.register.byte_13); result.register.byte_14 = (byte)(left.register.byte_14 / right.register.byte_14); result.register.byte_15 = (byte)(left.register.byte_15 / right.register.byte_15); } else if (typeof(T) == typeof(sbyte)) { result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 / right.register.sbyte_0); result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 / right.register.sbyte_1); result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 / right.register.sbyte_2); result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 / right.register.sbyte_3); result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 / right.register.sbyte_4); result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 / right.register.sbyte_5); result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 / right.register.sbyte_6); result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 / right.register.sbyte_7); result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 / right.register.sbyte_8); result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 / right.register.sbyte_9); result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 / right.register.sbyte_10); result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 / right.register.sbyte_11); result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 / right.register.sbyte_12); result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 / right.register.sbyte_13); result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 / right.register.sbyte_14); result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 / right.register.sbyte_15); } else if (typeof(T) == typeof(ushort)) { result.register.uint16_0 = (ushort)(left.register.uint16_0 / right.register.uint16_0); result.register.uint16_1 = (ushort)(left.register.uint16_1 / right.register.uint16_1); result.register.uint16_2 = (ushort)(left.register.uint16_2 / right.register.uint16_2); result.register.uint16_3 = (ushort)(left.register.uint16_3 / right.register.uint16_3); result.register.uint16_4 = (ushort)(left.register.uint16_4 / right.register.uint16_4); result.register.uint16_5 = (ushort)(left.register.uint16_5 / right.register.uint16_5); result.register.uint16_6 = (ushort)(left.register.uint16_6 / right.register.uint16_6); result.register.uint16_7 = (ushort)(left.register.uint16_7 / right.register.uint16_7); } else if (typeof(T) == typeof(short)) { result.register.int16_0 = (short)(left.register.int16_0 / right.register.int16_0); result.register.int16_1 = (short)(left.register.int16_1 / right.register.int16_1); result.register.int16_2 = (short)(left.register.int16_2 / right.register.int16_2); result.register.int16_3 = (short)(left.register.int16_3 / right.register.int16_3); result.register.int16_4 = (short)(left.register.int16_4 / right.register.int16_4); result.register.int16_5 = (short)(left.register.int16_5 / right.register.int16_5); result.register.int16_6 = (short)(left.register.int16_6 / right.register.int16_6); result.register.int16_7 = (short)(left.register.int16_7 / right.register.int16_7); } else if (typeof(T) == typeof(uint)) { result.register.uint32_0 = left.register.uint32_0 / right.register.uint32_0; result.register.uint32_1 = left.register.uint32_1 / right.register.uint32_1; result.register.uint32_2 = left.register.uint32_2 / right.register.uint32_2; result.register.uint32_3 = left.register.uint32_3 / right.register.uint32_3; } else if (typeof(T) == typeof(int)) { result.register.int32_0 = left.register.int32_0 / right.register.int32_0; result.register.int32_1 = left.register.int32_1 / right.register.int32_1; result.register.int32_2 = left.register.int32_2 / right.register.int32_2; result.register.int32_3 = left.register.int32_3 / right.register.int32_3; } else if (typeof(T) == typeof(ulong)) { result.register.uint64_0 = left.register.uint64_0 / right.register.uint64_0; result.register.uint64_1 = left.register.uint64_1 / right.register.uint64_1; } else if (typeof(T) == typeof(long)) { result.register.int64_0 = left.register.int64_0 / right.register.int64_0; result.register.int64_1 = left.register.int64_1 / right.register.int64_1; } else if (typeof(T) == typeof(float)) { result.register.single_0 = left.register.single_0 / right.register.single_0; result.register.single_1 = left.register.single_1 / right.register.single_1; result.register.single_2 = left.register.single_2 / right.register.single_2; result.register.single_3 = left.register.single_3 / right.register.single_3; } else if (typeof(T) == typeof(double)) { result.register.double_0 = left.register.double_0 / right.register.double_0; result.register.double_1 = left.register.double_1 / right.register.double_1; } return result; } public static Vector<T>operator -(Vector<T> value) { return Zero - value; } [JitIntrinsic] public unsafe static Vector<T>operator &(Vector<T> left, Vector<T> right) { Vector<T> result = default(Vector<T>); if (Vector.IsHardwareAccelerated) { long* ptr = &result.register.int64_0; long* ptr2 = &left.register.int64_0; long* ptr3 = &right.register.int64_0; for (int i = 0; i < Vector<long>.Count; i++) { ptr[i] = ptr2[i] & ptr3[i]; } } else { result.register.int64_0 = left.register.int64_0 & right.register.int64_0; result.register.int64_1 = left.register.int64_1 & right.register.int64_1; } return result; } [JitIntrinsic] public unsafe static Vector<T>operator |(Vector<T> left, Vector<T> right) { Vector<T> result = default(Vector<T>); if (Vector.IsHardwareAccelerated) { long* ptr = &result.register.int64_0; long* ptr2 = &left.register.int64_0; long* ptr3 = &right.register.int64_0; for (int i = 0; i < Vector<long>.Count; i++) { ptr[i] = ptr2[i] | ptr3[i]; } } else { result.register.int64_0 = left.register.int64_0 | right.register.int64_0; result.register.int64_1 = left.register.int64_1 | right.register.int64_1; } return result; } [JitIntrinsic] public unsafe static Vector<T>operator ^(Vector<T> left, Vector<T> right) { Vector<T> result = default(Vector<T>); if (Vector.IsHardwareAccelerated) { long* ptr = &result.register.int64_0; long* ptr2 = &left.register.int64_0; long* ptr3 = &right.register.int64_0; for (int i = 0; i < Vector<long>.Count; i++) { ptr[i] = ptr2[i] ^ ptr3[i]; } } else { result.register.int64_0 = left.register.int64_0 ^ right.register.int64_0; result.register.int64_1 = left.register.int64_1 ^ right.register.int64_1; } return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<T>operator ~(Vector<T> value) { return allOnes ^ value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Vector<T> left, Vector<T> right) { return left.Equals(right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Vector<T> left, Vector<T> right) { return !(left == right); } [JitIntrinsic] public static explicit operator Vector<byte>(Vector<T> value) { return new Vector<byte>(ref value.register); } [CLSCompliant(false)] [JitIntrinsic] public static explicit operator Vector<sbyte>(Vector<T> value) { return new Vector<sbyte>(ref value.register); } [CLSCompliant(false)] [JitIntrinsic] public static explicit operator Vector<ushort>(Vector<T> value) { return new Vector<ushort>(ref value.register); } [JitIntrinsic] public static explicit operator Vector<short>(Vector<T> value) { return new Vector<short>(ref value.register); } [CLSCompliant(false)] [JitIntrinsic] public static explicit operator Vector<uint>(Vector<T> value) { return new Vector<uint>(ref value.register); } [JitIntrinsic] public static explicit operator Vector<int>(Vector<T> value) { return new Vector<int>(ref value.register); } [CLSCompliant(false)] [JitIntrinsic] public static explicit operator Vector<ulong>(Vector<T> value) { return new Vector<ulong>(ref value.register); } [JitIntrinsic] public static explicit operator Vector<long>(Vector<T> value) { return new Vector<long>(ref value.register); } [JitIntrinsic] public static explicit operator Vector<float>(Vector<T> value) { return new Vector<float>(ref value.register); } [JitIntrinsic] public static explicit operator Vector<double>(Vector<T> value) { return new Vector<double>(ref value.register); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [JitIntrinsic] internal unsafe static Vector<T> Equals(Vector<T> left, Vector<T> right) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)]; for (int i = 0; i < Count; i++) { ptr[i] = (byte)(ScalarEquals(left[i], right[i]) ? ConstantHelper.GetByteWithAllBitsSet() : 0); } return new Vector<T>(ptr); } if (typeof(T) == typeof(sbyte)) { sbyte* ptr2 = stackalloc sbyte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)]; for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(ScalarEquals(left[j], right[j]) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); } return new Vector<T>(ptr2); } if (typeof(T) == typeof(ushort)) { ushort* ptr3 = stackalloc ushort[Count]; for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(ScalarEquals(left[k], right[k]) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); } return new Vector<T>(ptr3); } if (typeof(T) == typeof(short)) { short* ptr4
System.Reflection.TypeExtensions.dll
Decompiled 5 days agousing System; using System.Diagnostics; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using FxResources.System.Reflection.TypeExtensions; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyDefaultAlias("System.Reflection.TypeExtensions")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("System.Reflection.TypeExtensions")] [assembly: AssemblyFileVersion("4.700.19.56404")] [assembly: AssemblyInformationalVersion("3.1.0+0f7f38c4fd323b26da10cce95f857f77f0f09b48")] [assembly: AssemblyProduct("Microsoft® .NET Core")] [assembly: AssemblyTitle("System.Reflection.TypeExtensions")] [assembly: CLSCompliant(true)] [assembly: AssemblyVersion("4.1.5.0")] [assembly: TypeForwardedTo(typeof(BindingFlags))] namespace FxResources.System.Reflection.TypeExtensions { internal static class SR { } } namespace System { internal static class SR { private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string NoMetadataTokenAvailable => GetResourceString("NoMetadataTokenAvailable"); internal static string PlatformNotSupported_ReflectionTypeExtensions => GetResourceString("PlatformNotSupported_ReflectionTypeExtensions"); [MethodImpl(MethodImplOptions.NoInlining)] private static bool UsingResourceKeys() { return false; } internal static string GetResourceString(string resourceKey, string defaultString = null) { if (UsingResourceKeys()) { return defaultString ?? resourceKey; } string text = null; try { text = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } if (defaultString != null && resourceKey.Equals(text)) { return defaultString; } return text; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider provider, string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Reflection { internal static class Requires { internal static void NotNull(object obj, string name) { if (obj == null) { throw new ArgumentNullException(name); } } } public static class TypeExtensions { public static ConstructorInfo GetConstructor(Type type, Type[] types) { Requires.NotNull(type, "type"); return type.GetConstructor(types); } public static ConstructorInfo[] GetConstructors(Type type) { Requires.NotNull(type, "type"); return type.GetConstructors(); } public static ConstructorInfo[] GetConstructors(Type type, BindingFlags bindingAttr) { Requires.NotNull(type, "type"); return type.GetConstructors(bindingAttr); } public static MemberInfo[] GetDefaultMembers(Type type) { Requires.NotNull(type, "type"); return type.GetDefaultMembers(); } public static EventInfo GetEvent(Type type, string name) { Requires.NotNull(type, "type"); return type.GetEvent(name); } public static EventInfo GetEvent(Type type, string name, BindingFlags bindingAttr) { Requires.NotNull(type, "type"); return type.GetEvent(name, bindingAttr); } public static EventInfo[] GetEvents(Type type) { Requires.NotNull(type, "type"); return type.GetEvents(); } public static EventInfo[] GetEvents(Type type, BindingFlags bindingAttr) { Requires.NotNull(type, "type"); return type.GetEvents(bindingAttr); } public static FieldInfo GetField(Type type, string name) { Requires.NotNull(type, "type"); return type.GetField(name); } public static FieldInfo GetField(Type type, string name, BindingFlags bindingAttr) { Requires.NotNull(type, "type"); return type.GetField(name, bindingAttr); } public static FieldInfo[] GetFields(Type type) { Requires.NotNull(type, "type"); return type.GetFields(); } public static FieldInfo[] GetFields(Type type, BindingFlags bindingAttr) { Requires.NotNull(type, "type"); return type.GetFields(bindingAttr); } public static Type[] GetGenericArguments(Type type) { Requires.NotNull(type, "type"); return type.GetGenericArguments(); } public static Type[] GetInterfaces(Type type) { Requires.NotNull(type, "type"); return type.GetInterfaces(); } public static MemberInfo[] GetMember(Type type, string name) { Requires.NotNull(type, "type"); return type.GetMember(name); } public static MemberInfo[] GetMember(Type type, string name, BindingFlags bindingAttr) { Requires.NotNull(type, "type"); return type.GetMember(name, bindingAttr); } public static MemberInfo[] GetMembers(Type type) { Requires.NotNull(type, "type"); return type.GetMembers(); } public static MemberInfo[] GetMembers(Type type, BindingFlags bindingAttr) { Requires.NotNull(type, "type"); return type.GetMembers(bindingAttr); } public static MethodInfo GetMethod(Type type, string name) { Requires.NotNull(type, "type"); return type.GetMethod(name); } public static MethodInfo GetMethod(Type type, string name, BindingFlags bindingAttr) { Requires.NotNull(type, "type"); return type.GetMethod(name, bindingAttr); } public static MethodInfo GetMethod(Type type, string name, Type[] types) { Requires.NotNull(type, "type"); return type.GetMethod(name, types); } public static MethodInfo[] GetMethods(Type type) { Requires.NotNull(type, "type"); return type.GetMethods(); } public static MethodInfo[] GetMethods(Type type, BindingFlags bindingAttr) { Requires.NotNull(type, "type"); return type.GetMethods(bindingAttr); } public static Type GetNestedType(Type type, string name, BindingFlags bindingAttr) { Requires.NotNull(type, "type"); return type.GetNestedType(name, bindingAttr); } public static Type[] GetNestedTypes(Type type, BindingFlags bindingAttr) { Requires.NotNull(type, "type"); return type.GetNestedTypes(bindingAttr); } public static PropertyInfo[] GetProperties(Type type) { Requires.NotNull(type, "type"); return type.GetProperties(); } public static PropertyInfo[] GetProperties(Type type, BindingFlags bindingAttr) { Requires.NotNull(type, "type"); return type.GetProperties(bindingAttr); } public static PropertyInfo GetProperty(Type type, string name) { Requires.NotNull(type, "type"); return type.GetProperty(name); } public static PropertyInfo GetProperty(Type type, string name, BindingFlags bindingAttr) { Requires.NotNull(type, "type"); return type.GetProperty(name, bindingAttr); } public static PropertyInfo GetProperty(Type type, string name, Type returnType) { Requires.NotNull(type, "type"); return type.GetProperty(name, returnType); } public static PropertyInfo GetProperty(Type type, string name, Type returnType, Type[] types) { Requires.NotNull(type, "type"); return type.GetProperty(name, returnType, types); } public static bool IsAssignableFrom(Type type, Type c) { Requires.NotNull(type, "type"); return type.IsAssignableFrom(c); } public static bool IsInstanceOfType(Type type, object o) { Requires.NotNull(type, "type"); return type.IsInstanceOfType(o); } } public static class AssemblyExtensions { public static Type[] GetExportedTypes(Assembly assembly) { Requires.NotNull(assembly, "assembly"); return assembly.GetExportedTypes(); } public static Module[] GetModules(Assembly assembly) { Requires.NotNull(assembly, "assembly"); return assembly.GetModules(); } public static Type[] GetTypes(Assembly assembly) { Requires.NotNull(assembly, "assembly"); return assembly.GetTypes(); } } public static class EventInfoExtensions { public static MethodInfo GetAddMethod(EventInfo eventInfo) { Requires.NotNull(eventInfo, "eventInfo"); return eventInfo.GetAddMethod(); } public static MethodInfo GetAddMethod(EventInfo eventInfo, bool nonPublic) { Requires.NotNull(eventInfo, "eventInfo"); return eventInfo.GetAddMethod(nonPublic); } public static MethodInfo GetRaiseMethod(EventInfo eventInfo) { Requires.NotNull(eventInfo, "eventInfo"); return eventInfo.GetRaiseMethod(); } public static MethodInfo GetRaiseMethod(EventInfo eventInfo, bool nonPublic) { Requires.NotNull(eventInfo, "eventInfo"); return eventInfo.GetRaiseMethod(nonPublic); } public static MethodInfo GetRemoveMethod(EventInfo eventInfo) { Requires.NotNull(eventInfo, "eventInfo"); return eventInfo.GetRemoveMethod(); } public static MethodInfo GetRemoveMethod(EventInfo eventInfo, bool nonPublic) { Requires.NotNull(eventInfo, "eventInfo"); return eventInfo.GetRemoveMethod(nonPublic); } } public static class MemberInfoExtensions { public static bool HasMetadataToken(this MemberInfo member) { Requires.NotNull(member, "member"); try { return GetMetadataTokenOrZeroOrThrow(member) != 0; } catch (InvalidOperationException) { return false; } } public static int GetMetadataToken(this MemberInfo member) { Requires.NotNull(member, "member"); int metadataTokenOrZeroOrThrow = GetMetadataTokenOrZeroOrThrow(member); if (metadataTokenOrZeroOrThrow == 0) { throw new InvalidOperationException(System.SR.NoMetadataTokenAvailable); } return metadataTokenOrZeroOrThrow; } private static int GetMetadataTokenOrZeroOrThrow(MemberInfo member) { int metadataToken = member.MetadataToken; if ((metadataToken & 0xFFFFFF) == 0) { return 0; } return metadataToken; } } public static class MethodInfoExtensions { public static MethodInfo GetBaseDefinition(MethodInfo method) { Requires.NotNull(method, "method"); return method.GetBaseDefinition(); } } public static class ModuleExtensions { public static bool HasModuleVersionId(this Module module) { Requires.NotNull(module, "module"); return true; } public static Guid GetModuleVersionId(this Module module) { Requires.NotNull(module, "module"); return module.ModuleVersionId; } } public static class PropertyInfoExtensions { public static MethodInfo[] GetAccessors(PropertyInfo property) { Requires.NotNull(property, "property"); return property.GetAccessors(); } public static MethodInfo[] GetAccessors(PropertyInfo property, bool nonPublic) { Requires.NotNull(property, "property"); return property.GetAccessors(nonPublic); } public static MethodInfo GetGetMethod(PropertyInfo property) { Requires.NotNull(property, "property"); return property.GetGetMethod(); } public static MethodInfo GetGetMethod(PropertyInfo property, bool nonPublic) { Requires.NotNull(property, "property"); return property.GetGetMethod(nonPublic); } public static MethodInfo GetSetMethod(PropertyInfo property) { Requires.NotNull(property, "property"); return property.GetSetMethod(); } public static MethodInfo GetSetMethod(PropertyInfo property, bool nonPublic) { Requires.NotNull(property, "property"); return property.GetSetMethod(nonPublic); } } }
System.Runtime.CompilerServices.Unsafe.dll
Decompiled 5 days agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using Microsoft.CodeAnalysis; [assembly: AssemblyProduct("Microsoft® .NET Framework")] [assembly: CLSCompliant(false)] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: CompilationRelaxations(8)] [assembly: AssemblyDescription("System.Runtime.CompilerServices.Unsafe")] [assembly: AssemblyFileVersion("6.0.21.52210")] [assembly: AssemblyInformationalVersion("6.0.0")] [assembly: AssemblyTitle("System.Runtime.CompilerServices.Unsafe")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyVersion("6.0.0.0")] namespace System.Runtime.CompilerServices { public static class Unsafe { [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static T Read<T>(void* source) { return Unsafe.Read<T>(source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static T ReadUnaligned<T>(void* source) { return Unsafe.ReadUnaligned<T>(source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static T ReadUnaligned<T>(ref byte source) { return Unsafe.ReadUnaligned<T>(ref source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void Write<T>(void* destination, T value) { Unsafe.Write(destination, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void WriteUnaligned<T>(void* destination, T value) { Unsafe.WriteUnaligned(destination, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void WriteUnaligned<T>(ref byte destination, T value) { Unsafe.WriteUnaligned(ref destination, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void Copy<T>(void* destination, ref T source) { Unsafe.Write(destination, source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void Copy<T>(ref T destination, void* source) { destination = Unsafe.Read<T>(source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void* AsPointer<T>(ref T value) { return Unsafe.AsPointer(ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void SkipInit<T>(out T value) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static int SizeOf<T>() { return Unsafe.SizeOf<T>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void CopyBlock(void* destination, void* source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlock(destination, source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void CopyBlock(ref byte destination, ref byte source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlock(ref destination, ref source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void CopyBlockUnaligned(void* destination, void* source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlockUnaligned(destination, source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void CopyBlockUnaligned(ref byte destination, ref byte source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlockUnaligned(ref destination, ref source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void InitBlock(void* startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlock(startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void InitBlock(ref byte startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlock(ref startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void InitBlockUnaligned(void* startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlockUnaligned(startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void InitBlockUnaligned(ref byte startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlockUnaligned(ref startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static T As<T>(object o) where T : class { return (T)o; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static ref T AsRef<T>(void* source) { return ref *(T*)source; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T AsRef<T>(in T source) { return ref source; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref TTo As<TFrom, TTo>(ref TFrom source) { return ref Unsafe.As<TFrom, TTo>(ref source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Unbox<T>(object box) where T : struct { return ref (T)box; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Add<T>(ref T source, int elementOffset) { return ref Unsafe.Add(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void* Add<T>(void* source, int elementOffset) { return (byte*)source + (nint)elementOffset * (nint)Unsafe.SizeOf<T>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Add<T>(ref T source, IntPtr elementOffset) { return ref Unsafe.Add(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T Add<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint elementOffset) { return ref Unsafe.Add(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T AddByteOffset<T>(ref T source, IntPtr byteOffset) { return ref Unsafe.AddByteOffset(ref source, byteOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T AddByteOffset<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint byteOffset) { return ref Unsafe.AddByteOffset(ref source, byteOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Subtract<T>(ref T source, int elementOffset) { return ref Unsafe.Subtract(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void* Subtract<T>(void* source, int elementOffset) { return (byte*)source - (nint)elementOffset * (nint)Unsafe.SizeOf<T>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Subtract<T>(ref T source, IntPtr elementOffset) { return ref Unsafe.Subtract(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T Subtract<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint elementOffset) { return ref Unsafe.Subtract(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T SubtractByteOffset<T>(ref T source, IntPtr byteOffset) { return ref Unsafe.SubtractByteOffset(ref source, byteOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T SubtractByteOffset<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint byteOffset) { return ref Unsafe.SubtractByteOffset(ref source, byteOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static IntPtr ByteOffset<T>(ref T origin, ref T target) { return Unsafe.ByteOffset(target: ref target, origin: ref origin); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static bool AreSame<T>(ref T left, ref T right) { return Unsafe.AreSame(ref left, ref right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static bool IsAddressGreaterThan<T>(ref T left, ref T right) { return Unsafe.IsAddressGreaterThan(ref left, ref right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static bool IsAddressLessThan<T>(ref T left, ref T right) { return Unsafe.IsAddressLessThan(ref left, ref right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static bool IsNullRef<T>(ref T source) { return Unsafe.AsPointer(ref source) == null; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static ref T NullRef<T>() { return ref *(T*)null; } } } namespace System.Runtime.Versioning { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class NonVersionableAttribute : Attribute { } } namespace System.Runtime.CompilerServices { internal sealed class IsReadOnlyAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] [Microsoft.CodeAnalysis.Embedded] [CompilerGenerated] internal sealed class NativeIntegerAttribute : Attribute { public readonly bool[] TransformFlags; public NativeIntegerAttribute() { TransformFlags = new bool[1] { true }; } public NativeIntegerAttribute(bool[] A_0) { TransformFlags = A_0; } } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } }
System.Text.Encoding.CodePages.dll
Decompiled 5 days ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers.Binary; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Threading; using FxResources.System.Text.Encoding.CodePages; using Microsoft.CodeAnalysis; using Microsoft.Win32.SafeHandles; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("System.Text.Encoding.CodePages")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Provides support for code-page based encodings, including Windows-1252, Shift-JIS, and GB2312.\r\n\r\nCommonly Used Types:\r\nSystem.Text.CodePagesEncodingProvider")] [assembly: AssemblyFileVersion("7.0.22.51805")] [assembly: AssemblyInformationalVersion("7.0.0+d099f075e45d2aa6007a22b71b45a08758559f80")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("System.Text.Encoding.CodePages")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("7.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [module: System.Runtime.CompilerServices.NullablePublicOnly(false)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.System.Text.Encoding.CodePages { internal static class SR { } } namespace System { internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string ArgumentOutOfRange_NeedNonNegNum => GetResourceString("ArgumentOutOfRange_NeedNonNegNum"); internal static string ArgumentOutOfRange_IndexCount => GetResourceString("ArgumentOutOfRange_IndexCount"); internal static string ArgumentOutOfRange_IndexCountBuffer => GetResourceString("ArgumentOutOfRange_IndexCountBuffer"); internal static string NotSupported_NoCodepageData => GetResourceString("NotSupported_NoCodepageData"); internal static string Argument_EncodingConversionOverflowBytes => GetResourceString("Argument_EncodingConversionOverflowBytes"); internal static string Argument_InvalidCharSequenceNoIndex => GetResourceString("Argument_InvalidCharSequenceNoIndex"); internal static string ArgumentOutOfRange_GetByteCountOverflow => GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"); internal static string Argument_EncodingConversionOverflowChars => GetResourceString("Argument_EncodingConversionOverflowChars"); internal static string ArgumentOutOfRange_GetCharCountOverflow => GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"); internal static string Argument_EncoderFallbackNotEmpty => GetResourceString("Argument_EncoderFallbackNotEmpty"); internal static string Argument_RecursiveFallback => GetResourceString("Argument_RecursiveFallback"); internal static string Argument_RecursiveFallbackBytes => GetResourceString("Argument_RecursiveFallbackBytes"); internal static string ArgumentOutOfRange_Range => GetResourceString("ArgumentOutOfRange_Range"); internal static string Argument_CodepageNotSupported => GetResourceString("Argument_CodepageNotSupported"); internal static string ArgumentOutOfRange_IndexMustBeLess => GetResourceString("ArgumentOutOfRange_IndexMustBeLess"); internal static string ArgumentOutOfRange_IndexMustBeLessOrEqual => GetResourceString("ArgumentOutOfRange_IndexMustBeLessOrEqual"); internal static string MissingEncodingNameResource => GetResourceString("MissingEncodingNameResource"); internal static string Globalization_cp_37 => GetResourceString("Globalization_cp_37"); internal static string Globalization_cp_437 => GetResourceString("Globalization_cp_437"); internal static string Globalization_cp_500 => GetResourceString("Globalization_cp_500"); internal static string Globalization_cp_708 => GetResourceString("Globalization_cp_708"); internal static string Globalization_cp_720 => GetResourceString("Globalization_cp_720"); internal static string Globalization_cp_737 => GetResourceString("Globalization_cp_737"); internal static string Globalization_cp_775 => GetResourceString("Globalization_cp_775"); internal static string Globalization_cp_850 => GetResourceString("Globalization_cp_850"); internal static string Globalization_cp_852 => GetResourceString("Globalization_cp_852"); internal static string Globalization_cp_855 => GetResourceString("Globalization_cp_855"); internal static string Globalization_cp_857 => GetResourceString("Globalization_cp_857"); internal static string Globalization_cp_858 => GetResourceString("Globalization_cp_858"); internal static string Globalization_cp_860 => GetResourceString("Globalization_cp_860"); internal static string Globalization_cp_861 => GetResourceString("Globalization_cp_861"); internal static string Globalization_cp_862 => GetResourceString("Globalization_cp_862"); internal static string Globalization_cp_863 => GetResourceString("Globalization_cp_863"); internal static string Globalization_cp_864 => GetResourceString("Globalization_cp_864"); internal static string Globalization_cp_865 => GetResourceString("Globalization_cp_865"); internal static string Globalization_cp_866 => GetResourceString("Globalization_cp_866"); internal static string Globalization_cp_869 => GetResourceString("Globalization_cp_869"); internal static string Globalization_cp_870 => GetResourceString("Globalization_cp_870"); internal static string Globalization_cp_874 => GetResourceString("Globalization_cp_874"); internal static string Globalization_cp_875 => GetResourceString("Globalization_cp_875"); internal static string Globalization_cp_932 => GetResourceString("Globalization_cp_932"); internal static string Globalization_cp_936 => GetResourceString("Globalization_cp_936"); internal static string Globalization_cp_949 => GetResourceString("Globalization_cp_949"); internal static string Globalization_cp_950 => GetResourceString("Globalization_cp_950"); internal static string Globalization_cp_1026 => GetResourceString("Globalization_cp_1026"); internal static string Globalization_cp_1047 => GetResourceString("Globalization_cp_1047"); internal static string Globalization_cp_1140 => GetResourceString("Globalization_cp_1140"); internal static string Globalization_cp_1141 => GetResourceString("Globalization_cp_1141"); internal static string Globalization_cp_1142 => GetResourceString("Globalization_cp_1142"); internal static string Globalization_cp_1143 => GetResourceString("Globalization_cp_1143"); internal static string Globalization_cp_1144 => GetResourceString("Globalization_cp_1144"); internal static string Globalization_cp_1145 => GetResourceString("Globalization_cp_1145"); internal static string Globalization_cp_1146 => GetResourceString("Globalization_cp_1146"); internal static string Globalization_cp_1147 => GetResourceString("Globalization_cp_1147"); internal static string Globalization_cp_1148 => GetResourceString("Globalization_cp_1148"); internal static string Globalization_cp_1149 => GetResourceString("Globalization_cp_1149"); internal static string Globalization_cp_1250 => GetResourceString("Globalization_cp_1250"); internal static string Globalization_cp_1251 => GetResourceString("Globalization_cp_1251"); internal static string Globalization_cp_1252 => GetResourceString("Globalization_cp_1252"); internal static string Globalization_cp_1253 => GetResourceString("Globalization_cp_1253"); internal static string Globalization_cp_1254 => GetResourceString("Globalization_cp_1254"); internal static string Globalization_cp_1255 => GetResourceString("Globalization_cp_1255"); internal static string Globalization_cp_1256 => GetResourceString("Globalization_cp_1256"); internal static string Globalization_cp_1257 => GetResourceString("Globalization_cp_1257"); internal static string Globalization_cp_1258 => GetResourceString("Globalization_cp_1258"); internal static string Globalization_cp_1361 => GetResourceString("Globalization_cp_1361"); internal static string Globalization_cp_10000 => GetResourceString("Globalization_cp_10000"); internal static string Globalization_cp_10001 => GetResourceString("Globalization_cp_10001"); internal static string Globalization_cp_10002 => GetResourceString("Globalization_cp_10002"); internal static string Globalization_cp_10003 => GetResourceString("Globalization_cp_10003"); internal static string Globalization_cp_10004 => GetResourceString("Globalization_cp_10004"); internal static string Globalization_cp_10005 => GetResourceString("Globalization_cp_10005"); internal static string Globalization_cp_10006 => GetResourceString("Globalization_cp_10006"); internal static string Globalization_cp_10007 => GetResourceString("Globalization_cp_10007"); internal static string Globalization_cp_10008 => GetResourceString("Globalization_cp_10008"); internal static string Globalization_cp_10010 => GetResourceString("Globalization_cp_10010"); internal static string Globalization_cp_10017 => GetResourceString("Globalization_cp_10017"); internal static string Globalization_cp_10021 => GetResourceString("Globalization_cp_10021"); internal static string Globalization_cp_10029 => GetResourceString("Globalization_cp_10029"); internal static string Globalization_cp_10079 => GetResourceString("Globalization_cp_10079"); internal static string Globalization_cp_10081 => GetResourceString("Globalization_cp_10081"); internal static string Globalization_cp_10082 => GetResourceString("Globalization_cp_10082"); internal static string Globalization_cp_20000 => GetResourceString("Globalization_cp_20000"); internal static string Globalization_cp_20001 => GetResourceString("Globalization_cp_20001"); internal static string Globalization_cp_20002 => GetResourceString("Globalization_cp_20002"); internal static string Globalization_cp_20003 => GetResourceString("Globalization_cp_20003"); internal static string Globalization_cp_20004 => GetResourceString("Globalization_cp_20004"); internal static string Globalization_cp_20005 => GetResourceString("Globalization_cp_20005"); internal static string Globalization_cp_20105 => GetResourceString("Globalization_cp_20105"); internal static string Globalization_cp_20106 => GetResourceString("Globalization_cp_20106"); internal static string Globalization_cp_20107 => GetResourceString("Globalization_cp_20107"); internal static string Globalization_cp_20108 => GetResourceString("Globalization_cp_20108"); internal static string Globalization_cp_20261 => GetResourceString("Globalization_cp_20261"); internal static string Globalization_cp_20269 => GetResourceString("Globalization_cp_20269"); internal static string Globalization_cp_20273 => GetResourceString("Globalization_cp_20273"); internal static string Globalization_cp_20277 => GetResourceString("Globalization_cp_20277"); internal static string Globalization_cp_20278 => GetResourceString("Globalization_cp_20278"); internal static string Globalization_cp_20280 => GetResourceString("Globalization_cp_20280"); internal static string Globalization_cp_20284 => GetResourceString("Globalization_cp_20284"); internal static string Globalization_cp_20285 => GetResourceString("Globalization_cp_20285"); internal static string Globalization_cp_20290 => GetResourceString("Globalization_cp_20290"); internal static string Globalization_cp_20297 => GetResourceString("Globalization_cp_20297"); internal static string Globalization_cp_20420 => GetResourceString("Globalization_cp_20420"); internal static string Globalization_cp_20423 => GetResourceString("Globalization_cp_20423"); internal static string Globalization_cp_20424 => GetResourceString("Globalization_cp_20424"); internal static string Globalization_cp_20833 => GetResourceString("Globalization_cp_20833"); internal static string Globalization_cp_20838 => GetResourceString("Globalization_cp_20838"); internal static string Globalization_cp_20866 => GetResourceString("Globalization_cp_20866"); internal static string Globalization_cp_20871 => GetResourceString("Globalization_cp_20871"); internal static string Globalization_cp_20880 => GetResourceString("Globalization_cp_20880"); internal static string Globalization_cp_20905 => GetResourceString("Globalization_cp_20905"); internal static string Globalization_cp_20924 => GetResourceString("Globalization_cp_20924"); internal static string Globalization_cp_20932 => GetResourceString("Globalization_cp_20932"); internal static string Globalization_cp_20936 => GetResourceString("Globalization_cp_20936"); internal static string Globalization_cp_20949 => GetResourceString("Globalization_cp_20949"); internal static string Globalization_cp_21025 => GetResourceString("Globalization_cp_21025"); internal static string Globalization_cp_21027 => GetResourceString("Globalization_cp_21027"); internal static string Globalization_cp_21866 => GetResourceString("Globalization_cp_21866"); internal static string Globalization_cp_28592 => GetResourceString("Globalization_cp_28592"); internal static string Globalization_cp_28593 => GetResourceString("Globalization_cp_28593"); internal static string Globalization_cp_28594 => GetResourceString("Globalization_cp_28594"); internal static string Globalization_cp_28595 => GetResourceString("Globalization_cp_28595"); internal static string Globalization_cp_28596 => GetResourceString("Globalization_cp_28596"); internal static string Globalization_cp_28597 => GetResourceString("Globalization_cp_28597"); internal static string Globalization_cp_28598 => GetResourceString("Globalization_cp_28598"); internal static string Globalization_cp_28599 => GetResourceString("Globalization_cp_28599"); internal static string Globalization_cp_28603 => GetResourceString("Globalization_cp_28603"); internal static string Globalization_cp_28605 => GetResourceString("Globalization_cp_28605"); internal static string Globalization_cp_29001 => GetResourceString("Globalization_cp_29001"); internal static string Globalization_cp_38598 => GetResourceString("Globalization_cp_38598"); internal static string Globalization_cp_50000 => GetResourceString("Globalization_cp_50000"); internal static string Globalization_cp_50220 => GetResourceString("Globalization_cp_50220"); internal static string Globalization_cp_50221 => GetResourceString("Globalization_cp_50221"); internal static string Globalization_cp_50222 => GetResourceString("Globalization_cp_50222"); internal static string Globalization_cp_50225 => GetResourceString("Globalization_cp_50225"); internal static string Globalization_cp_50227 => GetResourceString("Globalization_cp_50227"); internal static string Globalization_cp_50229 => GetResourceString("Globalization_cp_50229"); internal static string Globalization_cp_50930 => GetResourceString("Globalization_cp_50930"); internal static string Globalization_cp_50931 => GetResourceString("Globalization_cp_50931"); internal static string Globalization_cp_50933 => GetResourceString("Globalization_cp_50933"); internal static string Globalization_cp_50935 => GetResourceString("Globalization_cp_50935"); internal static string Globalization_cp_50937 => GetResourceString("Globalization_cp_50937"); internal static string Globalization_cp_50939 => GetResourceString("Globalization_cp_50939"); internal static string Globalization_cp_51932 => GetResourceString("Globalization_cp_51932"); internal static string Globalization_cp_51936 => GetResourceString("Globalization_cp_51936"); internal static string Globalization_cp_51949 => GetResourceString("Globalization_cp_51949"); internal static string Globalization_cp_52936 => GetResourceString("Globalization_cp_52936"); internal static string Globalization_cp_54936 => GetResourceString("Globalization_cp_54936"); internal static string Globalization_cp_57002 => GetResourceString("Globalization_cp_57002"); internal static string Globalization_cp_57003 => GetResourceString("Globalization_cp_57003"); internal static string Globalization_cp_57004 => GetResourceString("Globalization_cp_57004"); internal static string Globalization_cp_57005 => GetResourceString("Globalization_cp_57005"); internal static string Globalization_cp_57006 => GetResourceString("Globalization_cp_57006"); internal static string Globalization_cp_57007 => GetResourceString("Globalization_cp_57007"); internal static string Globalization_cp_57008 => GetResourceString("Globalization_cp_57008"); internal static string Globalization_cp_57009 => GetResourceString("Globalization_cp_57009"); internal static string Globalization_cp_57010 => GetResourceString("Globalization_cp_57010"); internal static string Globalization_cp_57011 => GetResourceString("Globalization_cp_57011"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } internal static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider provider, string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] internal sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] internal sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } } namespace System.Runtime.Versioning { internal abstract class OSPlatformAttribute : Attribute { public string PlatformName { get; } private protected OSPlatformAttribute(string platformName) { PlatformName = platformName; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] internal sealed class TargetPlatformAttribute : OSPlatformAttribute { public TargetPlatformAttribute(string platformName) : base(platformName) { } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] internal sealed class SupportedOSPlatformAttribute : OSPlatformAttribute { public SupportedOSPlatformAttribute(string platformName) : base(platformName) { } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] internal sealed class UnsupportedOSPlatformAttribute : OSPlatformAttribute { public string Message { get; } public UnsupportedOSPlatformAttribute(string platformName) : base(platformName) { } public UnsupportedOSPlatformAttribute(string platformName, string message) : base(platformName) { Message = message; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] internal sealed class ObsoletedOSPlatformAttribute : OSPlatformAttribute { public string Message { get; } public string Url { get; set; } public ObsoletedOSPlatformAttribute(string platformName) : base(platformName) { } public ObsoletedOSPlatformAttribute(string platformName, string message) : base(platformName) { Message = message; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] internal sealed class SupportedOSPlatformGuardAttribute : OSPlatformAttribute { public SupportedOSPlatformGuardAttribute(string platformName) : base(platformName) { } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] internal sealed class UnsupportedOSPlatformGuardAttribute : OSPlatformAttribute { public UnsupportedOSPlatformGuardAttribute(string platformName) : base(platformName) { } } } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class LibraryImportAttribute : Attribute { public string LibraryName { get; } public string EntryPoint { get; set; } public StringMarshalling StringMarshalling { get; set; } public Type StringMarshallingCustomType { get; set; } public bool SetLastError { get; set; } public LibraryImportAttribute(string libraryName) { LibraryName = libraryName; } } internal enum StringMarshalling { Custom, Utf8, Utf16 } } namespace System.Text { internal abstract class BaseCodePageEncoding : EncodingNLS, ISerializable { [StructLayout(LayoutKind.Explicit)] internal struct CodePageDataFileHeader { [FieldOffset(0)] internal char TableName; [FieldOffset(32)] internal ushort Version; [FieldOffset(40)] internal short CodePageCount; [FieldOffset(42)] internal short unused1; } [StructLayout(LayoutKind.Explicit, Pack = 2)] internal struct CodePageIndex { [FieldOffset(0)] internal char CodePageName; [FieldOffset(32)] internal short CodePage; [FieldOffset(34)] internal short ByteCount; [FieldOffset(36)] internal int Offset; } [StructLayout(LayoutKind.Explicit)] internal struct CodePageHeader { [FieldOffset(0)] internal char CodePageName; [FieldOffset(32)] internal ushort VersionMajor; [FieldOffset(34)] internal ushort VersionMinor; [FieldOffset(36)] internal ushort VersionRevision; [FieldOffset(38)] internal ushort VersionBuild; [FieldOffset(40)] internal short CodePage; [FieldOffset(42)] internal short ByteCount; [FieldOffset(44)] internal char UnicodeReplace; [FieldOffset(46)] internal ushort ByteReplace; } internal const string CODE_PAGE_DATA_FILE_NAME = "codepages.nlp"; protected int dataTableCodePage; protected int iExtraBytes; protected char[] arrayUnicodeBestFit; protected char[] arrayBytesBestFit; private const int CODEPAGE_DATA_FILE_HEADER_SIZE = 44; private const int CODEPAGE_HEADER_SIZE = 48; private static readonly byte[] s_codePagesDataHeader = new byte[44]; protected static Stream s_codePagesEncodingDataStream = GetEncodingDataStream("codepages.nlp"); protected static readonly object s_streamLock = new object(); protected byte[] m_codePageHeader = new byte[48]; protected int m_firstDataWordOffset; protected int m_dataSize; protected SafeAllocHHandle safeNativeMemoryHandle; internal BaseCodePageEncoding(int codepage) : this(codepage, codepage) { } internal BaseCodePageEncoding(int codepage, int dataCodePage) : base(codepage, new InternalEncoderBestFitFallback(null), new InternalDecoderBestFitFallback(null)) { ((InternalEncoderBestFitFallback)base.EncoderFallback).encoding = this; ((InternalDecoderBestFitFallback)base.DecoderFallback).encoding = this; dataTableCodePage = dataCodePage; LoadCodePageTables(); } internal BaseCodePageEncoding(int codepage, int dataCodePage, EncoderFallback enc, DecoderFallback dec) : base(codepage, enc, dec) { dataTableCodePage = dataCodePage; LoadCodePageTables(); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } private unsafe static void ReadCodePageDataFileHeader(Stream stream, byte[] codePageDataFileHeader) { int num = stream.Read(codePageDataFileHeader, 0, codePageDataFileHeader.Length); if (BitConverter.IsLittleEndian) { return; } fixed (byte* ptr = &codePageDataFileHeader[0]) { CodePageDataFileHeader* ptr2 = (CodePageDataFileHeader*)ptr; char* ptr3 = &ptr2->TableName; for (int i = 0; i < 16; i++) { ptr3[i] = (char)BinaryPrimitives.ReverseEndianness(ptr3[i]); } ushort* ptr4 = &ptr2->Version; for (int j = 0; j < 4; j++) { ptr4[j] = BinaryPrimitives.ReverseEndianness(ptr4[j]); } ptr2->CodePageCount = BinaryPrimitives.ReverseEndianness(ptr2->CodePageCount); } } private unsafe static void ReadCodePageIndex(Stream stream, byte[] codePageIndex) { int num = stream.Read(codePageIndex, 0, codePageIndex.Length); if (BitConverter.IsLittleEndian) { return; } fixed (byte* ptr = &codePageIndex[0]) { CodePageIndex* ptr2 = (CodePageIndex*)ptr; char* ptr3 = &ptr2->CodePageName; for (int i = 0; i < 16; i++) { ptr3[i] = (char)BinaryPrimitives.ReverseEndianness(ptr3[i]); } ptr2->CodePage = BinaryPrimitives.ReverseEndianness(ptr2->CodePage); ptr2->ByteCount = BinaryPrimitives.ReverseEndianness(ptr2->ByteCount); ptr2->Offset = BinaryPrimitives.ReverseEndianness(ptr2->Offset); } } private unsafe static void ReadCodePageHeader(Stream stream, byte[] codePageHeader) { int num = stream.Read(codePageHeader, 0, codePageHeader.Length); if (BitConverter.IsLittleEndian) { return; } fixed (byte* ptr = &codePageHeader[0]) { CodePageHeader* ptr2 = (CodePageHeader*)ptr; char* ptr3 = &ptr2->CodePageName; for (int i = 0; i < 16; i++) { ptr3[i] = (char)BinaryPrimitives.ReverseEndianness(ptr3[i]); } ptr2->VersionMajor = BinaryPrimitives.ReverseEndianness(ptr2->VersionMajor); ptr2->VersionMinor = BinaryPrimitives.ReverseEndianness(ptr2->VersionMinor); ptr2->VersionRevision = BinaryPrimitives.ReverseEndianness(ptr2->VersionRevision); ptr2->VersionBuild = BinaryPrimitives.ReverseEndianness(ptr2->VersionBuild); ptr2->CodePage = BinaryPrimitives.ReverseEndianness(ptr2->CodePage); ptr2->ByteCount = BinaryPrimitives.ReverseEndianness(ptr2->ByteCount); ptr2->UnicodeReplace = (char)BinaryPrimitives.ReverseEndianness(ptr2->UnicodeReplace); ptr2->ByteReplace = BinaryPrimitives.ReverseEndianness(ptr2->ByteReplace); } } internal static Stream GetEncodingDataStream(string tableName) { Stream manifestResourceStream = typeof(CodePagesEncodingProvider).Assembly.GetManifestResourceStream(tableName); if (manifestResourceStream == null) { throw new InvalidOperationException(); } ReadCodePageDataFileHeader(manifestResourceStream, s_codePagesDataHeader); return manifestResourceStream; } private void LoadCodePageTables() { if (!FindCodePage(dataTableCodePage)) { throw new NotSupportedException(System.SR.Format(System.SR.NotSupported_NoCodepageData, CodePage)); } LoadManagedCodePage(); } private unsafe bool FindCodePage(int codePage) { byte[] array = new byte[sizeof(CodePageIndex)]; lock (s_streamLock) { s_codePagesEncodingDataStream.Seek(44L, SeekOrigin.Begin); int codePageCount; fixed (byte* ptr = &s_codePagesDataHeader[0]) { CodePageDataFileHeader* ptr2 = (CodePageDataFileHeader*)ptr; codePageCount = ptr2->CodePageCount; } fixed (byte* ptr3 = &array[0]) { CodePageIndex* ptr4 = (CodePageIndex*)ptr3; for (int i = 0; i < codePageCount; i++) { ReadCodePageIndex(s_codePagesEncodingDataStream, array); if (ptr4->CodePage == codePage) { long position = s_codePagesEncodingDataStream.Position; s_codePagesEncodingDataStream.Seek(ptr4->Offset, SeekOrigin.Begin); ReadCodePageHeader(s_codePagesEncodingDataStream, m_codePageHeader); m_firstDataWordOffset = (int)s_codePagesEncodingDataStream.Position; if (i == codePageCount - 1) { m_dataSize = (int)(s_codePagesEncodingDataStream.Length - ptr4->Offset - m_codePageHeader.Length); } else { s_codePagesEncodingDataStream.Seek(position, SeekOrigin.Begin); int offset = ptr4->Offset; ReadCodePageIndex(s_codePagesEncodingDataStream, array); m_dataSize = ptr4->Offset - offset - m_codePageHeader.Length; } return true; } } } } return false; } internal unsafe static int GetCodePageByteSize(int codePage) { byte[] array = new byte[sizeof(CodePageIndex)]; lock (s_streamLock) { s_codePagesEncodingDataStream.Seek(44L, SeekOrigin.Begin); int codePageCount; fixed (byte* ptr = &s_codePagesDataHeader[0]) { CodePageDataFileHeader* ptr2 = (CodePageDataFileHeader*)ptr; codePageCount = ptr2->CodePageCount; } fixed (byte* ptr3 = &array[0]) { CodePageIndex* ptr4 = (CodePageIndex*)ptr3; for (int i = 0; i < codePageCount; i++) { ReadCodePageIndex(s_codePagesEncodingDataStream, array); if (ptr4->CodePage == codePage) { return ptr4->ByteCount; } } } } return 0; } protected abstract void LoadManagedCodePage(); protected unsafe byte* GetNativeMemory(int iSize) { if (safeNativeMemoryHandle == null) { byte* ptr = (byte*)(void*)Marshal.AllocHGlobal(iSize); safeNativeMemoryHandle = new SafeAllocHHandle((IntPtr)ptr); } return (byte*)(void*)safeNativeMemoryHandle.DangerousGetHandle(); } protected abstract void ReadBestFitTable(); internal char[] GetBestFitUnicodeToBytesData() { if (arrayUnicodeBestFit == null) { ReadBestFitTable(); } return arrayUnicodeBestFit; } internal char[] GetBestFitBytesToUnicodeData() { if (arrayBytesBestFit == null) { ReadBestFitTable(); } return arrayBytesBestFit; } internal void CheckMemorySection() { if (safeNativeMemoryHandle != null && safeNativeMemoryHandle.DangerousGetHandle() == IntPtr.Zero) { LoadManagedCodePage(); } } } public sealed class CodePagesEncodingProvider : EncodingProvider { private static readonly EncodingProvider s_singleton = new CodePagesEncodingProvider(); private readonly Dictionary<int, Encoding> _encodings = new Dictionary<int, Encoding>(); private readonly ReaderWriterLockSlim _cacheLock = new ReaderWriterLockSlim(); private const int ISCIIAssemese = 57006; private const int ISCIIBengali = 57003; private const int ISCIIDevanagari = 57002; private const int ISCIIGujarathi = 57010; private const int ISCIIKannada = 57008; private const int ISCIIMalayalam = 57009; private const int ISCIIOriya = 57007; private const int ISCIIPanjabi = 57011; private const int ISCIITamil = 57004; private const int ISCIITelugu = 57005; private const int ISOKorean = 50225; private const int ChineseHZ = 52936; private const int ISO2022JP = 50220; private const int ISO2022JPESC = 50221; private const int ISO2022JPSISO = 50222; private const int ISOSimplifiedCN = 50227; private const int EUCJP = 51932; private const int CodePageMacGB2312 = 10008; private const int CodePageMacKorean = 10003; private const int CodePageGB2312 = 20936; private const int CodePageDLLKorean = 20949; private const int GB18030 = 54936; private const int DuplicateEUCCN = 51936; private const int EUCKR = 51949; private const int EUCCN = 936; private const int ISO_8859_8I = 38598; private const int ISO_8859_8_Visual = 28598; public static EncodingProvider Instance => s_singleton; private static int SystemDefaultCodePage => 0; internal CodePagesEncodingProvider() { } public override Encoding? GetEncoding(int codepage) { if (codepage < 0 || codepage > 65535) { return null; } if (codepage == 0) { int systemDefaultCodePage = SystemDefaultCodePage; if (systemDefaultCodePage == 0) { return null; } return GetEncoding(systemDefaultCodePage); } Encoding value = null; _cacheLock.EnterUpgradeableReadLock(); try { if (_encodings.TryGetValue(codepage, out value)) { return value; } switch (BaseCodePageEncoding.GetCodePageByteSize(codepage)) { case 1: value = new SBCSCodePageEncoding(codepage); break; case 2: value = new DBCSCodePageEncoding(codepage); break; default: value = GetEncodingRare(codepage); if (value == null) { return null; } break; } _cacheLock.EnterWriteLock(); try { if (_encodings.TryGetValue(codepage, out var value2)) { return value2; } _encodings.Add(codepage, value); return value; } finally { _cacheLock.ExitWriteLock(); } } finally { _cacheLock.ExitUpgradeableReadLock(); } } public override Encoding? GetEncoding(string name) { int codePageFromName = System.Text.EncodingTable.GetCodePageFromName(name); if (codePageFromName == 0) { return null; } return GetEncoding(codePageFromName); } private static Encoding GetEncodingRare(int codepage) { Encoding result = null; switch (codepage) { case 57002: case 57003: case 57004: case 57005: case 57006: case 57007: case 57008: case 57009: case 57010: case 57011: result = new ISCIIEncoding(codepage); break; case 10008: result = new DBCSCodePageEncoding(10008, 20936); break; case 10003: result = new DBCSCodePageEncoding(10003, 20949); break; case 54936: result = new GB18030Encoding(); break; case 50220: case 50221: case 50222: case 50225: case 52936: result = new ISO2022Encoding(codepage); break; case 50227: case 51936: result = new DBCSCodePageEncoding(codepage, 936); break; case 51932: result = new EUCJPEncoding(); break; case 51949: result = new DBCSCodePageEncoding(codepage, 20949); break; case 38598: result = new SBCSCodePageEncoding(codepage, 28598); break; } return result; } } internal class DBCSCodePageEncoding : BaseCodePageEncoding { internal sealed class DBCSDecoder : System.Text.DecoderNLS { internal byte bLeftOver; internal override bool HasState => bLeftOver != 0; public DBCSDecoder(DBCSCodePageEncoding encoding) : base(encoding) { } public override void Reset() { bLeftOver = 0; m_fallbackBuffer?.Reset(); } } protected unsafe char* mapBytesToUnicode = null; protected unsafe ushort* mapUnicodeToBytes = null; protected const char UNKNOWN_CHAR_FLAG = '\0'; protected const char UNICODE_REPLACEMENT_CHAR = '\ufffd'; protected const char LEAD_BYTE_CHAR = '\ufffe'; private ushort _bytesUnknown; private int _byteCountUnknown; protected char charUnknown; private static object s_InternalSyncObject; private static object InternalSyncObject { get { if (s_InternalSyncObject == null) { object value = new object(); Interlocked.CompareExchange<object>(ref s_InternalSyncObject, value, (object)null); } return s_InternalSyncObject; } } public DBCSCodePageEncoding(int codePage) : this(codePage, codePage) { } internal unsafe DBCSCodePageEncoding(int codePage, int dataCodePage) : base(codePage, dataCodePage) { } internal unsafe DBCSCodePageEncoding(int codePage, int dataCodePage, EncoderFallback enc, DecoderFallback dec) : base(codePage, dataCodePage, enc, dec) { } internal unsafe static char ReadChar(char* pChar) { if (BitConverter.IsLittleEndian) { return *pChar; } return (char)BinaryPrimitives.ReverseEndianness(*pChar); } protected unsafe override void LoadManagedCodePage() { fixed (byte* ptr = &m_codePageHeader[0]) { CodePageHeader* ptr2 = (CodePageHeader*)ptr; if (ptr2->ByteCount != 2) { throw new NotSupportedException(System.SR.Format(System.SR.NotSupported_NoCodepageData, CodePage)); } _bytesUnknown = ptr2->ByteReplace; charUnknown = ptr2->UnicodeReplace; if (base.DecoderFallback is InternalDecoderBestFitFallback) { ((InternalDecoderBestFitFallback)base.DecoderFallback).cReplacement = charUnknown; } _byteCountUnknown = 1; if (_bytesUnknown > 255) { _byteCountUnknown++; } int num = 262148 + iExtraBytes; byte* nativeMemory = GetNativeMemory(num); Unsafe.InitBlockUnaligned(nativeMemory, 0, (uint)num); mapBytesToUnicode = (char*)nativeMemory; mapUnicodeToBytes = (ushort*)(nativeMemory + 131072); byte[] array = new byte[m_dataSize]; lock (BaseCodePageEncoding.s_streamLock) { BaseCodePageEncoding.s_codePagesEncodingDataStream.Seek(m_firstDataWordOffset, SeekOrigin.Begin); int num2 = BaseCodePageEncoding.s_codePagesEncodingDataStream.Read(array, 0, m_dataSize); } fixed (byte* ptr3 = array) { char* ptr4 = (char*)ptr3; int num3 = 0; int num4 = 0; while (num3 < 65536) { char c = ReadChar(ptr4); ptr4++; switch (c) { case '\u0001': num3 = ReadChar(ptr4); ptr4++; continue; case '\u0002': case '\u0003': case '\u0004': case '\u0005': case '\u0006': case '\a': case '\b': case '\t': case '\n': case '\v': case '\f': case '\r': case '\u000e': case '\u000f': case '\u0010': case '\u0011': case '\u0012': case '\u0013': case '\u0014': case '\u0015': case '\u0016': case '\u0017': case '\u0018': case '\u0019': case '\u001a': case '\u001b': case '\u001c': case '\u001d': case '\u001e': case '\u001f': num3 += c; continue; } switch (c) { case '\uffff': num4 = num3; c = (char)num3; break; case '\ufffe': num4 = num3; break; case '\ufffd': num3++; continue; default: num4 = num3; break; } if (CleanUpBytes(ref num4)) { if (c != '\ufffe') { mapUnicodeToBytes[(int)c] = (ushort)num4; } mapBytesToUnicode[num4] = c; } num3++; } } CleanUpEndBytes(mapBytesToUnicode); } } protected virtual bool CleanUpBytes(ref int bytes) { return true; } protected unsafe virtual void CleanUpEndBytes(char* chars) { } protected unsafe override void ReadBestFitTable() { lock (InternalSyncObject) { if (arrayUnicodeBestFit != null) { return; } byte[] array = new byte[m_dataSize]; lock (BaseCodePageEncoding.s_streamLock) { BaseCodePageEncoding.s_codePagesEncodingDataStream.Seek(m_firstDataWordOffset, SeekOrigin.Begin); int num = BaseCodePageEncoding.s_codePagesEncodingDataStream.Read(array, 0, m_dataSize); } fixed (byte* ptr = array) { char* ptr2 = (char*)ptr; int num2 = 0; while (num2 < 65536) { char c = ReadChar(ptr2); ptr2++; switch (c) { case '\u0001': num2 = ReadChar(ptr2); ptr2++; break; case '\u0002': case '\u0003': case '\u0004': case '\u0005': case '\u0006': case '\a': case '\b': case '\t': case '\n': case '\v': case '\f': case '\r': case '\u000e': case '\u000f': case '\u0010': case '\u0011': case '\u0012': case '\u0013': case '\u0014': case '\u0015': case '\u0016': case '\u0017': case '\u0018': case '\u0019': case '\u001a': case '\u001b': case '\u001c': case '\u001d': case '\u001e': case '\u001f': num2 += c; break; default: num2++; break; } } char* ptr3 = ptr2; int num3 = 0; num2 = ReadChar(ptr2); ptr2++; while (num2 < 65536) { char c2 = ReadChar(ptr2); ptr2++; switch (c2) { case '\u0001': num2 = ReadChar(ptr2); ptr2++; continue; case '\u0002': case '\u0003': case '\u0004': case '\u0005': case '\u0006': case '\a': case '\b': case '\t': case '\n': case '\v': case '\f': case '\r': case '\u000e': case '\u000f': case '\u0010': case '\u0011': case '\u0012': case '\u0013': case '\u0014': case '\u0015': case '\u0016': case '\u0017': case '\u0018': case '\u0019': case '\u001a': case '\u001b': case '\u001c': case '\u001d': case '\u001e': case '\u001f': num2 += c2; continue; } if (c2 != '\ufffd') { int bytes = num2; if (CleanUpBytes(ref bytes) && mapBytesToUnicode[bytes] != c2) { num3++; } } num2++; } char[] array2 = new char[num3 * 2]; num3 = 0; ptr2 = ptr3; num2 = ReadChar(ptr2); ptr2++; bool flag = false; while (num2 < 65536) { char c3 = ReadChar(ptr2); ptr2++; switch (c3) { case '\u0001': num2 = ReadChar(ptr2); ptr2++; continue; case '\u0002': case '\u0003': case '\u0004': case '\u0005': case '\u0006': case '\a': case '\b': case '\t': case '\n': case '\v': case '\f': case '\r': case '\u000e': case '\u000f': case '\u0010': case '\u0011': case '\u0012': case '\u0013': case '\u0014': case '\u0015': case '\u0016': case '\u0017': case '\u0018': case '\u0019': case '\u001a': case '\u001b': case '\u001c': case '\u001d': case '\u001e': case '\u001f': num2 += c3; continue; } if (c3 != '\ufffd') { int bytes2 = num2; if (CleanUpBytes(ref bytes2) && mapBytesToUnicode[bytes2] != c3) { if (bytes2 != num2) { flag = true; } array2[num3++] = (char)bytes2; array2[num3++] = c3; } } num2++; } if (flag) { for (int i = 0; i < array2.Length - 2; i += 2) { int num4 = i; char c4 = array2[i]; for (int j = i + 2; j < array2.Length; j += 2) { if (c4 > array2[j]) { c4 = array2[j]; num4 = j; } } if (num4 != i) { char c5 = array2[num4]; array2[num4] = array2[i]; array2[i] = c5; c5 = array2[num4 + 1]; array2[num4 + 1] = array2[i + 1]; array2[i + 1] = c5; } } } arrayBytesBestFit = array2; char* ptr4 = ptr2; int num5 = ReadChar(ptr2++); num3 = 0; while (num5 < 65536) { char c6 = ReadChar(ptr2); ptr2++; switch (c6) { case '\u0001': num5 = ReadChar(ptr2); ptr2++; continue; case '\u0002': case '\u0003': case '\u0004': case '\u0005': case '\u0006': case '\a': case '\b': case '\t': case '\n': case '\v': case '\f': case '\r': case '\u000e': case '\u000f': case '\u0010': case '\u0011': case '\u0012': case '\u0013': case '\u0014': case '\u0015': case '\u0016': case '\u0017': case '\u0018': case '\u0019': case '\u001a': case '\u001b': case '\u001c': case '\u001d': case '\u001e': case '\u001f': num5 += c6; continue; } if (c6 > '\0') { num3++; } num5++; } array2 = new char[num3 * 2]; ptr2 = ptr4; num5 = ReadChar(ptr2++); num3 = 0; while (num5 < 65536) { char c7 = ReadChar(ptr2); ptr2++; switch (c7) { case '\u0001': num5 = ReadChar(ptr2); ptr2++; continue; case '\u0002': case '\u0003': case '\u0004': case '\u0005': case '\u0006': case '\a': case '\b': case '\t': case '\n': case '\v': case '\f': case '\r': case '\u000e': case '\u000f': case '\u0010': case '\u0011': case '\u0012': case '\u0013': case '\u0014': case '\u0015': case '\u0016': case '\u0017': case '\u0018': case '\u0019': case '\u001a': case '\u001b': case '\u001c': case '\u001d': case '\u001e': case '\u001f': num5 += c7; continue; } if (c7 > '\0') { int bytes3 = c7; if (CleanUpBytes(ref bytes3)) { array2[num3++] = (char)num5; array2[num3++] = mapBytesToUnicode[bytes3]; } } num5++; } arrayUnicodeBestFit = array2; } } } public unsafe override int GetByteCount(char* chars, int count, System.Text.EncoderNLS encoder) { CheckMemorySection(); char c = '\0'; if (encoder != null) { c = encoder.charLeftOver; if (encoder.InternalHasFallbackBuffer && encoder.FallbackBuffer.Remaining > 0) { throw new ArgumentException(System.SR.Format(System.SR.Argument_EncoderFallbackNotEmpty, EncodingName, encoder.Fallback.GetType())); } } int num = 0; char* ptr = chars + count; EncoderFallbackBuffer encoderFallbackBuffer = null; EncoderFallbackBufferHelper encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer); if (c > '\0') { encoderFallbackBuffer = encoder.FallbackBuffer; encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer); encoderFallbackBufferHelper.InternalInitialize(chars, ptr, encoder, _setEncoder: false); encoderFallbackBufferHelper.InternalFallback(c, ref chars); } char c2; while ((c2 = ((encoderFallbackBuffer != null) ? encoderFallbackBufferHelper.InternalGetNextChar() : '\0')) != 0 || chars < ptr) { if (c2 == '\0') { c2 = *chars; chars++; } ushort num2 = mapUnicodeToBytes[(int)c2]; if (num2 == 0 && c2 != 0) { if (encoderFallbackBuffer == null) { encoderFallbackBuffer = ((encoder != null) ? encoder.FallbackBuffer : base.EncoderFallback.CreateFallbackBuffer()); encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer); encoderFallbackBufferHelper.InternalInitialize(ptr - count, ptr, encoder, _setEncoder: false); } encoderFallbackBufferHelper.InternalFallback(c2, ref chars); } else { num++; if (num2 >= 256) { num++; } } } return num; } public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, System.Text.EncoderNLS encoder) { CheckMemorySection(); EncoderFallbackBuffer encoderFallbackBuffer = null; char* ptr = chars + charCount; char* ptr2 = chars; byte* ptr3 = bytes; byte* ptr4 = bytes + byteCount; EncoderFallbackBufferHelper encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer); char c = '\0'; if (encoder != null) { c = encoder.charLeftOver; encoderFallbackBuffer = encoder.FallbackBuffer; encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer); encoderFallbackBufferHelper.InternalInitialize(chars, ptr, encoder, _setEncoder: true); if (encoder.m_throwOnOverflow && encoderFallbackBuffer.Remaining > 0) { throw new ArgumentException(System.SR.Format(System.SR.Argument_EncoderFallbackNotEmpty, EncodingName, encoder.Fallback.GetType())); } if (c > '\0') { encoderFallbackBufferHelper.InternalFallback(c, ref chars); } } char c2; while ((c2 = ((encoderFallbackBuffer != null) ? encoderFallbackBufferHelper.InternalGetNextChar() : '\0')) != 0 || chars < ptr) { if (c2 == '\0') { c2 = *chars; chars++; } ushort num = mapUnicodeToBytes[(int)c2]; if (num == 0 && c2 != 0) { if (encoderFallbackBuffer == null) { encoderFallbackBuffer = base.EncoderFallback.CreateFallbackBuffer(); encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer); encoderFallbackBufferHelper.InternalInitialize(ptr - charCount, ptr, encoder, _setEncoder: true); } encoderFallbackBufferHelper.InternalFallback(c2, ref chars); continue; } if (num >= 256) { if (bytes + 1 >= ptr4) { if (encoderFallbackBuffer == null || !encoderFallbackBufferHelper.bFallingBack) { chars--; } else { encoderFallbackBuffer.MovePrevious(); } ThrowBytesOverflow(encoder, chars == ptr2); break; } *bytes = (byte)(num >> 8); bytes++; } else if (bytes >= ptr4) { if (encoderFallbackBuffer == null || !encoderFallbackBufferHelper.bFallingBack) { chars--; } else { encoderFallbackBuffer.MovePrevious(); } ThrowBytesOverflow(encoder, chars == ptr2); break; } *bytes = (byte)(num & 0xFFu); bytes++; } if (encoder != null) { if (encoderFallbackBuffer != null && !encoderFallbackBufferHelper.bUsedEncoder) { encoder.charLeftOver = '\0'; } encoder.m_charsUsed = (int)(chars - ptr2); } return (int)(bytes - ptr3); } public unsafe override int GetCharCount(byte* bytes, int count, System.Text.DecoderNLS baseDecoder) { CheckMemorySection(); DBCSDecoder dBCSDecoder = (DBCSDecoder)baseDecoder; DecoderFallbackBuffer decoderFallbackBuffer = null; byte* ptr = bytes + count; int num = count; DecoderFallbackBufferHelper decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); if (dBCSDecoder != null && dBCSDecoder.bLeftOver > 0) { if (count == 0) { if (!dBCSDecoder.MustFlush) { return 0; } decoderFallbackBuffer = dBCSDecoder.FallbackBuffer; decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); decoderFallbackBufferHelper.InternalInitialize(bytes, null); byte[] bytes2 = new byte[1] { dBCSDecoder.bLeftOver }; return decoderFallbackBufferHelper.InternalFallback(bytes2, bytes); } int num2 = dBCSDecoder.bLeftOver << 8; num2 |= *bytes; bytes++; if (mapBytesToUnicode[num2] == '\0' && num2 != 0) { num--; decoderFallbackBuffer = dBCSDecoder.FallbackBuffer; decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); decoderFallbackBufferHelper.InternalInitialize(ptr - count, null); byte[] bytes3 = new byte[2] { (byte)(num2 >> 8), (byte)num2 }; num += decoderFallbackBufferHelper.InternalFallback(bytes3, bytes); } } while (bytes < ptr) { int num3 = *bytes; bytes++; char c = mapBytesToUnicode[num3]; if (c == '\ufffe') { num--; if (bytes < ptr) { num3 <<= 8; num3 |= *bytes; bytes++; c = mapBytesToUnicode[num3]; } else { if (dBCSDecoder != null && !dBCSDecoder.MustFlush) { break; } num++; c = '\0'; } } if (c == '\0' && num3 != 0) { if (decoderFallbackBuffer == null) { decoderFallbackBuffer = ((dBCSDecoder != null) ? dBCSDecoder.FallbackBuffer : base.DecoderFallback.CreateFallbackBuffer()); decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); decoderFallbackBufferHelper.InternalInitialize(ptr - count, null); } num--; byte[] bytes4 = ((num3 >= 256) ? new byte[2] { (byte)(num3 >> 8), (byte)num3 } : new byte[1] { (byte)num3 }); num += decoderFallbackBufferHelper.InternalFallback(bytes4, bytes); } } return num; } public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount, System.Text.DecoderNLS baseDecoder) { CheckMemorySection(); DBCSDecoder dBCSDecoder = (DBCSDecoder)baseDecoder; byte* ptr = bytes; byte* ptr2 = bytes + byteCount; char* ptr3 = chars; char* ptr4 = chars + charCount; bool flag = false; DecoderFallbackBuffer decoderFallbackBuffer = null; DecoderFallbackBufferHelper decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); if (dBCSDecoder != null && dBCSDecoder.bLeftOver > 0) { if (byteCount == 0) { if (!dBCSDecoder.MustFlush) { return 0; } decoderFallbackBuffer = dBCSDecoder.FallbackBuffer; decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); decoderFallbackBufferHelper.InternalInitialize(bytes, ptr4); byte[] bytes2 = new byte[1] { dBCSDecoder.bLeftOver }; if (!decoderFallbackBufferHelper.InternalFallback(bytes2, bytes, ref chars)) { ThrowCharsOverflow(dBCSDecoder, nothingDecoded: true); } dBCSDecoder.bLeftOver = 0; return (int)(chars - ptr3); } int num = dBCSDecoder.bLeftOver << 8; num |= *bytes; bytes++; char c = mapBytesToUnicode[num]; if (c == '\0' && num != 0) { decoderFallbackBuffer = dBCSDecoder.FallbackBuffer; decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); decoderFallbackBufferHelper.InternalInitialize(ptr2 - byteCount, ptr4); byte[] bytes3 = new byte[2] { (byte)(num >> 8), (byte)num }; if (!decoderFallbackBufferHelper.InternalFallback(bytes3, bytes, ref chars)) { ThrowCharsOverflow(dBCSDecoder, nothingDecoded: true); } } else { if (chars >= ptr4) { ThrowCharsOverflow(dBCSDecoder, nothingDecoded: true); } *(chars++) = c; } } while (bytes < ptr2) { int num2 = *bytes; bytes++; char c2 = mapBytesToUnicode[num2]; if (c2 == '\ufffe') { if (bytes < ptr2) { num2 <<= 8; num2 |= *bytes; bytes++; c2 = mapBytesToUnicode[num2]; } else { if (dBCSDecoder != null && !dBCSDecoder.MustFlush) { flag = true; dBCSDecoder.bLeftOver = (byte)num2; break; } c2 = '\0'; } } if (c2 == '\0' && num2 != 0) { if (decoderFallbackBuffer == null) { decoderFallbackBuffer = ((dBCSDecoder != null) ? dBCSDecoder.FallbackBuffer : base.DecoderFallback.CreateFallbackBuffer()); decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); decoderFallbackBufferHelper.InternalInitialize(ptr2 - byteCount, ptr4); } byte[] array = ((num2 >= 256) ? new byte[2] { (byte)(num2 >> 8), (byte)num2 } : new byte[1] { (byte)num2 }); if (!decoderFallbackBufferHelper.InternalFallback(array, bytes, ref chars)) { bytes -= array.Length; decoderFallbackBufferHelper.InternalReset(); ThrowCharsOverflow(dBCSDecoder, bytes == ptr); break; } continue; } if (chars >= ptr4) { bytes--; if (num2 >= 256) { bytes--; } ThrowCharsOverflow(dBCSDecoder, bytes == ptr); break; } *(chars++) = c2; } if (dBCSDecoder != null) { if (!flag) { dBCSDecoder.bLeftOver = 0; } dBCSDecoder.m_bytesUsed = (int)(bytes - ptr); } return (int)(chars - ptr3); } public override int GetMaxByteCount(int charCount) { if (charCount < 0) { throw new ArgumentOutOfRangeException("charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } long num = (long)charCount + 1L; if (base.EncoderFallback.MaxCharCount > 1) { num *= base.EncoderFallback.MaxCharCount; } num *= 2; if (num > int.MaxValue) { throw new ArgumentOutOfRangeException("charCount", System.SR.ArgumentOutOfRange_GetByteCountOverflow); } return (int)num; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) { throw new ArgumentOutOfRangeException("byteCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } long num = (long)byteCount + 1L; if (base.DecoderFallback.MaxCharCount > 1) { num *= base.DecoderFallback.MaxCharCount; } if (num > int.MaxValue) { throw new ArgumentOutOfRangeException("byteCount", System.SR.ArgumentOutOfRange_GetCharCountOverflow); } return (int)num; } public override Decoder GetDecoder() { return new DBCSDecoder(this); } } internal sealed class InternalDecoderBestFitFallback : DecoderFallback { internal BaseCodePageEncoding encoding; internal char[] arrayBestFit; internal char cReplacement = '?'; public override int MaxCharCount => 1; internal InternalDecoderBestFitFallback(BaseCodePageEncoding _encoding) { encoding = _encoding; } public override DecoderFallbackBuffer CreateFallbackBuffer() { return new InternalDecoderBestFitFallbackBuffer(this); } public override bool Equals([NotNullWhen(true)] object value) { if (value is InternalDecoderBestFitFallback internalDecoderBestFitFallback) { return encoding.CodePage == internalDecoderBestFitFallback.encoding.CodePage; } return false; } public override int GetHashCode() { return encoding.CodePage; } } internal sealed class InternalDecoderBestFitFallbackBuffer : DecoderFallbackBuffer { internal char cBestFit; internal int iCount = -1; internal int iSize; private readonly InternalDecoderBestFitFallback _oFallback; private static object s_InternalSyncObject; private static object InternalSyncObject { get { if (s_InternalSyncObject == null) { object value = new object(); Interlocked.CompareExchange<object>(ref s_InternalSyncObject, value, (object)null); } return s_InternalSyncObject; } } public override int Remaining { get { if (iCount <= 0) { return 0; } return iCount; } } public InternalDecoderBestFitFallbackBuffer(InternalDecoderBestFitFallback fallback) { _oFallback = fallback; if (_oFallback.arrayBestFit != null) { return; } lock (InternalSyncObject) { InternalDecoderBestFitFallback oFallback = _oFallback; if (oFallback.arrayBestFit == null) { oFallback.arrayBestFit = fallback.encoding.GetBestFitBytesToUnicodeData(); } } } public override bool Fallback(byte[] bytesUnknown, int index) { cBestFit = TryBestFit(bytesUnknown); if (cBestFit == '\0') { cBestFit = _oFallback.cReplacement; } iCount = (iSize = 1); return true; } public override char GetNextChar() { iCount--; if (iCount < 0) { return '\0'; } if (iCount == int.MaxValue) { iCount = -1; return '\0'; } return cBestFit; } public override bool MovePrevious() { if (iCount >= 0) { iCount++; } if (iCount >= 0) { return iCount <= iSize; } return false; } public override void Reset() { iCount = -1; } internal unsafe static int InternalFallback(byte[] bytes, byte* pBytes) { return 1; } private char TryBestFit(byte[] bytesCheck) { int num = 0; int num2 = _oFallback.arrayBestFit.Length; if (num2 == 0) { return '\0'; } if (bytesCheck.Length == 0 || bytesCheck.Length > 2) { return '\0'; } char c = ((bytesCheck.Length != 1) ? ((char)((bytesCheck[0] << 8) + bytesCheck[1])) : ((char)bytesCheck[0])); if (c < _oFallback.arrayBestFit[0] || c > _oFallback.arrayBestFit[num2 - 2]) { return '\0'; } int num3; while ((num3 = num2 - num) > 6) { int num4 = (num3 / 2 + num) & 0xFFFE; char c2 = _oFallback.arrayBestFit[num4]; if (c2 == c) { return _oFallback.arrayBestFit[num4 + 1]; } if (c2 < c) { num = num4; } else { num2 = num4; } } for (int num4 = num; num4 < num2; num4 += 2) { if (_oFallback.arrayBestFit[num4] == c) { return _oFallback.arrayBestFit[num4 + 1]; } } return '\0'; } } internal struct DecoderFallbackBufferHelper { internal unsafe byte* byteStart; internal unsafe char* charEnd; private readonly DecoderFallbackBuffer _fallbackBuffer; public unsafe DecoderFallbackBufferHelper(DecoderFallbackBuffer fallbackBuffer) { _fallbackBuffer = fallbackBuffer; byteStart = null; charEnd = null; } internal unsafe void InternalReset() { byteStart = null; _fallbackBuffer.Reset(); } internal unsafe void InternalInitialize(byte* _byteStart, char* _charEnd) { byteStart = _byteStart; charEnd = _charEnd; } internal unsafe bool InternalFallback(byte[] bytes, byte* pBytes, ref char* chars) { if (_fallbackBuffer.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length))) { char* ptr = chars; bool flag = false; char nextChar; while ((nextChar = _fallbackBuffer.GetNextChar()) != 0) { if (char.IsSurrogate(nextChar)) { if (char.IsHighSurrogate(nextChar)) { if (flag) { throw new ArgumentException(System.SR.Argument_InvalidCharSequenceNoIndex); } flag = true; } else { if (!flag) { throw new ArgumentException(System.SR.Argument_InvalidCharSequenceNoIndex); } flag = false; } } if (ptr >= charEnd) { return false; } *(ptr++) = nextChar; } if (flag) { throw new ArgumentException(System.SR.Argument_InvalidCharSequenceNoIndex); } chars = ptr; } return true; } internal unsafe int InternalFallback(byte[] bytes, byte* pBytes) { if (_fallbackBuffer.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length))) { int num = 0; bool flag = false; char nextChar; while ((nextChar = _fallbackBuffer.GetNextChar()) != 0) { if (char.IsSurrogate(nextChar)) { if (char.IsHighSurrogate(nextChar)) { if (flag) { throw new ArgumentException(System.SR.Argument_InvalidCharSequenceNoIndex); } flag = true; } else { if (!flag) { throw new ArgumentException(System.SR.Argument_InvalidCharSequenceNoIndex); } flag = false; } } num++; } if (flag) { throw new ArgumentException(System.SR.Argument_InvalidCharSequenceNoIndex); } return num; } return 0; } } internal class DecoderNLS : Decoder, ISerializable { protected EncodingNLS m_encoding; protected bool m_mustFlush; internal bool m_throwOnOverflow; internal int m_bytesUsed; internal DecoderFallback m_fallback; internal DecoderFallbackBuffer m_fallbackBuffer; internal new DecoderFallback Fallback => m_fallback; internal bool InternalHasFallbackBuffer => m_fallbackBuffer != null; public new DecoderFallbackBuffer FallbackBuffer { get { if (m_fallbackBuffer == null) { m_fallbackBuffer = ((m_fallback != null) ? m_fallback.CreateFallbackBuffer() : DecoderFallback.ReplacementFallback.CreateFallbackBuffer()); } return m_fallbackBuffer; } } public bool MustFlush => m_mustFlush; internal virtual bool HasState => false; internal DecoderNLS(EncodingNLS encoding) { m_encoding = encoding; m_fallback = m_encoding.DecoderFallback; Reset(); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } public override void Reset() { m_fallbackBuffer?.Reset(); } public override int GetCharCount(byte[] bytes, int index, int count) { return GetCharCount(bytes, index, count, flush: false); } public unsafe override int GetCharCount(byte[] bytes, int index, int count, bool flush) { if (bytes == null) { throw new ArgumentNullException("bytes"); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - index < count) { throw new ArgumentOutOfRangeException("bytes", System.SR.ArgumentOutOfRange_IndexCountBuffer); } if (bytes.Length == 0) { bytes = new byte[1]; } fixed (byte* ptr = &bytes[0]) { return GetCharCount(ptr + index, count, flush); } } public unsafe override int GetCharCount(byte* bytes, int count, bool flush) { if (bytes == null) { throw new ArgumentNullException("bytes"); } if (count < 0) { throw new ArgumentOutOfRangeException("count", System.SR.ArgumentOutOfRange_NeedNonNegNum); } m_mustFlush = flush; m_throwOnOverflow = true; return m_encoding.GetCharCount(bytes, count, this); } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { return GetChars(bytes, byteIndex, byteCount, chars, charIndex, flush: false); } public unsafe override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush) { if (bytes == null) { throw new ArgumentNullException("bytes"); } if (chars == null) { throw new ArgumentNullException("chars"); } if (byteIndex < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException((byteIndex < 0) ? "byteIndex" : "byteCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - byteIndex < byteCount) { throw new ArgumentOutOfRangeException("bytes", System.SR.ArgumentOutOfRange_IndexCountBuffer); } if (charIndex < 0 || charIndex > chars.Length) { throw new ArgumentOutOfRangeException("charIndex", System.SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); } if (bytes.Length == 0) { bytes = new byte[1]; } int charCount = chars.Length - charIndex; if (chars.Length == 0) { chars = new char[1]; } fixed (byte* ptr = &bytes[0]) { fixed (char* ptr2 = &chars[0]) { return GetChars(ptr + byteIndex, byteCount, ptr2 + charIndex, charCount, flush); } } } public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush) { if (bytes == null) { throw new ArgumentNullException("bytes"); } if (chars == null) { throw new ArgumentNullException("chars"); } if (byteCount < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((byteCount < 0) ? "byteCount" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } m_mustFlush = flush; m_throwOnOverflow = true; return m_encoding.GetChars(bytes, byteCount, chars, charCount, this); } public unsafe override void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { if (bytes == null) { throw new ArgumentNullException("bytes"); } if (chars == null) { throw new ArgumentNullException("chars"); } if (byteIndex < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException((byteIndex < 0) ? "byteIndex" : "byteCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (charIndex < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - byteIndex < byteCount) { throw new ArgumentOutOfRangeException("bytes", System.SR.ArgumentOutOfRange_IndexCountBuffer); } if (chars.Length - charIndex < charCount) { throw new ArgumentOutOfRangeException("chars", System.SR.ArgumentOutOfRange_IndexCountBuffer); } if (bytes.Length == 0) { bytes = new byte[1]; } if (chars.Length == 0) { chars = new char[1]; } fixed (byte* ptr = &bytes[0]) { fixed (char* ptr2 = &chars[0]) { Convert(ptr + byteIndex, byteCount, ptr2 + charIndex, charCount, flush, out bytesUsed, out charsUsed, out completed); } } } public unsafe override void Convert(byte* bytes, int byteCount, char* chars, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { if (bytes == null) { throw new ArgumentNullException("bytes"); } if (chars == null) { throw new ArgumentNullException("chars"); } if (byteCount < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((byteCount < 0) ? "byteCount" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } m_mustFlush = flush; m_throwOnOverflow = false; m_bytesUsed = 0; charsUsed = m_encoding.GetChars(bytes, byteCount, chars, charCount, this); bytesUsed = m_bytesUsed; completed = bytesUsed == byteCount && (!flush || !HasState) && (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0); } internal void ClearMustFlush() { m_mustFlush = false; } } internal sealed class InternalEncoderBestFitFallback : EncoderFallback { internal BaseCodePageEncoding encoding; internal char[] arrayBestFit; public override int MaxCharCount => 1; internal InternalEncoderBestFitFallback(BaseCodePageEncoding _encoding) { encoding = _encoding; } public override EncoderFallbackBuffer CreateFallbackBuffer() { return new InternalEncoderBestFitFallbackBuffer(this); } public override bool Equals([NotNullWhen(true)] object value) { if (value is InternalEncoderBestFitFallback internalEncoderBestFitFallback) { return encoding.CodePage == internalEncoderBestFitFallback.encoding.CodePage; } return false; } public override int GetHashCode() { return encoding.CodePage; } } internal sealed class InternalEncoderBestFitFallbackBuffer : EncoderFallbackBuffer { private char _cBestFit; private readonly InternalEncoderBestFitFallback _oFallback; private int _iCount = -1; private int _iSize; private static object s_InternalSyncObject; private static object InternalSyncObject { get { if (s_InternalSyncObject == null) { object value = new object(); Interlocked.CompareExchange<object>(ref s_InternalSyncObject, value, (object)null); } return s_InternalSyncObject; } } public override int Remaining { get { if (_iCount <= 0) { return 0; } return _iCount; } } public InternalEncoderBestFitFallbackBuffer(InternalEncoderBestFitFallback fallback) { _oFallback = fallback; if (_oFallback.arrayBestFit != null) { return; } lock (InternalSyncObject) { InternalEncoderBestFitFallback oFallback = _oFallback; if (oFallback.arrayBestFit == null) { oFallback.arrayBestFit = fallback.encoding.GetBestFitUnicodeToBytesData(); } } } public override bool Fallback(char charUnknown, int index) { _iCount = (_iSize = 1); _cBestFit = TryBestFit(charUnknown); if (_cBestFit == '\0') { _cBestFit = '?'; } return true; } public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index) { if (!char.IsHighSurrogate(charUnknownHigh)) { throw new ArgumentOutOfRangeException("charUnknownHigh", System.SR.Format(System.SR.ArgumentOutOfRange_Range, 55296, 56319)); } if (!char.IsLowSurrogate(charUnknownLow)) { throw new ArgumentOutOfRangeException("charUnknownLow", System.SR.Format(System.SR.ArgumentOutOfRange_Range, 56320, 57343)); } _cBestFit = '?'; _iCount = (_iSize = 2); return true; } public override char GetNextChar() { _iCount--; if (_iCount < 0) { return '\0'; } if (_iCount == int.MaxValue) { _iCount = -1; return '\0'; } return _cBestFit; } public override bool MovePrevious() { if (_iCount >= 0) { _iCount++; } if (_iCount >= 0) { return _iCount <= _iSize; } return false; } public override void Reset() { _iCount = -1; } private char TryBestFit(char cUnknown) { int num = 0; int num2 = _oFallback.arrayBestFit.Length; int num3; while ((num3 = num2 - num) > 6) { int num4 = (num3 / 2 + num) & 0xFFFE; char c = _oFallback.arrayBestFit[num4]; if (c == cUnknown) { return _oFallback.arrayBestFit[num4 + 1]; } if (c < cUnknown) { num = num4; } else { num2 = num4; } } for (int num4 = num; num4 < num2; num4 += 2) { if (_oFallback.arrayBestFit[num4] == cUnknown) { return _oFallback.arrayBestFit[num4 + 1]; } } return '\0'; } } internal struct EncoderFallbackBufferHelper { internal unsafe char* charStart; internal unsafe char* charEnd; internal System.Text.EncoderNLS encoder; internal bool setEncoder; internal bool bUsedEncoder; internal bool bFallingBack; internal int iRecursionCount; private const int iMaxRecursion = 250; private readonly EncoderFallbackBuffer _fallbackBuffer; public unsafe EncoderFallbackBufferHelper(EncoderFallbackBuffer fallbackBuffer) { _fallbackBuffer = fallbackBuffer; bFallingBack = (bUsedEncoder = (setEncoder = false)); iRecursionCount = 0; charEnd = (charStart = null); encoder = null; } internal unsafe void InternalReset() { charStart = null; bFallingBack = false; iRecursionCount = 0; _fallbackBuffer.Reset(); } internal unsafe void InternalInitialize(char* _charStart, char* _charEnd, System.Text.EncoderNLS _encoder, bool _setEncoder) { charStart = _charStart; charEnd = _charEnd; encoder = _encoder; setEncoder = _setEncoder; bUsedEncoder = false; bFallingBack = false; iRecursionCount = 0; } internal char InternalGetNextChar() { char nextChar = _fallbackBuffer.GetNextChar(); bFallingBack = nextChar != '\0'; if (nextChar == '\0') { iRecursionCount = 0; } return nextChar; } internal unsafe bool InternalFallback(char ch, ref char* chars) { int index = (int)(chars - charStart) - 1; if (char.IsHighSurrogate(ch)) { if (chars >= charEnd) { if (encoder != null && !encoder.MustFlush) { if (setEncoder) { bUsedEncoder = true; encoder.charLeftOver = ch; } bFallingBack = false; return false; } } else { char c = *chars; if (char.IsLowSurrogate(c)) { if (bFallingBack && iRecursionCount++ > 250) { ThrowLastCharRecursive(char.ConvertToUtf32(ch, c)); } chars++; bFallingBack = _fallbackBuffer.Fallback(ch, c, index); return bFallingBack; } } } if (bFallingBack && iRecursionCount++ > 250) { ThrowLastCharRecursive(ch); } bFallingBack = _fallbackBuffer.Fallback(ch, index); return bFallingBack; } internal static void ThrowLastCharRecursive(int charRecursive) { throw new ArgumentException(System.SR.Format(System.SR.Argument_RecursiveFallback, charRecursive), "chars"); } } internal class EncoderNLS : Encoder, ISerializable { internal char charLeftOver; protected EncodingNLS m_encoding; protected bool m_mustFlush; internal bool m_throwOnOverflow; internal int m_charsUsed; internal EncoderFallback m_fallback; internal EncoderFallbackBuffer m_fallbackBuffer; internal new EncoderFallback Fallback => m_fallback; internal bool InternalHasFallbackBuffer => m_fallbackBuffer != null; public new EncoderFallbackBuffer FallbackBuffer { get { if (m_fallbackBuffer == null) { m_fallbackBuffer = ((m_fallback != null) ? m_fallback.CreateFallbackBuffer() : EncoderFallback.ReplacementFallback.CreateFallbackBuffer()); } return m_fallbackBuffer; } } public Encoding Encoding => m_encoding; public bool MustFlush => m_mustFlush; internal virtual bool HasState => charLeftOver != '\0'; internal EncoderNLS(EncodingNLS encoding) { m_encoding = encoding; m_fallback = m_encoding.EncoderFallback; Reset(); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } public override void Reset() { charLeftOver = '\0'; m_fallbackBuffer?.Reset(); } public unsafe override int GetByteCount(char[] chars, int index, int count, bool flush) { if (chars == null) { throw new ArgumentNullException("chars"); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (chars.Length - index < count) { throw new ArgumentOutOfRangeException("chars", System.SR.ArgumentOutOfRange_IndexCountBuffer); } if (chars.Length == 0) { chars = new char[1]; } int num = -1; fixed (char* ptr = &chars[0]) { num = GetByteCount(ptr + index, count, flush); } return num; } public unsafe override int GetByteCount(char* chars, int count, bool flush) { if (chars == null) { throw new ArgumentNullException("chars"); } if (count < 0) { throw new ArgumentOutOfRangeException("count", System.SR.ArgumentOutOfRange_NeedNonNegNum); } m_mustFlush = flush; m_throwOnOverflow = true; return m_encoding.GetByteCount(chars, count, this); } public unsafe override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush) { if (chars == null) { throw new ArgumentNullException("chars"); } if (bytes == null) { throw new ArgumentNullException("bytes"); } if (charIndex < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (chars.Length - charIndex < charCount) { throw new ArgumentOutOfRangeException("chars", System.SR.ArgumentOutOfRange_IndexCountBuffer); } if (byteIndex < 0 || byteIndex > bytes.Length) { throw new ArgumentOutOfRangeException("byteIndex", System.SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); } if (chars.Length == 0) { chars = new char[1]; } int byteCount = bytes.Length - byteIndex; if (bytes.Length == 0) { bytes = new byte[1]; } fixed (char* ptr = &chars[0]) { fixed (byte* ptr2 = &bytes[0]) { return GetBytes(ptr + charIndex, charCount, ptr2 + byteIndex, byteCount, flush); } } } public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush) { if (chars == null) { throw new ArgumentNullException("chars"); } if (bytes == null) { throw new ArgumentNullException("bytes"); } if (byteCount < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((byteCount < 0) ? "byteCount" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } m_mustFlush = flush; m_throwOnOverflow = true; return m_encoding.GetBytes(chars, charCount, bytes, byteCount, this); } public unsafe override void Convert(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { if (chars == null) { throw new ArgumentNullException("chars"); } if (bytes == null) { throw new ArgumentNullException("bytes"); } if (charIndex < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (byteIndex < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException((byteIndex < 0) ? "byteIndex" : "byteCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (chars.Length - charIndex < charCount) { throw new ArgumentOutOfRangeException("chars", System.SR.ArgumentOutOfRange_IndexCountBuffer); } if (bytes.Length - byteIndex < byteCount) { throw new ArgumentOutOfRangeException("bytes", System.SR.ArgumentOutOfRange_IndexCountBuffer); } if (chars.Length == 0) { chars = new char[1]; } if (bytes.Length == 0) { bytes = new byte[1]; } fixed (char* ptr = &chars[0]) { fixed (byte* ptr2 = &bytes[0]) { Convert(ptr + charIndex, charCount, ptr2 + byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out completed); } } } public unsafe override void Convert(char* chars, int charCount, byte* bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { if (chars == null) { throw new ArgumentNullException("chars"); } if (bytes == null) { throw new ArgumentNullException("bytes"); } if (charCount < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException((charCount < 0) ? "charCount" : "byteCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } m_mustFlush = flush; m_throwOnOverflow = false; m_charsUsed = 0; bytesUsed = m_encoding.GetBytes(chars, charCount, bytes, byteCount, this); charsUsed = m_charsUsed; completed = charsUsed == charCount && (!flush || !HasState) && (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0); } internal void ClearMustFlush() { m_mustFlush = false; } } internal sealed class EncodingByteBuffer { private unsafe byte* _bytes; private unsafe readonly byte* _byteStart; private unsafe readonly byte* _byteEnd; private unsafe char* _chars; private unsafe readonly char* _charStart; private unsafe readonly char* _charEnd; private int _byteCountResult; private readonly EncodingNLS _enc; private readonly System.Text.EncoderNLS _encoder; internal EncoderFallbackBuffer fallbackBuffer; internal EncoderFallbackBufferHelper fallbackBufferHelper; internal unsafe bool MoreData { get { if (fallbackBuffer.Remaining <= 0) { return _chars < _charEnd; } return true; } } internal unsafe int CharsUsed => (int)(_chars - _charStart); internal int Count => _byteCountResult; internal unsafe EncodingByteBuffer(EncodingNLS inEncoding, System.Text.EncoderNLS inEncoder, byte* inByteStart, int inByteCount, char* inCharStart, int inCharCount) { _enc = inEncoding; _encoder = inEncoder; _charStart = inCharStart; _chars = inCharStart; _charEnd = inCharStart + inCharCount; _bytes = inByteStart; _byteStart = inByteStart; _byteEnd = inByteStart + inByteCount; if (_encoder == null) { fallbackBuffer = _enc.EncoderFallback.CreateFallbackBuffer(); } else { fallbackBuffer = _encoder.FallbackBuffer; if (_encoder.m_throwOnOverflow && _encoder.InternalHasFallbackBuffer && fallbackBuffer.Remaining > 0) { throw new ArgumentException(System.SR.Format(System.SR.Argument_EncoderFallbackNotEmpty, _encoder.Encoding.EncodingName, _encoder.Fallback.GetType())); } } fallbackBufferHelper = new EncoderFallbackBufferHelper(fallbackBuffer); fallbackBufferHelper.InternalInitialize(_chars, _charEnd, _encoder, _bytes != null); } internal unsafe bool AddByte(byte b, int moreBytesExpected) { if (_bytes != null) { if (_bytes >= _byteEnd - moreBytesExpected) { MovePrevious(bThrow: true); return false; } *(_bytes++) = b; } _byteCountResult++; return true; } internal bool AddByte(byte b1) { return AddByte(b1, 0); } internal bool AddByte(byte b1, byte b2) { return AddByte(b1, b2, 0); } internal bool AddByte(byte b1, byte b2, int moreBytesExpected) { if (AddByte(b1, 1 + moreBytesExpected)) { return AddByte(b2, moreBytesExpected); } return false; } internal bool AddByte(byte b1, byte b2, byte b3) { return AddByte(b1, b2, b3, 0); } internal bool AddByte(byte b1, byte b2, byte b3, int moreBytesExpected) { if (AddByte(b1, 2 + moreBytesExpected) && AddByte(b2, 1 + moreBytesExpected)) { return AddByte(b3, moreBytesExpected); } return false; } internal bool AddByte(byte b1, byte b2, byte b3, byte b4) { if (AddByte(b1, 3) && AddByte(b2, 2) && AddByte(b3, 1)) { return AddByte(b4, 0); } return false; } internal unsafe void MovePrevious(bool bThrow) { if (fallbackBufferHelper.bFallingBack) { fallbackBuffer.MovePrevious(); } else if (_chars > _charStart) { _chars--; } if (bThrow) { _enc.ThrowBytesOverflow(_encoder, _bytes == _byteStart); } } internal unsafe bool Fallback(char charFallback) { return fallbackBufferHelper.InternalFallback(charFallback, ref _chars); } internal unsafe char GetNextChar() { char c = fallbackBufferHelper.InternalGetNextChar(); if (c == '\0' && _chars < _charEnd) { c = *(_chars++); } return c; } } internal sealed class EncodingCharBuffer { private unsafe char* _chars; private unsafe readonly char* _charStart; private unsafe readonly char* _charEnd; private int _charCountResult; private readonly EncodingNLS _enc; private readonly System.Text.DecoderNLS _decoder; private unsafe readonly byte* _byteStart; private unsafe readonly byte* _byteEnd; private unsafe byte* _bytes; private readonly DecoderFallbackBuffer _fallbackBuffer; private DecoderFallbackBufferHelper _fallbackBufferHelper; internal unsafe bool MoreData => _bytes < _byteEnd; internal unsafe int BytesUsed => (int)(_bytes - _byteStart); internal int Count => _charCountResult; internal unsafe EncodingCharBuffer(EncodingNLS enc, System.Text.DecoderNLS decoder, char* charStart, int charCount, byte* byteStart, int byteCount) { _enc = enc; _decoder = decoder; _chars = charStart; _charStart = charStart; _charEnd = charStart + charCount; _byteStart = byteStart; _bytes = byteStart; _byteEnd = byteStart + byteCount; if (_decoder == null) { _fallbackBuffer = enc.DecoderFallback.CreateFallbackBuffer(); } else { _fallbackBuffer = _decoder.FallbackBuffer; } _fallbackBufferHelper = new DecoderFallbackBufferHelper(_fallbackBuffer); _fallbackBufferHelper.InternalInitialize(_bytes, _charEnd); } internal unsafe bool AddChar(char ch, int numBytes) { if (_chars != null) { if (_chars >= _charEnd) { _bytes -= numBytes; _enc.ThrowCharsOverflow(_decoder, _bytes <= _byteStart); return false; } *(_chars++) = ch; } _charCountResult++; return true; } internal bool AddChar(char ch) { return AddChar(ch, 1); } internal unsafe bool AddChar(char ch1, char ch2, int numBytes) { if (_chars >= _charEnd - 1) { _bytes -= numBytes; _enc.ThrowCharsOverflow(_decoder, _bytes <= _byteStart); return false; } if (AddChar(ch1, numBytes)) { return AddChar(ch2, numBytes); } return false; } internal unsafe void AdjustBytes(int count) { _bytes += count; } internal unsafe bool EvenMoreData(int count) { return _bytes <= _byteEnd - count; } internal unsafe byte GetNextByte() { if (_bytes >= _byteEnd) { return 0; } return *(_bytes++); } internal bool Fallback(byte fallbackByte) { byte[] byteBuffer = new byte[1] { fallbackByte }; return Fallback(byteBuffer); } internal bool Fallback(byte byte1, byte byte2) { byte[] byteBuffer = new byte[2] { byte1, byte2 }; return Fallback(byteBuffer); } internal bool Fallback(byte byte1, byte byte2, byte byte3, byte byte4) { byte[] byteBuffer = new byte[4] { byte1, byte2, byte3, byte4 }; return Fallback(byteBuffer); } internal unsafe bool Fallback(byte[] byteBuffer) { if (_chars != null) { char* chars = _chars; if (!_fallbackBufferHelper.InternalFallback(byteBuffer, _bytes, ref _chars)) { _bytes -= byteBuffer.Length; _fallbackBufferHelper.InternalReset(); _enc.ThrowCharsOverflow(_decoder, _chars == _charStart); return false; } _charCountResult += (int)(_chars - chars); } else { _charCountResult += _fallbackBufferHelper.InternalFallback(byteBuffer, _bytes); } return true; } } internal abstract class EncodingNLS : Encoding { private string _encodingName; private string _webName; public override string EncodingName { get { if (_encodingName == null) { _encodingName = GetLocalizedEncodingNameResource(CodePage); if (_encodingName == null) { throw new NotSupportedException(System.SR.Format(System.SR.MissingEncodingNameResource, WebName, CodePage)); } if (_encodingName.StartsWith("Globalization_cp_", StringComparison.OrdinalIgnoreCase)) { _encodingName = System.Text.EncodingTable.GetEnglishNameFromCodePage(CodePage); if (_encodingName == null) { throw new NotSupportedException(System.SR.Format(System.SR.MissingEncodingNameResource, WebName, CodePage)); } } } return _encodingName; } } public override string WebName { get { if (_webName == null) { _webName = System.Text.EncodingTable.GetWebNameFromCodePage(CodePage); if (_webName == null) { throw new NotSupportedException(System.SR.Format(System.SR.NotSupported_NoCodepageData, CodePage)); } } return _webName; } } public override string HeaderName => CodePage switch { 932 => "iso-2022-jp", 50221 => "iso-2022-jp", 50225 => "euc-kr", _ => WebName, }; public override string BodyName => CodePage switch { 932 => "iso-2022-jp", 1250 => "iso-8859-2", 1251 => "koi8-r", 1252 => "iso-8859-1", 1253 => "iso-8859-7", 1254 => "iso-8859-9", 50221 => "iso-2022-jp", 50225 => "iso-2022-kr", _ => WebName, }; protected EncodingNLS(int codePage) : base(codePage) { } protected EncodingNLS(int codePage, EncoderFallback enc, DecoderFallback dec) : base(codePage, enc, dec) { } public unsafe abstract int GetByteCount(char* chars, int count, System.Text.EncoderNLS encoder); public unsafe abstract int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, System.Text.EncoderNLS encoder); public unsafe abstract int GetCharCount(byte* bytes, int count, System.Text.DecoderNLS decoder); public unsafe abstract int GetChars(byte* bytes, int byteCount, char* chars, int charCount, System.Text.DecoderNLS decoder); public unsafe override int GetByteCount(char[] chars, int index, int count) { if (chars == null) { throw new ArgumentNullException("chars"); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (chars.Length - index < count) { throw new ArgumentOutOfRangeException("chars", System.SR.ArgumentOutOfRange_IndexCountBuffer); } if (chars.Length == 0) { return 0; } fixed (char* ptr = &chars[0]) { return GetByteCount(ptr + index, count, null); } } public unsafe override int GetByteCount(string s) { if (s == null) { throw new ArgumentNullException("s"); } fixed (char* chars = s) { return GetByteCount(chars, s.Length, null); } } public unsafe override int GetByteCount(char* chars, int count) { if (chars == null) { throw new ArgumentNullException("chars"); } if (count < 0) { throw new ArgumentOutOfRangeException("count", System.SR.ArgumentOutOfRange_NeedNonNegNum); } return GetByteCount(chars, count, null); } public unsafe override int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (s == null) { throw new ArgumentNullException("s"); } if (bytes == null) { throw new ArgumentNullException("bytes"); } if (charIndex < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (s.Length - charIndex < charCount) { throw new ArgumentOutOfRangeException("s", System.SR.ArgumentOutOfRange_IndexCount); } if (byteIndex < 0 || byteIndex > bytes.Length) { throw new ArgumentOutOfRangeException("byteIndex", System.SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); } int byteCount = bytes.Length - byteIndex; if (bytes.Length == 0) { bytes = new byte[1]; } fixed (char* ptr = s) { fixed (byte* ptr2 = &bytes[0]) { return GetBytes(ptr + charIndex, charCount, ptr2 + byteIndex, byteCount, null); } } } public unsafe override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (chars == null) { throw new ArgumentNullException("chars"); } if (bytes == null) { throw new ArgumentNullException("bytes"); } if (charIndex < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (chars.Length - charIndex < charCount) { throw new ArgumentOutOfRangeException("chars", System.SR.ArgumentOutOfRange_IndexCountBuffer); } if (byteIndex < 0 || byteIndex > bytes.Length) { throw new ArgumentOutOfRangeException("byteIndex", System.SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); } if (chars.Length == 0) { return 0; } int byteCount = bytes.Length - byteIndex; if (bytes.Length == 0) { bytes = new byte[1]; } fixed (char* ptr = &chars[0]) { fixed (byte* ptr2
System.Threading.dll
Decompiled 5 days agousing System; using System.Diagnostics; using System.Diagnostics.Tracing; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; using System.Threading; using FxResources.System.Threading; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyTitle("System.Threading")] [assembly: AssemblyDescription("System.Threading")] [assembly: AssemblyDefaultAlias("System.Threading")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyProduct("Microsoft® .NET Framework")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyFileVersion("4.6.24705.01")] [assembly: AssemblyInformationalVersion("4.6.24705.01. Commit Hash: 4d1af962ca0fede10beb01d197367c2f90e92c97")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.0.12.0")] [assembly: TypeForwardedTo(typeof(AbandonedMutexException))] [assembly: TypeForwardedTo(typeof(AsyncLocal<>))] [assembly: TypeForwardedTo(typeof(AsyncLocalValueChangedArgs<>))] [assembly: TypeForwardedTo(typeof(AutoResetEvent))] [assembly: TypeForwardedTo(typeof(ContextCallback))] [assembly: TypeForwardedTo(typeof(EventResetMode))] [assembly: TypeForwardedTo(typeof(EventWaitHandle))] [assembly: TypeForwardedTo(typeof(ExecutionContext))] [assembly: TypeForwardedTo(typeof(Interlocked))] [assembly: TypeForwardedTo(typeof(LazyInitializer))] [assembly: TypeForwardedTo(typeof(LockRecursionException))] [assembly: TypeForwardedTo(typeof(ManualResetEvent))] [assembly: TypeForwardedTo(typeof(ManualResetEventSlim))] [assembly: TypeForwardedTo(typeof(Monitor))] [assembly: TypeForwardedTo(typeof(Mutex))] [assembly: TypeForwardedTo(typeof(Semaphore))] [assembly: TypeForwardedTo(typeof(SemaphoreFullException))] [assembly: TypeForwardedTo(typeof(SemaphoreSlim))] [assembly: TypeForwardedTo(typeof(SendOrPostCallback))] [assembly: TypeForwardedTo(typeof(SpinLock))] [assembly: TypeForwardedTo(typeof(SpinWait))] [assembly: TypeForwardedTo(typeof(SynchronizationContext))] [assembly: TypeForwardedTo(typeof(SynchronizationLockException))] [assembly: TypeForwardedTo(typeof(ThreadLocal<>))] [assembly: TypeForwardedTo(typeof(Volatile))] [assembly: TypeForwardedTo(typeof(WaitHandleCannotBeOpenedException))] [module: UnverifiableCode] namespace FxResources.System.Threading { internal static class SR { } } namespace System { internal static class SR { private static ResourceManager s_resourceManager; private const string s_resourcesName = "FxResources.System.Threading.SR"; private static ResourceManager ResourceManager { get { if (s_resourceManager == null) { s_resourceManager = new ResourceManager(ResourceType); } return s_resourceManager; } } internal static string CountdownEvent_Increment_AlreadyZero => GetResourceString("CountdownEvent_Increment_AlreadyZero", null); internal static string CountdownEvent_Increment_AlreadyMax => GetResourceString("CountdownEvent_Increment_AlreadyMax", null); internal static string CountdownEvent_Decrement_BelowZero => GetResourceString("CountdownEvent_Decrement_BelowZero", null); internal static string Common_OperationCanceled => GetResourceString("Common_OperationCanceled", null); internal static string Barrier_Dispose => GetResourceString("Barrier_Dispose", null); internal static string Barrier_SignalAndWait_InvalidOperation_ZeroTotal => GetResourceString("Barrier_SignalAndWait_InvalidOperation_ZeroTotal", null); internal static string Barrier_SignalAndWait_ArgumentOutOfRange => GetResourceString("Barrier_SignalAndWait_ArgumentOutOfRange", null); internal static string Barrier_RemoveParticipants_InvalidOperation => GetResourceString("Barrier_RemoveParticipants_InvalidOperation", null); internal static string Barrier_RemoveParticipants_ArgumentOutOfRange => GetResourceString("Barrier_RemoveParticipants_ArgumentOutOfRange", null); internal static string Barrier_RemoveParticipants_NonPositive_ArgumentOutOfRange => GetResourceString("Barrier_RemoveParticipants_NonPositive_ArgumentOutOfRange", null); internal static string Barrier_InvalidOperation_CalledFromPHA => GetResourceString("Barrier_InvalidOperation_CalledFromPHA", null); internal static string Barrier_AddParticipants_NonPositive_ArgumentOutOfRange => GetResourceString("Barrier_AddParticipants_NonPositive_ArgumentOutOfRange", null); internal static string Barrier_SignalAndWait_InvalidOperation_ThreadsExceeded => GetResourceString("Barrier_SignalAndWait_InvalidOperation_ThreadsExceeded", null); internal static string BarrierPostPhaseException => GetResourceString("BarrierPostPhaseException", null); internal static string Barrier_ctor_ArgumentOutOfRange => GetResourceString("Barrier_ctor_ArgumentOutOfRange", null); internal static string Barrier_AddParticipants_Overflow_ArgumentOutOfRange => GetResourceString("Barrier_AddParticipants_Overflow_ArgumentOutOfRange", null); internal static string SynchronizationLockException_IncorrectDispose => GetResourceString("SynchronizationLockException_IncorrectDispose", null); internal static string SynchronizationLockException_MisMatchedWrite => GetResourceString("SynchronizationLockException_MisMatchedWrite", null); internal static string LockRecursionException_UpgradeAfterReadNotAllowed => GetResourceString("LockRecursionException_UpgradeAfterReadNotAllowed", null); internal static string LockRecursionException_UpgradeAfterWriteNotAllowed => GetResourceString("LockRecursionException_UpgradeAfterWriteNotAllowed", null); internal static string SynchronizationLockException_MisMatchedUpgrade => GetResourceString("SynchronizationLockException_MisMatchedUpgrade", null); internal static string SynchronizationLockException_MisMatchedRead => GetResourceString("SynchronizationLockException_MisMatchedRead", null); internal static string LockRecursionException_WriteAfterReadNotAllowed => GetResourceString("LockRecursionException_WriteAfterReadNotAllowed", null); internal static string LockRecursionException_RecursiveWriteNotAllowed => GetResourceString("LockRecursionException_RecursiveWriteNotAllowed", null); internal static string LockRecursionException_ReadAfterWriteNotAllowed => GetResourceString("LockRecursionException_ReadAfterWriteNotAllowed", null); internal static string LockRecursionException_RecursiveUpgradeNotAllowed => GetResourceString("LockRecursionException_RecursiveUpgradeNotAllowed", null); internal static string LockRecursionException_RecursiveReadNotAllowed => GetResourceString("LockRecursionException_RecursiveReadNotAllowed", null); internal static Type ResourceType => typeof(FxResources.System.Threading.SR); [MethodImpl(MethodImplOptions.NoInlining)] private static bool UsingResourceKeys() { return false; } internal static string GetResourceString(string resourceKey, string defaultString) { string text = null; try { text = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } if (defaultString != null && resourceKey.Equals(text, StringComparison.Ordinal)) { return defaultString; } return text; } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } } } namespace System.Threading { internal static class Helpers { internal static void Sleep(int milliseconds) { Thread.Sleep(milliseconds); } internal static void Spin(int iterations) { Thread.SpinWait(iterations); } } public class BarrierPostPhaseException : Exception { public BarrierPostPhaseException() : this((string)null) { } public BarrierPostPhaseException(Exception innerException) : this(null, innerException) { } public BarrierPostPhaseException(string message) : this(message, null) { } public BarrierPostPhaseException(string message, Exception innerException) : base((message == null) ? System.SR.BarrierPostPhaseException : message, innerException) { } } [DebuggerDisplay("Participant Count={ParticipantCount},Participants Remaining={ParticipantsRemaining}")] public class Barrier : IDisposable { private volatile int _currentTotalCount; private const int CURRENT_MASK = 2147418112; private const int TOTAL_MASK = 32767; private const int SENSE_MASK = int.MinValue; private const int MAX_PARTICIPANTS = 32767; private long _currentPhase; private bool _disposed; private ManualResetEventSlim _oddEvent; private ManualResetEventSlim _evenEvent; private ExecutionContext _ownerThreadContext; [SecurityCritical] private static ContextCallback s_invokePostPhaseAction; private Action<Barrier> _postPhaseAction; private Exception _exception; private int _actionCallerID; public int ParticipantsRemaining { get { int currentTotalCount = _currentTotalCount; int num = currentTotalCount & 0x7FFF; int num2 = (currentTotalCount & 0x7FFF0000) >> 16; return num - num2; } } public int ParticipantCount => _currentTotalCount & 0x7FFF; public long CurrentPhaseNumber { get { return Volatile.Read(ref _currentPhase); } internal set { Volatile.Write(ref _currentPhase, value); } } public Barrier(int participantCount) : this(participantCount, null) { } public Barrier(int participantCount, Action<Barrier> postPhaseAction) { if (participantCount < 0 || participantCount > 32767) { throw new ArgumentOutOfRangeException("participantCount", participantCount, System.SR.Barrier_ctor_ArgumentOutOfRange); } _currentTotalCount = participantCount; _postPhaseAction = postPhaseAction; _oddEvent = new ManualResetEventSlim(initialState: true); _evenEvent = new ManualResetEventSlim(initialState: false); if (postPhaseAction != null) { _ownerThreadContext = ExecutionContext.Capture(); } _actionCallerID = 0; } private void GetCurrentTotal(int currentTotal, out int current, out int total, out bool sense) { total = currentTotal & 0x7FFF; current = (currentTotal & 0x7FFF0000) >> 16; sense = (((currentTotal & int.MinValue) == 0) ? true : false); } private bool SetCurrentTotal(int currentTotal, int current, int total, bool sense) { int num = (current << 16) | total; if (!sense) { num |= int.MinValue; } return Interlocked.CompareExchange(ref _currentTotalCount, num, currentTotal) == currentTotal; } public long AddParticipant() { try { return AddParticipants(1); } catch (ArgumentOutOfRangeException) { throw new InvalidOperationException(System.SR.Barrier_AddParticipants_Overflow_ArgumentOutOfRange); } } public long AddParticipants(int participantCount) { ThrowIfDisposed(); if (participantCount < 1) { throw new ArgumentOutOfRangeException("participantCount", participantCount, System.SR.Barrier_AddParticipants_NonPositive_ArgumentOutOfRange); } if (participantCount > 32767) { throw new ArgumentOutOfRangeException("participantCount", System.SR.Barrier_AddParticipants_Overflow_ArgumentOutOfRange); } if (_actionCallerID != 0 && Environment.CurrentManagedThreadId == _actionCallerID) { throw new InvalidOperationException(System.SR.Barrier_InvalidOperation_CalledFromPHA); } SpinWait spinWait = default(SpinWait); long num = 0L; bool sense; while (true) { int currentTotalCount = _currentTotalCount; GetCurrentTotal(currentTotalCount, out var current, out var total, out sense); if (participantCount + total > 32767) { throw new ArgumentOutOfRangeException("participantCount", System.SR.Barrier_AddParticipants_Overflow_ArgumentOutOfRange); } if (SetCurrentTotal(currentTotalCount, current, total + participantCount, sense)) { break; } spinWait.SpinOnce(); } long currentPhaseNumber = CurrentPhaseNumber; num = ((sense != (currentPhaseNumber % 2 == 0)) ? (currentPhaseNumber + 1) : currentPhaseNumber); if (num != currentPhaseNumber) { if (sense) { _oddEvent.Wait(); } else { _evenEvent.Wait(); } } else if (sense && _evenEvent.IsSet) { _evenEvent.Reset(); } else if (!sense && _oddEvent.IsSet) { _oddEvent.Reset(); } return num; } public void RemoveParticipant() { RemoveParticipants(1); } public void RemoveParticipants(int participantCount) { ThrowIfDisposed(); if (participantCount < 1) { throw new ArgumentOutOfRangeException("participantCount", participantCount, System.SR.Barrier_RemoveParticipants_NonPositive_ArgumentOutOfRange); } if (_actionCallerID != 0 && Environment.CurrentManagedThreadId == _actionCallerID) { throw new InvalidOperationException(System.SR.Barrier_InvalidOperation_CalledFromPHA); } SpinWait spinWait = default(SpinWait); while (true) { int currentTotalCount = _currentTotalCount; GetCurrentTotal(currentTotalCount, out var current, out var total, out var sense); if (total < participantCount) { throw new ArgumentOutOfRangeException("participantCount", System.SR.Barrier_RemoveParticipants_ArgumentOutOfRange); } if (total - participantCount < current) { throw new InvalidOperationException(System.SR.Barrier_RemoveParticipants_InvalidOperation); } int num = total - participantCount; if (num > 0 && current == num) { if (SetCurrentTotal(currentTotalCount, 0, total - participantCount, !sense)) { FinishPhase(sense); break; } } else if (SetCurrentTotal(currentTotalCount, current, total - participantCount, sense)) { break; } spinWait.SpinOnce(); } } public void SignalAndWait() { SignalAndWait(default(CancellationToken)); } public void SignalAndWait(CancellationToken cancellationToken) { SignalAndWait(-1, cancellationToken); } public bool SignalAndWait(TimeSpan timeout) { return SignalAndWait(timeout, default(CancellationToken)); } public bool SignalAndWait(TimeSpan timeout, CancellationToken cancellationToken) { long num = (long)timeout.TotalMilliseconds; if (num < -1 || num > int.MaxValue) { throw new ArgumentOutOfRangeException("timeout", timeout, System.SR.Barrier_SignalAndWait_ArgumentOutOfRange); } return SignalAndWait((int)timeout.TotalMilliseconds, cancellationToken); } public bool SignalAndWait(int millisecondsTimeout) { return SignalAndWait(millisecondsTimeout, default(CancellationToken)); } public bool SignalAndWait(int millisecondsTimeout, CancellationToken cancellationToken) { ThrowIfDisposed(); cancellationToken.ThrowIfCancellationRequested(); if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException("millisecondsTimeout", millisecondsTimeout, System.SR.Barrier_SignalAndWait_ArgumentOutOfRange); } if (_actionCallerID != 0 && Environment.CurrentManagedThreadId == _actionCallerID) { throw new InvalidOperationException(System.SR.Barrier_InvalidOperation_CalledFromPHA); } SpinWait spinWait = default(SpinWait); int current; int total; bool sense; long currentPhaseNumber; while (true) { int currentTotalCount = _currentTotalCount; GetCurrentTotal(currentTotalCount, out current, out total, out sense); currentPhaseNumber = CurrentPhaseNumber; if (total == 0) { throw new InvalidOperationException(System.SR.Barrier_SignalAndWait_InvalidOperation_ZeroTotal); } if (current == 0 && sense != (CurrentPhaseNumber % 2 == 0)) { throw new InvalidOperationException(System.SR.Barrier_SignalAndWait_InvalidOperation_ThreadsExceeded); } if (current + 1 == total) { if (SetCurrentTotal(currentTotalCount, 0, total, !sense)) { if (System.Threading.CdsSyncEtwBCLProvider.Log.IsEnabled()) { System.Threading.CdsSyncEtwBCLProvider.Log.Barrier_PhaseFinished(sense, CurrentPhaseNumber); } FinishPhase(sense); return true; } } else if (SetCurrentTotal(currentTotalCount, current + 1, total, sense)) { break; } spinWait.SpinOnce(); } ManualResetEventSlim currentPhaseEvent = (sense ? _evenEvent : _oddEvent); bool flag = false; bool flag2 = false; try { flag2 = DiscontinuousWait(currentPhaseEvent, millisecondsTimeout, cancellationToken, currentPhaseNumber); } catch (OperationCanceledException) { flag = true; } catch (ObjectDisposedException) { if (currentPhaseNumber >= CurrentPhaseNumber) { throw; } flag2 = true; } if (!flag2) { spinWait.Reset(); while (true) { int currentTotalCount = _currentTotalCount; GetCurrentTotal(currentTotalCount, out current, out total, out var sense2); if (currentPhaseNumber < CurrentPhaseNumber || sense != sense2) { break; } if (SetCurrentTotal(currentTotalCount, current - 1, total, sense)) { if (flag) { throw new OperationCanceledException(System.SR.Common_OperationCanceled, cancellationToken); } return false; } spinWait.SpinOnce(); } WaitCurrentPhase(currentPhaseEvent, currentPhaseNumber); } if (_exception != null) { throw new BarrierPostPhaseException(_exception); } return true; } [SecuritySafeCritical] private void FinishPhase(bool observedSense) { if (_postPhaseAction != null) { try { _actionCallerID = Environment.CurrentManagedThreadId; if (_ownerThreadContext != null) { ExecutionContext ownerThreadContext = _ownerThreadContext; ContextCallback callback = InvokePostPhaseAction; ExecutionContext.Run(_ownerThreadContext, callback, this); } else { _postPhaseAction(this); } _exception = null; return; } catch (Exception exception) { _exception = exception; return; } finally { _actionCallerID = 0; SetResetEvents(observedSense); if (_exception != null) { throw new BarrierPostPhaseException(_exception); } } } SetResetEvents(observedSense); } [SecurityCritical] private static void InvokePostPhaseAction(object obj) { Barrier barrier = (Barrier)obj; barrier._postPhaseAction(barrier); } private void SetResetEvents(bool observedSense) { CurrentPhaseNumber++; if (observedSense) { _oddEvent.Reset(); _evenEvent.Set(); } else { _evenEvent.Reset(); _oddEvent.Set(); } } private void WaitCurrentPhase(ManualResetEventSlim currentPhaseEvent, long observedPhase) { SpinWait spinWait = default(SpinWait); while (!currentPhaseEvent.IsSet && CurrentPhaseNumber - observedPhase <= 1) { spinWait.SpinOnce(); } } private bool DiscontinuousWait(ManualResetEventSlim currentPhaseEvent, int totalTimeout, CancellationToken token, long observedPhase) { int num = 100; int num2 = 10000; while (observedPhase == CurrentPhaseNumber) { int num3 = ((totalTimeout == -1) ? num : Math.Min(num, totalTimeout)); if (currentPhaseEvent.Wait(num3, token)) { return true; } if (totalTimeout != -1) { totalTimeout -= num3; if (totalTimeout <= 0) { return false; } } num = ((num >= num2) ? num2 : Math.Min(num << 1, num2)); } WaitCurrentPhase(currentPhaseEvent, observedPhase); return true; } public void Dispose() { if (_actionCallerID != 0 && Environment.CurrentManagedThreadId == _actionCallerID) { throw new InvalidOperationException(System.SR.Barrier_InvalidOperation_CalledFromPHA); } Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { _oddEvent.Dispose(); _evenEvent.Dispose(); } _disposed = true; } } private void ThrowIfDisposed() { if (_disposed) { throw new ObjectDisposedException("Barrier", System.SR.Barrier_Dispose); } } } [EventSource(Name = "System.Threading.SynchronizationEventSource", Guid = "EC631D38-466B-4290-9306-834971BA0217")] internal sealed class CdsSyncEtwBCLProvider : EventSource { public static System.Threading.CdsSyncEtwBCLProvider Log = new System.Threading.CdsSyncEtwBCLProvider(); private const EventKeywords ALL_KEYWORDS = EventKeywords.All; private const int SPINLOCK_FASTPATHFAILED_ID = 1; private const int SPINWAIT_NEXTSPINWILLYIELD_ID = 2; private const int BARRIER_PHASEFINISHED_ID = 3; private CdsSyncEtwBCLProvider() { } [Event(1, Level = EventLevel.Warning)] public void SpinLock_FastPathFailed(int ownerID) { if (IsEnabled(EventLevel.Warning, EventKeywords.All)) { WriteEvent(1, ownerID); } } [Event(2, Level = EventLevel.Informational)] public void SpinWait_NextSpinWillYield() { if (IsEnabled(EventLevel.Informational, EventKeywords.All)) { WriteEvent(2); } } [SecuritySafeCritical] [Event(3, Level = EventLevel.Verbose, Version = 1)] public unsafe void Barrier_PhaseFinished(bool currentSense, long phaseNum) { if (IsEnabled(EventLevel.Verbose, EventKeywords.All)) { EventData* ptr = stackalloc EventData[2]; int num = (currentSense ? 1 : 0); ptr->Size = 4; ptr->DataPointer = (IntPtr)(&num); ptr[1].Size = 8; ptr[1].DataPointer = (IntPtr)(&phaseNum); WriteEventCore(3, 2, ptr); } } } [DebuggerDisplay("Initial Count={InitialCount}, Current Count={CurrentCount}")] public class CountdownEvent : IDisposable { private int _initialCount; private volatile int _currentCount; private ManualResetEventSlim _event; private volatile bool _disposed; public int CurrentCount { get { int currentCount = _currentCount; if (currentCount >= 0) { return currentCount; } return 0; } } public int InitialCount => _initialCount; public bool IsSet => _currentCount <= 0; public WaitHandle WaitHandle { get { ThrowIfDisposed(); return _event.WaitHandle; } } public CountdownEvent(int initialCount) { if (initialCount < 0) { throw new ArgumentOutOfRangeException("initialCount"); } _initialCount = initialCount; _currentCount = initialCount; _event = new ManualResetEventSlim(); if (initialCount == 0) { _event.Set(); } } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { _event.Dispose(); _disposed = true; } } public bool Signal() { ThrowIfDisposed(); if (_currentCount <= 0) { throw new InvalidOperationException(System.SR.CountdownEvent_Decrement_BelowZero); } int num = Interlocked.Decrement(ref _currentCount); if (num == 0) { _event.Set(); return true; } if (num < 0) { throw new InvalidOperationException(System.SR.CountdownEvent_Decrement_BelowZero); } return false; } public bool Signal(int signalCount) { if (signalCount <= 0) { throw new ArgumentOutOfRangeException("signalCount"); } ThrowIfDisposed(); SpinWait spinWait = default(SpinWait); int currentCount; while (true) { currentCount = _currentCount; if (currentCount < signalCount) { throw new InvalidOperationException(System.SR.CountdownEvent_Decrement_BelowZero); } if (Interlocked.CompareExchange(ref _currentCount, currentCount - signalCount, currentCount) == currentCount) { break; } spinWait.SpinOnce(); } if (currentCount == signalCount) { _event.Set(); return true; } return false; } public void AddCount() { AddCount(1); } public bool TryAddCount() { return TryAddCount(1); } public void AddCount(int signalCount) { if (!TryAddCount(signalCount)) { throw new InvalidOperationException(System.SR.CountdownEvent_Increment_AlreadyZero); } } public bool TryAddCount(int signalCount) { if (signalCount <= 0) { throw new ArgumentOutOfRangeException("signalCount"); } ThrowIfDisposed(); SpinWait spinWait = default(SpinWait); while (true) { int currentCount = _currentCount; if (currentCount <= 0) { return false; } if (currentCount > int.MaxValue - signalCount) { throw new InvalidOperationException(System.SR.CountdownEvent_Increment_AlreadyMax); } if (Interlocked.CompareExchange(ref _currentCount, currentCount + signalCount, currentCount) == currentCount) { break; } spinWait.SpinOnce(); } return true; } public void Reset() { Reset(_initialCount); } public void Reset(int count) { ThrowIfDisposed(); if (count < 0) { throw new ArgumentOutOfRangeException("count"); } _currentCount = count; _initialCount = count; if (count == 0) { _event.Set(); } else { _event.Reset(); } } public void Wait() { Wait(-1, default(CancellationToken)); } public void Wait(CancellationToken cancellationToken) { Wait(-1, cancellationToken); } public bool Wait(TimeSpan timeout) { long num = (long)timeout.TotalMilliseconds; if (num < -1 || num > int.MaxValue) { throw new ArgumentOutOfRangeException("timeout"); } return Wait((int)num, default(CancellationToken)); } public bool Wait(TimeSpan timeout, CancellationToken cancellationToken) { long num = (long)timeout.TotalMilliseconds; if (num < -1 || num > int.MaxValue) { throw new ArgumentOutOfRangeException("timeout"); } return Wait((int)num, cancellationToken); } public bool Wait(int millisecondsTimeout) { return Wait(millisecondsTimeout, default(CancellationToken)); } public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken) { if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException("millisecondsTimeout"); } ThrowIfDisposed(); cancellationToken.ThrowIfCancellationRequested(); bool flag = IsSet; if (!flag) { flag = _event.Wait(millisecondsTimeout, cancellationToken); } return flag; } private void ThrowIfDisposed() { if (_disposed) { throw new ObjectDisposedException("CountdownEvent"); } } } public enum LockRecursionPolicy { NoRecursion, SupportsRecursion } internal class ReaderWriterCount { public long lockID; public int readercount; public int writercount; public int upgradecount; public System.Threading.ReaderWriterCount next; } public class ReaderWriterLockSlim : IDisposable { private struct TimeoutTracker { private int _total; private int _start; public int RemainingMilliseconds { get { if (_total == -1 || _total == 0) { return _total; } int num = Environment.TickCount - _start; if (num < 0 || num >= _total) { return 0; } return _total - num; } } public bool IsExpired => RemainingMilliseconds == 0; public TimeoutTracker(TimeSpan timeout) { long num = (long)timeout.TotalMilliseconds; if (num < -1 || num > int.MaxValue) { throw new ArgumentOutOfRangeException("timeout"); } _total = (int)num; if (_total != -1 && _total != 0) { _start = Environment.TickCount; } else { _start = 0; } } public TimeoutTracker(int millisecondsTimeout) { if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException("millisecondsTimeout"); } _total = millisecondsTimeout; if (_total != -1 && _total != 0) { _start = Environment.TickCount; } else { _start = 0; } } } private bool _fIsReentrant; private int _myLock; private const int LockSpinCycles = 20; private const int LockSpinCount = 10; private const int LockSleep0Count = 5; private uint _numWriteWaiters; private uint _numReadWaiters; private uint _numWriteUpgradeWaiters; private uint _numUpgradeWaiters; private bool _fNoWaiters; private int _upgradeLockOwnerId; private int _writeLockOwnerId; private EventWaitHandle _writeEvent; private EventWaitHandle _readEvent; private EventWaitHandle _upgradeEvent; private EventWaitHandle _waitUpgradeEvent; private static long s_nextLockID; private long _lockID; [ThreadStatic] private static System.Threading.ReaderWriterCount t_rwc; private bool _fUpgradeThreadHoldingRead; private const int MaxSpinCount = 20; private uint _owners; private const uint WRITER_HELD = 2147483648u; private const uint WAITING_WRITERS = 1073741824u; private const uint WAITING_UPGRADER = 536870912u; private const uint MAX_READER = 268435454u; private const uint READER_MASK = 268435455u; private bool _fDisposed; public bool IsReadLockHeld { get { if (RecursiveReadCount > 0) { return true; } return false; } } public bool IsUpgradeableReadLockHeld { get { if (RecursiveUpgradeCount > 0) { return true; } return false; } } public bool IsWriteLockHeld { get { if (RecursiveWriteCount > 0) { return true; } return false; } } public LockRecursionPolicy RecursionPolicy { get { if (_fIsReentrant) { return LockRecursionPolicy.SupportsRecursion; } return LockRecursionPolicy.NoRecursion; } } public int CurrentReadCount { get { int numReaders = (int)GetNumReaders(); if (_upgradeLockOwnerId != -1) { return numReaders - 1; } return numReaders; } } public int RecursiveReadCount { get { int result = 0; System.Threading.ReaderWriterCount threadRWCount = GetThreadRWCount(dontAllocate: true); if (threadRWCount != null) { result = threadRWCount.readercount; } return result; } } public int RecursiveUpgradeCount { get { if (_fIsReentrant) { int result = 0; System.Threading.ReaderWriterCount threadRWCount = GetThreadRWCount(dontAllocate: true); if (threadRWCount != null) { result = threadRWCount.upgradecount; } return result; } if (Environment.CurrentManagedThreadId == _upgradeLockOwnerId) { return 1; } return 0; } } public int RecursiveWriteCount { get { if (_fIsReentrant) { int result = 0; System.Threading.ReaderWriterCount threadRWCount = GetThreadRWCount(dontAllocate: true); if (threadRWCount != null) { result = threadRWCount.writercount; } return result; } if (Environment.CurrentManagedThreadId == _writeLockOwnerId) { return 1; } return 0; } } public int WaitingReadCount => (int)_numReadWaiters; public int WaitingUpgradeCount => (int)_numUpgradeWaiters; public int WaitingWriteCount => (int)_numWriteWaiters; private void InitializeThreadCounts() { _upgradeLockOwnerId = -1; _writeLockOwnerId = -1; } public ReaderWriterLockSlim() : this(LockRecursionPolicy.NoRecursion) { } public ReaderWriterLockSlim(LockRecursionPolicy recursionPolicy) { if (recursionPolicy == LockRecursionPolicy.SupportsRecursion) { _fIsReentrant = true; } InitializeThreadCounts(); _fNoWaiters = true; _lockID = Interlocked.Increment(ref s_nextLockID); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsRWEntryEmpty(System.Threading.ReaderWriterCount rwc) { if (rwc.lockID == 0L) { return true; } if (rwc.readercount == 0 && rwc.writercount == 0 && rwc.upgradecount == 0) { return true; } return false; } private bool IsRwHashEntryChanged(System.Threading.ReaderWriterCount lrwc) { return lrwc.lockID != _lockID; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private System.Threading.ReaderWriterCount GetThreadRWCount(bool dontAllocate) { System.Threading.ReaderWriterCount next = t_rwc; System.Threading.ReaderWriterCount readerWriterCount = null; while (next != null) { if (next.lockID == _lockID) { return next; } if (!dontAllocate && readerWriterCount == null && IsRWEntryEmpty(next)) { readerWriterCount = next; } next = next.next; } if (dontAllocate) { return null; } if (readerWriterCount == null) { readerWriterCount = new System.Threading.ReaderWriterCount(); readerWriterCount.next = t_rwc; t_rwc = readerWriterCount; } readerWriterCount.lockID = _lockID; return readerWriterCount; } public void EnterReadLock() { TryEnterReadLock(-1); } public bool TryEnterReadLock(TimeSpan timeout) { return TryEnterReadLock(new TimeoutTracker(timeout)); } public bool TryEnterReadLock(int millisecondsTimeout) { return TryEnterReadLock(new TimeoutTracker(millisecondsTimeout)); } private bool TryEnterReadLock(TimeoutTracker timeout) { return TryEnterReadLockCore(timeout); } private bool TryEnterReadLockCore(TimeoutTracker timeout) { if (_fDisposed) { throw new ObjectDisposedException(null); } System.Threading.ReaderWriterCount readerWriterCount = null; int currentManagedThreadId = Environment.CurrentManagedThreadId; if (!_fIsReentrant) { if (currentManagedThreadId == _writeLockOwnerId) { throw new LockRecursionException(System.SR.LockRecursionException_ReadAfterWriteNotAllowed); } EnterMyLock(); readerWriterCount = GetThreadRWCount(dontAllocate: false); if (readerWriterCount.readercount > 0) { ExitMyLock(); throw new LockRecursionException(System.SR.LockRecursionException_RecursiveReadNotAllowed); } if (currentManagedThreadId == _upgradeLockOwnerId) { readerWriterCount.readercount++; _owners++; ExitMyLock(); return true; } } else { EnterMyLock(); readerWriterCount = GetThreadRWCount(dontAllocate: false); if (readerWriterCount.readercount > 0) { readerWriterCount.readercount++; ExitMyLock(); return true; } if (currentManagedThreadId == _upgradeLockOwnerId) { readerWriterCount.readercount++; _owners++; ExitMyLock(); _fUpgradeThreadHoldingRead = true; return true; } if (currentManagedThreadId == _writeLockOwnerId) { readerWriterCount.readercount++; _owners++; ExitMyLock(); return true; } } bool flag = true; int num = 0; while (true) { if (_owners < 268435454) { _owners++; readerWriterCount.readercount++; ExitMyLock(); return flag; } if (num < 20) { ExitMyLock(); if (timeout.IsExpired) { return false; } num++; SpinWait(num); EnterMyLock(); if (IsRwHashEntryChanged(readerWriterCount)) { readerWriterCount = GetThreadRWCount(dontAllocate: false); } } else if (_readEvent == null) { LazyCreateEvent(ref _readEvent, makeAutoResetEvent: false); if (IsRwHashEntryChanged(readerWriterCount)) { readerWriterCount = GetThreadRWCount(dontAllocate: false); } } else { flag = WaitOnEvent(_readEvent, ref _numReadWaiters, timeout, isWriteWaiter: false); if (!flag) { break; } if (IsRwHashEntryChanged(readerWriterCount)) { readerWriterCount = GetThreadRWCount(dontAllocate: false); } } } return false; } public void EnterWriteLock() { TryEnterWriteLock(-1); } public bool TryEnterWriteLock(TimeSpan timeout) { return TryEnterWriteLock(new TimeoutTracker(timeout)); } public bool TryEnterWriteLock(int millisecondsTimeout) { return TryEnterWriteLock(new TimeoutTracker(millisecondsTimeout)); } private bool TryEnterWriteLock(TimeoutTracker timeout) { return TryEnterWriteLockCore(timeout); } private bool TryEnterWriteLockCore(TimeoutTracker timeout) { if (_fDisposed) { throw new ObjectDisposedException(null); } int currentManagedThreadId = Environment.CurrentManagedThreadId; bool flag = false; System.Threading.ReaderWriterCount threadRWCount; if (!_fIsReentrant) { if (currentManagedThreadId == _writeLockOwnerId) { throw new LockRecursionException(System.SR.LockRecursionException_RecursiveWriteNotAllowed); } if (currentManagedThreadId == _upgradeLockOwnerId) { flag = true; } EnterMyLock(); threadRWCount = GetThreadRWCount(dontAllocate: true); if (threadRWCount != null && threadRWCount.readercount > 0) { ExitMyLock(); throw new LockRecursionException(System.SR.LockRecursionException_WriteAfterReadNotAllowed); } } else { EnterMyLock(); threadRWCount = GetThreadRWCount(dontAllocate: false); if (currentManagedThreadId == _writeLockOwnerId) { threadRWCount.writercount++; ExitMyLock(); return true; } if (currentManagedThreadId == _upgradeLockOwnerId) { flag = true; } else if (threadRWCount.readercount > 0) { ExitMyLock(); throw new LockRecursionException(System.SR.LockRecursionException_WriteAfterReadNotAllowed); } } int num = 0; bool flag2 = true; while (true) { if (IsWriterAcquired()) { SetWriterAcquired(); break; } if (flag) { uint numReaders = GetNumReaders(); if (numReaders == 1) { SetWriterAcquired(); break; } if (numReaders == 2 && threadRWCount != null) { if (IsRwHashEntryChanged(threadRWCount)) { threadRWCount = GetThreadRWCount(dontAllocate: false); } if (threadRWCount.readercount > 0) { SetWriterAcquired(); break; } } } if (num < 20) { ExitMyLock(); if (timeout.IsExpired) { return false; } num++; SpinWait(num); EnterMyLock(); } else if (flag) { if (_waitUpgradeEvent == null) { LazyCreateEvent(ref _waitUpgradeEvent, makeAutoResetEvent: true); } else if (!WaitOnEvent(_waitUpgradeEvent, ref _numWriteUpgradeWaiters, timeout, isWriteWaiter: true)) { return false; } } else if (_writeEvent == null) { LazyCreateEvent(ref _writeEvent, makeAutoResetEvent: true); } else if (!WaitOnEvent(_writeEvent, ref _numWriteWaiters, timeout, isWriteWaiter: true)) { return false; } } if (_fIsReentrant) { if (IsRwHashEntryChanged(threadRWCount)) { threadRWCount = GetThreadRWCount(dontAllocate: false); } threadRWCount.writercount++; } ExitMyLock(); _writeLockOwnerId = currentManagedThreadId; return true; } public void EnterUpgradeableReadLock() { TryEnterUpgradeableReadLock(-1); } public bool TryEnterUpgradeableReadLock(TimeSpan timeout) { return TryEnterUpgradeableReadLock(new TimeoutTracker(timeout)); } public bool TryEnterUpgradeableReadLock(int millisecondsTimeout) { return TryEnterUpgradeableReadLock(new TimeoutTracker(millisecondsTimeout)); } private bool TryEnterUpgradeableReadLock(TimeoutTracker timeout) { return TryEnterUpgradeableReadLockCore(timeout); } private bool TryEnterUpgradeableReadLockCore(TimeoutTracker timeout) { if (_fDisposed) { throw new ObjectDisposedException(null); } int currentManagedThreadId = Environment.CurrentManagedThreadId; System.Threading.ReaderWriterCount threadRWCount; if (!_fIsReentrant) { if (currentManagedThreadId == _upgradeLockOwnerId) { throw new LockRecursionException(System.SR.LockRecursionException_RecursiveUpgradeNotAllowed); } if (currentManagedThreadId == _writeLockOwnerId) { throw new LockRecursionException(System.SR.LockRecursionException_UpgradeAfterWriteNotAllowed); } EnterMyLock(); threadRWCount = GetThreadRWCount(dontAllocate: true); if (threadRWCount != null && threadRWCount.readercount > 0) { ExitMyLock(); throw new LockRecursionException(System.SR.LockRecursionException_UpgradeAfterReadNotAllowed); } } else { EnterMyLock(); threadRWCount = GetThreadRWCount(dontAllocate: false); if (currentManagedThreadId == _upgradeLockOwnerId) { threadRWCount.upgradecount++; ExitMyLock(); return true; } if (currentManagedThreadId == _writeLockOwnerId) { _owners++; _upgradeLockOwnerId = currentManagedThreadId; threadRWCount.upgradecount++; if (threadRWCount.readercount > 0) { _fUpgradeThreadHoldingRead = true; } ExitMyLock(); return true; } if (threadRWCount.readercount > 0) { ExitMyLock(); throw new LockRecursionException(System.SR.LockRecursionException_UpgradeAfterReadNotAllowed); } } bool flag = true; int num = 0; while (true) { if (_upgradeLockOwnerId == -1 && _owners < 268435454) { _owners++; _upgradeLockOwnerId = currentManagedThreadId; if (_fIsReentrant) { if (IsRwHashEntryChanged(threadRWCount)) { threadRWCount = GetThreadRWCount(dontAllocate: false); } threadRWCount.upgradecount++; } break; } if (num < 20) { ExitMyLock(); if (timeout.IsExpired) { return false; } num++; SpinWait(num); EnterMyLock(); } else if (_upgradeEvent == null) { LazyCreateEvent(ref _upgradeEvent, makeAutoResetEvent: true); } else if (!WaitOnEvent(_upgradeEvent, ref _numUpgradeWaiters, timeout, isWriteWaiter: false)) { return false; } } ExitMyLock(); return true; } public void ExitReadLock() { System.Threading.ReaderWriterCount readerWriterCount = null; EnterMyLock(); readerWriterCount = GetThreadRWCount(dontAllocate: true); if (readerWriterCount == null || readerWriterCount.readercount < 1) { ExitMyLock(); throw new SynchronizationLockException(System.SR.SynchronizationLockException_MisMatchedRead); } if (_fIsReentrant) { if (readerWriterCount.readercount > 1) { readerWriterCount.readercount--; ExitMyLock(); return; } if (Environment.CurrentManagedThreadId == _upgradeLockOwnerId) { _fUpgradeThreadHoldingRead = false; } } _owners--; readerWriterCount.readercount--; ExitAndWakeUpAppropriateWaiters(); } public void ExitWriteLock() { if (!_fIsReentrant) { if (Environment.CurrentManagedThreadId != _writeLockOwnerId) { throw new SynchronizationLockException(System.SR.SynchronizationLockException_MisMatchedWrite); } EnterMyLock(); } else { EnterMyLock(); System.Threading.ReaderWriterCount threadRWCount = GetThreadRWCount(dontAllocate: false); if (threadRWCount == null) { ExitMyLock(); throw new SynchronizationLockException(System.SR.SynchronizationLockException_MisMatchedWrite); } if (threadRWCount.writercount < 1) { ExitMyLock(); throw new SynchronizationLockException(System.SR.SynchronizationLockException_MisMatchedWrite); } threadRWCount.writercount--; if (threadRWCount.writercount > 0) { ExitMyLock(); return; } } ClearWriterAcquired(); _writeLockOwnerId = -1; ExitAndWakeUpAppropriateWaiters(); } public void ExitUpgradeableReadLock() { if (!_fIsReentrant) { if (Environment.CurrentManagedThreadId != _upgradeLockOwnerId) { throw new SynchronizationLockException(System.SR.SynchronizationLockException_MisMatchedUpgrade); } EnterMyLock(); } else { EnterMyLock(); System.Threading.ReaderWriterCount threadRWCount = GetThreadRWCount(dontAllocate: true); if (threadRWCount == null) { ExitMyLock(); throw new SynchronizationLockException(System.SR.SynchronizationLockException_MisMatchedUpgrade); } if (threadRWCount.upgradecount < 1) { ExitMyLock(); throw new SynchronizationLockException(System.SR.SynchronizationLockException_MisMatchedUpgrade); } threadRWCount.upgradecount--; if (threadRWCount.upgradecount > 0) { ExitMyLock(); return; } _fUpgradeThreadHoldingRead = false; } _owners--; _upgradeLockOwnerId = -1; ExitAndWakeUpAppropriateWaiters(); } private void LazyCreateEvent(ref EventWaitHandle waitEvent, bool makeAutoResetEvent) { ExitMyLock(); EventWaitHandle eventWaitHandle = ((!makeAutoResetEvent) ? ((EventWaitHandle)new ManualResetEvent(initialState: false)) : ((EventWaitHandle)new AutoResetEvent(initialState: false))); EnterMyLock(); if (waitEvent == null) { waitEvent = eventWaitHandle; } else { eventWaitHandle.Dispose(); } } private bool WaitOnEvent(EventWaitHandle waitEvent, ref uint numWaiters, TimeoutTracker timeout, bool isWriteWaiter) { waitEvent.Reset(); numWaiters++; _fNoWaiters = false; if (_numWriteWaiters == 1) { SetWritersWaiting(); } if (_numWriteUpgradeWaiters == 1) { SetUpgraderWaiting(); } bool flag = false; ExitMyLock(); try { flag = waitEvent.WaitOne(timeout.RemainingMilliseconds); } finally { EnterMyLock(); numWaiters--; if (_numWriteWaiters == 0 && _numWriteUpgradeWaiters == 0 && _numUpgradeWaiters == 0 && _numReadWaiters == 0) { _fNoWaiters = true; } if (_numWriteWaiters == 0) { ClearWritersWaiting(); } if (_numWriteUpgradeWaiters == 0) { ClearUpgraderWaiting(); } if (!flag) { if (isWriteWaiter) { ExitAndWakeUpAppropriateReadWaiters(); } else { ExitMyLock(); } } } return flag; } private void ExitAndWakeUpAppropriateWaiters() { if (_fNoWaiters) { ExitMyLock(); } else { ExitAndWakeUpAppropriateWaitersPreferringWriters(); } } private void ExitAndWakeUpAppropriateWaitersPreferringWriters() { uint numReaders = GetNumReaders(); if (_fIsReentrant && _numWriteUpgradeWaiters != 0 && _fUpgradeThreadHoldingRead && numReaders == 2) { ExitMyLock(); _waitUpgradeEvent.Set(); } else if (numReaders == 1 && _numWriteUpgradeWaiters != 0) { ExitMyLock(); _waitUpgradeEvent.Set(); } else if (numReaders == 0 && _numWriteWaiters != 0) { ExitMyLock(); _writeEvent.Set(); } else { ExitAndWakeUpAppropriateReadWaiters(); } } private void ExitAndWakeUpAppropriateReadWaiters() { if (_numWriteWaiters != 0 || _numWriteUpgradeWaiters != 0 || _fNoWaiters) { ExitMyLock(); return; } bool flag = _numReadWaiters != 0; bool flag2 = _numUpgradeWaiters != 0 && _upgradeLockOwnerId == -1; ExitMyLock(); if (flag) { _readEvent.Set(); } if (flag2) { _upgradeEvent.Set(); } } private bool IsWriterAcquired() { return (_owners & 0xBFFFFFFFu) == 0; } private void SetWriterAcquired() { _owners |= 2147483648u; } private void ClearWriterAcquired() { _owners &= 2147483647u; } private void SetWritersWaiting() { _owners |= 1073741824u; } private void ClearWritersWaiting() { _owners &= 3221225471u; } private void SetUpgraderWaiting() { _owners |= 536870912u; } private void ClearUpgraderWaiting() { _owners &= 3758096383u; } private uint GetNumReaders() { return _owners & 0xFFFFFFFu; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void EnterMyLock() { if (Interlocked.CompareExchange(ref _myLock, 1, 0) != 0) { EnterMyLockSpin(); } } private void EnterMyLockSpin() { int processorCount = Environment.ProcessorCount; int num = 0; while (true) { if (num < 10 && processorCount > 1) { Helpers.Spin(20 * (num + 1)); } else if (num < 15) { Helpers.Sleep(0); } else { Helpers.Sleep(1); } if (_myLock == 0 && Interlocked.CompareExchange(ref _myLock, 1, 0) == 0) { break; } num++; } } private void ExitMyLock() { Volatile.Write(ref _myLock, 0); } private static void SpinWait(int SpinCount) { if (SpinCount < 5 && Environment.ProcessorCount > 1) { Helpers.Spin(20 * SpinCount); } else if (SpinCount < 17) { Helpers.Sleep(0); } else { Helpers.Sleep(1); } } public void Dispose() { Dispose(disposing: true); } private void Dispose(bool disposing) { if (disposing && !_fDisposed) { if (WaitingReadCount > 0 || WaitingUpgradeCount > 0 || WaitingWriteCount > 0) { throw new SynchronizationLockException(System.SR.SynchronizationLockException_IncorrectDispose); } if (IsReadLockHeld || IsUpgradeableReadLockHeld || IsWriteLockHeld) { throw new SynchronizationLockException(System.SR.SynchronizationLockException_IncorrectDispose); } if (_writeEvent != null) { _writeEvent.Dispose(); _writeEvent = null; } if (_readEvent != null) { _readEvent.Dispose(); _readEvent = null; } if (_upgradeEvent != null) { _upgradeEvent.Dispose(); _upgradeEvent = null; } if (_waitUpgradeEvent != null) { _waitUpgradeEvent.Dispose(); _waitUpgradeEvent = null; } _fDisposed = true; } } } }