Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of CustomRadio v0.1.1
CliWrap.dll
Decompiled 2 years agousing System; using System.Buffers; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Management; using System.Net.Http; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Text; using System.Threading; using System.Threading.Tasks; using CliWrap.Builders; using CliWrap.Exceptions; using CliWrap.Utils; using CliWrap.Utils.Extensions; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Tyrrrz")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright (C) Oleksii Holub")] [assembly: AssemblyDescription("Library for interacting with external command-line interfaces")] [assembly: AssemblyFileVersion("3.6.4.0")] [assembly: AssemblyInformationalVersion("3.6.4+77a9f6d5692718555f040ad4603916ce0bdb0715")] [assembly: AssemblyProduct("CliWrap")] [assembly: AssemblyTitle("CliWrap")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/Tyrrrz/CliWrap")] [assembly: AssemblyVersion("3.6.4.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } internal static class PolyfillExtensions { public static async Task<Stream> GetStreamAsync(this HttpClient httpClient, string requestUri, CancellationToken cancellationToken = default(CancellationToken)) { _ = 1; try { HttpResponseMessage obj = await httpClient.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); obj.EnsureSuccessStatusCode(); return await ReadAsStreamAsync(obj.Content, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } catch (OperationCanceledException ex) when (ex.CancellationToken != cancellationToken && cancellationToken.IsCancellationRequested) { throw new OperationCanceledException(ex.Message, ex.InnerException, cancellationToken); } } public static async Task<Stream> GetStreamAsync(this HttpClient httpClient, Uri requestUri, CancellationToken cancellationToken = default(CancellationToken)) { return await GetStreamAsync(httpClient, requestUri.ToString(), cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static async Task<byte[]> GetByteArrayAsync(this HttpClient httpClient, string requestUri, CancellationToken cancellationToken = default(CancellationToken)) { _ = 1; try { using HttpResponseMessage response = await httpClient.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); response.EnsureSuccessStatusCode(); return await ReadAsByteArrayAsync(response.Content, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } catch (OperationCanceledException ex) when (ex.CancellationToken != cancellationToken && cancellationToken.IsCancellationRequested) { throw new OperationCanceledException(ex.Message, ex.InnerException, cancellationToken); } } public static async Task<byte[]> GetByteArrayAsync(this HttpClient httpClient, Uri requestUri, CancellationToken cancellationToken = default(CancellationToken)) { return await GetByteArrayAsync(httpClient, requestUri.ToString(), cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static async Task<string> GetStringAsync(this HttpClient httpClient, string requestUri, CancellationToken cancellationToken = default(CancellationToken)) { _ = 1; try { using HttpResponseMessage response = await httpClient.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); response.EnsureSuccessStatusCode(); return await ReadAsStringAsync(response.Content, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } catch (OperationCanceledException ex) when (ex.CancellationToken != cancellationToken && cancellationToken.IsCancellationRequested) { throw new OperationCanceledException(ex.Message, ex.InnerException, cancellationToken); } } public static async Task<string> GetStringAsync(this HttpClient httpClient, Uri requestUri, CancellationToken cancellationToken = default(CancellationToken)) { return await GetStringAsync(httpClient, requestUri.ToString(), cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static async Task<Stream> ReadAsStreamAsync(this HttpContent httpContent, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); return await httpContent.ReadAsStreamAsync().ConfigureAwait(continueOnCapturedContext: false); } public static async Task<byte[]> ReadAsByteArrayAsync(this HttpContent httpContent, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); return await httpContent.ReadAsByteArrayAsync().ConfigureAwait(continueOnCapturedContext: false); } public static async Task<string> ReadAsStringAsync(this HttpContent httpContent, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); return await httpContent.ReadAsStringAsync().ConfigureAwait(continueOnCapturedContext: false); } public static async Task WaitForExitAsync(this Process process, CancellationToken cancellationToken = default(CancellationToken)) { TaskCompletionSource<object?> tcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously); try { process.EnableRaisingEvents = true; } catch when (process.HasExited) { return; } process.Exited += HandleExited; try { using (cancellationToken.Register(delegate { tcs.TrySetCanceled(cancellationToken); })) { await tcs.Task; } } finally { process.Exited -= HandleExited; } void HandleExited(object? sender, EventArgs args) { tcs.TrySetResult(null); } } public static async Task WaitAsync(this Task task, TimeSpan timeout, CancellationToken cancellationToken) { Task cancellationTask = Task.Delay(timeout, cancellationToken); Task finishedTask = await Task.WhenAny(new Task[2] { task, cancellationTask }).ConfigureAwait(continueOnCapturedContext: false); await finishedTask.ConfigureAwait(continueOnCapturedContext: false); if (finishedTask == cancellationTask) { throw new TimeoutException("The operation has timed out."); } } public static async Task WaitAsync(this Task task, CancellationToken cancellationToken) { await WaitAsync(task, Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static async Task WaitAsync(this Task task, TimeSpan timeout) { await WaitAsync(task, timeout, CancellationToken.None).ConfigureAwait(continueOnCapturedContext: false); } public static async Task<T> WaitAsync<T>(this Task<T> task, TimeSpan timeout, CancellationToken cancellationToken) { Task cancellationTask = Task.Delay(timeout, cancellationToken); Task finishedTask = await Task.WhenAny(new Task[2] { task, cancellationTask }).ConfigureAwait(continueOnCapturedContext: false); await finishedTask.ConfigureAwait(continueOnCapturedContext: false); if (finishedTask == cancellationTask) { throw new TimeoutException("The operation has timed out."); } return task.Result; } public static async Task<T> WaitAsync<T>(this Task<T> task, CancellationToken cancellationToken) { return await WaitAsync(task, Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static async Task<T> WaitAsync<T>(this Task<T> task, TimeSpan timeout) { return await WaitAsync(task, timeout, CancellationToken.None).ConfigureAwait(continueOnCapturedContext: false); } public static int ReadAtLeast(this Stream stream, byte[] buffer, int minimumBytes, bool throwOnEndOfStream = true) { int i; int num; for (i = 0; i < buffer.Length; i += num) { num = stream.Read(buffer, i, Math.Min(minimumBytes, buffer.Length - i)); if (num <= 0) { break; } } if (i < minimumBytes && throwOnEndOfStream) { throw new EndOfStreamException(); } return i; } public static void ReadExactly(this Stream stream, byte[] buffer, int offset, int count) { int num; for (int i = 0; i < count; i += num) { num = stream.Read(buffer, offset + i, count - i); if (num <= 0) { throw new EndOfStreamException(); } } } public static void ReadExactly(this Stream stream, byte[] buffer) { stream.ReadExactly(buffer, 0, buffer.Length); } public static async Task<int> ReadAtLeastAsync(this Stream stream, byte[] buffer, int minimumBytes, bool throwOnEndOfStream = true, CancellationToken cancellationToken = default(CancellationToken)) { int totalBytesRead; int num; for (totalBytesRead = 0; totalBytesRead < buffer.Length; totalBytesRead += num) { num = await stream.ReadAsync(buffer, totalBytesRead, Math.Min(minimumBytes, buffer.Length - totalBytesRead), cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (num <= 0) { break; } } if (totalBytesRead < minimumBytes && throwOnEndOfStream) { throw new EndOfStreamException(); } return totalBytesRead; } public static async Task ReadExactlyAsync(this Stream stream, byte[] buffer, int offset, int count, CancellationToken cancellationToken = default(CancellationToken)) { int num; for (int totalBytesRead = 0; totalBytesRead < count; totalBytesRead += num) { num = await stream.ReadAsync(buffer, offset + totalBytesRead, count - totalBytesRead, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (num <= 0) { throw new EndOfStreamException(); } } } public static async Task ReadExactlyAsync(this Stream stream, byte[] buffer, CancellationToken cancellationToken = default(CancellationToken)) { await stream.ReadExactlyAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static int ReadAtLeast(this Stream stream, Span<byte> buffer, int minimumBytes, bool throwOnEndOfStream = true) { int i; int num; for (i = 0; i < buffer.Length; i += num) { num = stream.Read(buffer.Slice(i)); if (num <= 0) { break; } } if (i < minimumBytes && throwOnEndOfStream) { throw new EndOfStreamException(); } return i; } public static void ReadExactly(this Stream stream, Span<byte> buffer) { byte[] array = buffer.ToArray(); stream.ReadExactly(array, 0, array.Length); array.CopyTo(buffer); } public static async Task<int> ReadAtLeastAsync(this Stream stream, Memory<byte> buffer, int minimumBytes, bool throwOnEndOfStream = true, CancellationToken cancellationToken = default(CancellationToken)) { int totalBytesRead; int num; for (totalBytesRead = 0; totalBytesRead < buffer.Length; totalBytesRead += num) { num = await stream.ReadAsync(buffer.Slice(totalBytesRead), cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (num <= 0) { break; } } if (totalBytesRead < minimumBytes && throwOnEndOfStream) { throw new EndOfStreamException(); } return totalBytesRead; } public static async Task ReadExactlyAsync(this Stream stream, Memory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken)) { byte[] bufferArray = buffer.ToArray(); await stream.ReadExactlyAsync(bufferArray, 0, bufferArray.Length, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); bufferArray.CopyTo(buffer); } private static void KillProcessTree(int processId) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown ManagementObjectSearcher val = new ManagementObjectSearcher($"SELECT * FROM Win32_Process WHERE ParentProcessID={processId}"); try { ManagementObjectCollection val2 = val.Get(); try { try { using Process process = Process.GetProcessById(processId); if (!process.HasExited) { process.Kill(); } } catch { } foreach (ManagementObject item in ((IEnumerable)val2).Cast<ManagementObject>()) { KillProcessTree(Convert.ToInt32(((ManagementBaseObject)item)["ProcessID"])); } } finally { ((IDisposable)val2)?.Dispose(); } } finally { ((IDisposable)val)?.Dispose(); } } public static void Kill(this Process process, bool entireProcessTree) { if (!entireProcessTree) { process.Kill(); } else if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { process.Kill(); } else { KillProcessTree(process.Id); } } } namespace CliWrap { public static class Cli { public static Command Wrap(string targetFilePath) { return new Command(targetFilePath); } } public class Command : ICommandConfiguration { public string TargetFilePath { get; } public string Arguments { get; } public string WorkingDirPath { get; } public Credentials Credentials { get; } public IReadOnlyDictionary<string, string?> EnvironmentVariables { get; } public CommandResultValidation Validation { get; } public PipeSource StandardInputPipe { get; } public PipeTarget StandardOutputPipe { get; } public PipeTarget StandardErrorPipe { get; } public Command(string targetFilePath, string arguments, string workingDirPath, Credentials credentials, IReadOnlyDictionary<string, string?> environmentVariables, CommandResultValidation validation, PipeSource standardInputPipe, PipeTarget standardOutputPipe, PipeTarget standardErrorPipe) { TargetFilePath = targetFilePath; Arguments = arguments; WorkingDirPath = workingDirPath; Credentials = credentials; EnvironmentVariables = environmentVariables; Validation = validation; StandardInputPipe = standardInputPipe; StandardOutputPipe = standardOutputPipe; StandardErrorPipe = standardErrorPipe; } public Command(string targetFilePath) : this(targetFilePath, string.Empty, Directory.GetCurrentDirectory(), CliWrap.Credentials.Default, new Dictionary<string, string>(), CommandResultValidation.ZeroExitCode, PipeSource.Null, PipeTarget.Null, PipeTarget.Null) { } public Command WithTargetFile(string targetFilePath) { return new Command(targetFilePath, Arguments, WorkingDirPath, Credentials, EnvironmentVariables, Validation, StandardInputPipe, StandardOutputPipe, StandardErrorPipe); } public Command WithArguments(string arguments) { return new Command(TargetFilePath, arguments, WorkingDirPath, Credentials, EnvironmentVariables, Validation, StandardInputPipe, StandardOutputPipe, StandardErrorPipe); } public Command WithArguments(IEnumerable<string> arguments, bool escape) { IEnumerable<string> arguments2 = arguments; return WithArguments(delegate(ArgumentsBuilder args) { args.Add(arguments2, escape); }); } public Command WithArguments(IEnumerable<string> arguments) { return WithArguments(arguments, escape: true); } public Command WithArguments(Action<ArgumentsBuilder> configure) { ArgumentsBuilder argumentsBuilder = new ArgumentsBuilder(); configure(argumentsBuilder); return WithArguments(argumentsBuilder.Build()); } public Command WithWorkingDirectory(string workingDirPath) { return new Command(TargetFilePath, Arguments, workingDirPath, Credentials, EnvironmentVariables, Validation, StandardInputPipe, StandardOutputPipe, StandardErrorPipe); } public Command WithCredentials(Credentials credentials) { return new Command(TargetFilePath, Arguments, WorkingDirPath, credentials, EnvironmentVariables, Validation, StandardInputPipe, StandardOutputPipe, StandardErrorPipe); } public Command WithCredentials(Action<CredentialsBuilder> configure) { CredentialsBuilder credentialsBuilder = new CredentialsBuilder(); configure(credentialsBuilder); return WithCredentials(credentialsBuilder.Build()); } public Command WithEnvironmentVariables(IReadOnlyDictionary<string, string?> environmentVariables) { return new Command(TargetFilePath, Arguments, WorkingDirPath, Credentials, environmentVariables, Validation, StandardInputPipe, StandardOutputPipe, StandardErrorPipe); } public Command WithEnvironmentVariables(Action<EnvironmentVariablesBuilder> configure) { EnvironmentVariablesBuilder environmentVariablesBuilder = new EnvironmentVariablesBuilder(); configure(environmentVariablesBuilder); return WithEnvironmentVariables(environmentVariablesBuilder.Build()); } public Command WithValidation(CommandResultValidation validation) { return new Command(TargetFilePath, Arguments, WorkingDirPath, Credentials, EnvironmentVariables, validation, StandardInputPipe, StandardOutputPipe, StandardErrorPipe); } public Command WithStandardInputPipe(PipeSource source) { return new Command(TargetFilePath, Arguments, WorkingDirPath, Credentials, EnvironmentVariables, Validation, source, StandardOutputPipe, StandardErrorPipe); } public Command WithStandardOutputPipe(PipeTarget target) { return new Command(TargetFilePath, Arguments, WorkingDirPath, Credentials, EnvironmentVariables, Validation, StandardInputPipe, target, StandardErrorPipe); } public Command WithStandardErrorPipe(PipeTarget target) { return new Command(TargetFilePath, Arguments, WorkingDirPath, Credentials, EnvironmentVariables, Validation, StandardInputPipe, StandardOutputPipe, target); } [ExcludeFromCodeCoverage] public override string ToString() { return TargetFilePath + " " + Arguments; } private string GetOptimallyQualifiedTargetFilePath() { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return TargetFilePath; } if (Path.IsPathRooted(TargetFilePath) || !string.IsNullOrWhiteSpace(Path.GetExtension(TargetFilePath))) { return TargetFilePath; } return (from probeDirPath in GetProbeDirectoryPaths() where Directory.Exists(probeDirPath) select Path.Combine(probeDirPath, TargetFilePath) into baseFilePath from extension in new string[3] { "exe", "cmd", "bat" } select Path.ChangeExtension(baseFilePath, extension)).FirstOrDefault(File.Exists) ?? TargetFilePath; static IEnumerable<string> GetProbeDirectoryPaths() { if (!string.IsNullOrWhiteSpace(EnvironmentEx.ProcessPath)) { string directoryName = Path.GetDirectoryName(EnvironmentEx.ProcessPath); if (!string.IsNullOrWhiteSpace(directoryName)) { yield return directoryName; } } yield return Directory.GetCurrentDirectory(); string[] array = Environment.GetEnvironmentVariable("PATH")?.Split(Path.PathSeparator); if (array != null) { string[] array2 = array; for (int i = 0; i < array2.Length; i++) { yield return array2[i]; } } } } private ProcessStartInfo CreateStartInfo() { ProcessStartInfo processStartInfo = new ProcessStartInfo { FileName = GetOptimallyQualifiedTargetFilePath(), Arguments = Arguments, WorkingDirectory = WorkingDirPath, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true }; try { if (Credentials.Domain != null) { processStartInfo.Domain = Credentials.Domain; } if (Credentials.UserName != null) { processStartInfo.UserName = Credentials.UserName; } if (Credentials.Password != null) { processStartInfo.Password = Credentials.Password.ToSecureString(); } if (Credentials.LoadUserProfile) { processStartInfo.LoadUserProfile = Credentials.LoadUserProfile; } } catch (NotSupportedException innerException) { throw new NotSupportedException("Cannot start a process using the provided credentials. Setting custom domain, password, or loading user profile is only supported on Windows.", innerException); } foreach (var (key, text3) in EnvironmentVariables) { if (text3 != null) { processStartInfo.Environment[key] = text3; } else { processStartInfo.Environment.Remove(key); } } return processStartInfo; } private async Task PipeStandardInputAsync(ProcessEx process, CancellationToken cancellationToken = default(CancellationToken)) { await using (process.StandardInput.ToAsyncDisposable()) { try { await PolyfillExtensions.WaitAsync(StandardInputPipe.CopyToAsync(process.StandardInput, cancellationToken), cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } catch (IOException ex) when (ex.GetType() == typeof(IOException)) { } } } private async Task PipeStandardOutputAsync(ProcessEx process, CancellationToken cancellationToken = default(CancellationToken)) { await using (process.StandardOutput.ToAsyncDisposable()) { await StandardOutputPipe.CopyFromAsync(process.StandardOutput, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } } private async Task PipeStandardErrorAsync(ProcessEx process, CancellationToken cancellationToken = default(CancellationToken)) { await using (process.StandardError.ToAsyncDisposable()) { await StandardErrorPipe.CopyFromAsync(process.StandardError, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } } private async Task<CommandResult> ExecuteAsync(ProcessEx process, CancellationToken forcefulCancellationToken = default(CancellationToken), CancellationToken gracefulCancellationToken = default(CancellationToken)) { using (process) { CancellationTokenSource waitTimeoutCts = new CancellationTokenSource(); try { CommandResult result; await using (forcefulCancellationToken.Register(delegate { waitTimeoutCts.CancelAfter(TimeSpan.FromSeconds(3.0)); }).ToAsyncDisposable()) { using CancellationTokenSource stdInCts = CancellationTokenSource.CreateLinkedTokenSource(new CancellationToken[1] { forcefulCancellationToken }); CommandResult commandResult2; await using (forcefulCancellationToken.Register(process.Kill).ToAsyncDisposable()) { CommandResult commandResult; await using (gracefulCancellationToken.Register(process.Interrupt).ToAsyncDisposable()) { Task pipingTask = Task.WhenAll(PipeStandardInputAsync(process, stdInCts.Token), PipeStandardOutputAsync(process, forcefulCancellationToken), PipeStandardErrorAsync(process, forcefulCancellationToken)); try { await process.WaitUntilExitAsync(waitTimeoutCts.Token).ConfigureAwait(continueOnCapturedContext: false); stdInCts.Cancel(); await pipingTask.ConfigureAwait(continueOnCapturedContext: false); } catch (OperationCanceledException ex) when (ex.CancellationToken == forcefulCancellationToken || ex.CancellationToken == gracefulCancellationToken || ex.CancellationToken == waitTimeoutCts.Token || ex.CancellationToken == stdInCts.Token) { } forcefulCancellationToken.ThrowIfCancellationRequested("Command execution canceled. " + $"Underlying process ({process.Name}#{process.Id}) was forcefully terminated."); gracefulCancellationToken.ThrowIfCancellationRequested("Command execution canceled. " + $"Underlying process ({process.Name}#{process.Id}) was gracefully terminated."); if (process.ExitCode != 0 && Validation.IsZeroExitCodeValidationEnabled()) { throw new CommandExecutionException(this, process.ExitCode, $"Command execution failed because the underlying process ({process.Name}#{process.Id}) returned a non-zero exit code ({process.ExitCode}).\r\n\r\nCommand:\r\n{TargetFilePath} {Arguments}\r\n\r\nYou can suppress this validation by calling `WithValidation(CommandResultValidation.None)` on the command."); } commandResult = new CommandResult(process.ExitCode, process.StartTime, process.ExitTime); } commandResult2 = commandResult; } result = commandResult2; } return result; } finally { if (waitTimeoutCts != null) { ((IDisposable)waitTimeoutCts).Dispose(); } } } } public CommandTask<CommandResult> ExecuteAsync(CancellationToken forcefulCancellationToken, CancellationToken gracefulCancellationToken) { ProcessEx processEx = new ProcessEx(CreateStartInfo()); processEx.Start(); int id = processEx.Id; return new CommandTask<CommandResult>(ExecuteAsync(processEx, forcefulCancellationToken, gracefulCancellationToken), id); } public CommandTask<CommandResult> ExecuteAsync(CancellationToken cancellationToken = default(CancellationToken)) { return ExecuteAsync(cancellationToken, CancellationToken.None); } public static Command operator |(Command source, PipeTarget target) { return source.WithStandardOutputPipe(target); } public static Command operator |(Command source, Stream target) { return source | PipeTarget.ToStream(target); } public static Command operator |(Command source, StringBuilder target) { return source | PipeTarget.ToStringBuilder(target); } public static Command operator |(Command source, Func<string, CancellationToken, Task> target) { return source | PipeTarget.ToDelegate(target); } public static Command operator |(Command source, Func<string, Task> target) { return source | PipeTarget.ToDelegate(target); } public static Command operator |(Command source, Action<string> target) { return source | PipeTarget.ToDelegate(target); } public static Command operator |(Command source, (PipeTarget stdOut, PipeTarget stdErr) targets) { return source.WithStandardOutputPipe(targets.stdOut).WithStandardErrorPipe(targets.stdErr); } public static Command operator |(Command source, (Stream stdOut, Stream stdErr) targets) { return source | (PipeTarget.ToStream(targets.stdOut), PipeTarget.ToStream(targets.stdErr)); } public static Command operator |(Command source, (StringBuilder stdOut, StringBuilder stdErr) targets) { return source | (PipeTarget.ToStringBuilder(targets.stdOut), PipeTarget.ToStringBuilder(targets.stdErr)); } public static Command operator |(Command source, (Func<string, CancellationToken, Task> stdOut, Func<string, CancellationToken, Task> stdErr) targets) { return source | (PipeTarget.ToDelegate(targets.stdOut), PipeTarget.ToDelegate(targets.stdErr)); } public static Command operator |(Command source, (Func<string, Task> stdOut, Func<string, Task> stdErr) targets) { return source | (PipeTarget.ToDelegate(targets.stdOut), PipeTarget.ToDelegate(targets.stdErr)); } public static Command operator |(Command source, (Action<string> stdOut, Action<string> stdErr) targets) { return source | (PipeTarget.ToDelegate(targets.stdOut), PipeTarget.ToDelegate(targets.stdErr)); } public static Command operator |(PipeSource source, Command target) { return target.WithStandardInputPipe(source); } public static Command operator |(Stream source, Command target) { return PipeSource.FromStream(source) | target; } public static Command operator |(ReadOnlyMemory<byte> source, Command target) { return PipeSource.FromBytes(source) | target; } public static Command operator |(byte[] source, Command target) { return PipeSource.FromBytes(source) | target; } public static Command operator |(string source, Command target) { return PipeSource.FromString(source) | target; } public static Command operator |(Command source, Command target) { return PipeSource.FromCommand(source) | target; } } public class CommandResult { public int ExitCode { get; } public DateTimeOffset StartTime { get; } public DateTimeOffset ExitTime { get; } public TimeSpan RunTime => ExitTime - StartTime; public CommandResult(int exitCode, DateTimeOffset startTime, DateTimeOffset exitTime) { ExitCode = exitCode; StartTime = startTime; ExitTime = exitTime; } } [Flags] public enum CommandResultValidation { None = 0, ZeroExitCode = 1 } internal static class CommandResultValidationExtensions { public static bool IsZeroExitCodeValidationEnabled(this CommandResultValidation validation) { return (validation & CommandResultValidation.ZeroExitCode) != 0; } } public class CommandTask<TResult> : IDisposable { public Task<TResult> Task { get; } public int ProcessId { get; } public CommandTask(Task<TResult> task, int processId) { Task = task; ProcessId = processId; } internal CommandTask<T> Bind<T>(Func<Task<TResult>, Task<T>> transform) { return new CommandTask<T>(transform(Task), ProcessId); } public CommandTask<T> Select<T>(Func<TResult, T> transform) { Func<TResult, T> transform2 = transform; return Bind((Task<TResult> task) => task.Select(transform2)); } public TaskAwaiter<TResult> GetAwaiter() { return Task.GetAwaiter(); } public ConfiguredTaskAwaitable<TResult> ConfigureAwait(bool continueOnCapturedContext) { return Task.ConfigureAwait(continueOnCapturedContext); } public void Dispose() { Task.Dispose(); } public static implicit operator Task<TResult>(CommandTask<TResult> commandTask) { return commandTask.Task; } } public class Credentials { public string? Domain { get; } public string? UserName { get; } public string? Password { get; } public bool LoadUserProfile { get; } public static Credentials Default { get; } = new Credentials(); public Credentials(string? domain = null, string? userName = null, string? password = null, bool loadUserProfile = false) { Domain = domain; UserName = userName; Password = password; LoadUserProfile = loadUserProfile; } [ExcludeFromCodeCoverage] public Credentials(string? domain, string? username, string? password) : this(domain, username, password, loadUserProfile: false) { } } public interface ICommandConfiguration { string TargetFilePath { get; } string Arguments { get; } string WorkingDirPath { get; } Credentials Credentials { get; } IReadOnlyDictionary<string, string?> EnvironmentVariables { get; } CommandResultValidation Validation { get; } PipeSource StandardInputPipe { get; } PipeTarget StandardOutputPipe { get; } PipeTarget StandardErrorPipe { get; } } public abstract class PipeSource { public static PipeSource Null { get; } = Create((Stream _, CancellationToken cancellationToken) => cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : Task.CompletedTask); public abstract Task CopyToAsync(Stream destination, CancellationToken cancellationToken = default(CancellationToken)); public static PipeSource Create(Func<Stream, CancellationToken, Task> handlePipeAsync) { return new <PipeSource>F612AD58C26E22862AC9C5A7F308FD80EC164600953573616E18105DA95EAF684__AnonymousPipeSource(handlePipeAsync); } public static PipeSource Create(Action<Stream> handlePipe) { Action<Stream> handlePipe2 = handlePipe; return Create(delegate(Stream destination, CancellationToken _) { handlePipe2(destination); return Task.CompletedTask; }); } public static PipeSource FromStream(Stream stream, bool autoFlush) { Stream stream2 = stream; return Create(async delegate(Stream destination, CancellationToken cancellationToken) { await stream2.CopyToAsync(destination, autoFlush, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); }); } public static PipeSource FromStream(Stream stream) { return FromStream(stream, autoFlush: true); } public static PipeSource FromFile(string filePath) { string filePath2 = filePath; return Create(async delegate(Stream destination, CancellationToken cancellationToken) { FileStream fileStream = File.OpenRead(filePath2); await using (fileStream.ToAsyncDisposable()) { await fileStream.CopyToAsync(destination, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } }); } public static PipeSource FromBytes(ReadOnlyMemory<byte> data) { return Create(async delegate(Stream destination, CancellationToken cancellationToken) { await destination.WriteAsync(data, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); }); } public static PipeSource FromBytes(byte[] data) { return FromBytes((ReadOnlyMemory<byte>)data); } [Obsolete("Use FromBytes(ReadOnlyMemory<byte>) instead")] [ExcludeFromCodeCoverage] public static PipeSource FromMemory(ReadOnlyMemory<byte> data) { return FromBytes(data); } public static PipeSource FromString(string str, Encoding encoding) { return FromBytes(encoding.GetBytes(str)); } public static PipeSource FromString(string str) { return FromString(str, Console.InputEncoding); } public static PipeSource FromCommand(Command command) { Command command2 = command; return Create(async delegate(Stream destination, CancellationToken cancellationToken) { await command2.WithStandardOutputPipe(PipeTarget.ToStream(destination)).ExecuteAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); }); } } internal class <PipeSource>F612AD58C26E22862AC9C5A7F308FD80EC164600953573616E18105DA95EAF684__AnonymousPipeSource : PipeSource { private readonly Func<Stream, CancellationToken, Task> _copyToAsync; public <PipeSource>F612AD58C26E22862AC9C5A7F308FD80EC164600953573616E18105DA95EAF684__AnonymousPipeSource(Func<Stream, CancellationToken, Task> copyToAsync) { _copyToAsync = copyToAsync; } public override async Task CopyToAsync(Stream destination, CancellationToken cancellationToken = default(CancellationToken)) { await _copyToAsync(destination, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } } public abstract class PipeTarget { public static PipeTarget Null { get; } = Create((Stream _, CancellationToken cancellationToken) => cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : Task.CompletedTask); public abstract Task CopyFromAsync(Stream origin, CancellationToken cancellationToken = default(CancellationToken)); public static PipeTarget Create(Func<Stream, CancellationToken, Task> handlePipeAsync) { return new <PipeTarget>F825283E4191C5E3065EA9B63A9E400DE4BF8A70F67D820C9074D40C0E517F81E__AnonymousPipeTarget(handlePipeAsync); } public static PipeTarget Create(Action<Stream> handlePipe) { Action<Stream> handlePipe2 = handlePipe; return Create(delegate(Stream origin, CancellationToken _) { handlePipe2(origin); return Task.CompletedTask; }); } public static PipeTarget ToStream(Stream stream, bool autoFlush) { Stream stream2 = stream; return Create(async delegate(Stream origin, CancellationToken cancellationToken) { await origin.CopyToAsync(stream2, autoFlush, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); }); } public static PipeTarget ToStream(Stream stream) { return ToStream(stream, autoFlush: true); } public static PipeTarget ToFile(string filePath) { string filePath2 = filePath; return Create(async delegate(Stream origin, CancellationToken cancellationToken) { FileStream fileStream = File.Create(filePath2); await using (fileStream.ToAsyncDisposable()) { await origin.CopyToAsync(fileStream, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } }); } public static PipeTarget ToStringBuilder(StringBuilder stringBuilder, Encoding encoding) { Encoding encoding2 = encoding; StringBuilder stringBuilder2 = stringBuilder; return Create(async delegate(Stream origin, CancellationToken cancellationToken) { using StreamReader reader = new StreamReader(origin, encoding2, detectEncodingFromByteOrderMarks: false, 1024, leaveOpen: true); using IMemoryOwner<char> buffer = MemoryPool<char>.Shared.Rent(1024); while (true) { int num = await reader.ReadAsync(buffer.Memory, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (num <= 0) { break; } stringBuilder2.Append((object?)buffer.Memory.Slice(0, num)); } }); } public static PipeTarget ToStringBuilder(StringBuilder stringBuilder) { return ToStringBuilder(stringBuilder, Console.OutputEncoding); } public static PipeTarget ToDelegate(Func<string, CancellationToken, Task> handleLineAsync, Encoding encoding) { Encoding encoding2 = encoding; Func<string, CancellationToken, Task> handleLineAsync2 = handleLineAsync; return Create(async delegate(Stream origin, CancellationToken cancellationToken) { using StreamReader reader = new StreamReader(origin, encoding2, detectEncodingFromByteOrderMarks: false, 1024, leaveOpen: true); await foreach (string item in reader.ReadAllLinesAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)) { await handleLineAsync2(item, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } }); } public static PipeTarget ToDelegate(Func<string, CancellationToken, Task> handleLineAsync) { return ToDelegate(handleLineAsync, Console.OutputEncoding); } public static PipeTarget ToDelegate(Func<string, Task> handleLineAsync, Encoding encoding) { Func<string, Task> handleLineAsync2 = handleLineAsync; return ToDelegate(async delegate(string line, CancellationToken _) { await handleLineAsync2(line).ConfigureAwait(continueOnCapturedContext: false); }, encoding); } public static PipeTarget ToDelegate(Func<string, Task> handleLineAsync) { return ToDelegate(handleLineAsync, Console.OutputEncoding); } public static PipeTarget ToDelegate(Action<string> handleLine, Encoding encoding) { Action<string> handleLine2 = handleLine; return ToDelegate(delegate(string line) { handleLine2(line); return Task.CompletedTask; }, encoding); } public static PipeTarget ToDelegate(Action<string> handleLine) { return ToDelegate(handleLine, Console.OutputEncoding); } public static PipeTarget Merge(IEnumerable<PipeTarget> targets) { IReadOnlyList<PipeTarget> readOnlyList = OptimizeTargets(targets); if (readOnlyList.Count == 1) { return readOnlyList.Single(); } if (readOnlyList.Count == 0) { return Null; } return new <PipeTarget>F825283E4191C5E3065EA9B63A9E400DE4BF8A70F67D820C9074D40C0E517F81E__AggregatePipeTarget(readOnlyList); static void FlattenTargets(IEnumerable<PipeTarget> targets, ICollection<PipeTarget> output) { foreach (PipeTarget target in targets) { if (target is <PipeTarget>F825283E4191C5E3065EA9B63A9E400DE4BF8A70F67D820C9074D40C0E517F81E__AggregatePipeTarget <PipeTarget>F825283E4191C5E3065EA9B63A9E400DE4BF8A70F67D820C9074D40C0E517F81E__AggregatePipeTarget2) { FlattenTargets(<PipeTarget>F825283E4191C5E3065EA9B63A9E400DE4BF8A70F67D820C9074D40C0E517F81E__AggregatePipeTarget2.Targets, output); } else { output.Add(target); } } } static IReadOnlyList<PipeTarget> OptimizeTargets(IEnumerable<PipeTarget> targets) { List<PipeTarget> list = new List<PipeTarget>(); FlattenTargets(targets, list); list.RemoveAll((PipeTarget t) => t == Null); return list; } } public static PipeTarget Merge(params PipeTarget[] targets) { return Merge((IEnumerable<PipeTarget>)targets); } } internal class <PipeTarget>F825283E4191C5E3065EA9B63A9E400DE4BF8A70F67D820C9074D40C0E517F81E__AnonymousPipeTarget : PipeTarget { private readonly Func<Stream, CancellationToken, Task> _copyFromAsync; public <PipeTarget>F825283E4191C5E3065EA9B63A9E400DE4BF8A70F67D820C9074D40C0E517F81E__AnonymousPipeTarget(Func<Stream, CancellationToken, Task> copyFromAsync) { _copyFromAsync = copyFromAsync; } public override async Task CopyFromAsync(Stream origin, CancellationToken cancellationToken = default(CancellationToken)) { await _copyFromAsync(origin, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } } internal class <PipeTarget>F825283E4191C5E3065EA9B63A9E400DE4BF8A70F67D820C9074D40C0E517F81E__AggregatePipeTarget : PipeTarget { public IReadOnlyList<PipeTarget> Targets { get; } public <PipeTarget>F825283E4191C5E3065EA9B63A9E400DE4BF8A70F67D820C9074D40C0E517F81E__AggregatePipeTarget(IReadOnlyList<PipeTarget> targets) { Targets = targets; } public override async Task CopyFromAsync(Stream origin, CancellationToken cancellationToken = default(CancellationToken)) { CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(new CancellationToken[1] { cancellationToken }); try { Dictionary<PipeTarget, SimplexStream> targetSubStreams = new Dictionary<PipeTarget, SimplexStream>(); foreach (PipeTarget target in Targets) { targetSubStreams[target] = new SimplexStream(); } PipeTarget key; SimplexStream value; try { Task readingTask = Task.WhenAll(targetSubStreams.Select<KeyValuePair<PipeTarget, SimplexStream>, Task>(async delegate(KeyValuePair<PipeTarget, SimplexStream> targetSubStream) { KeyValuePair<PipeTarget, SimplexStream> keyValuePair = targetSubStream; var (pipeTarget2, origin2) = (KeyValuePair<PipeTarget, SimplexStream>)(ref keyValuePair); try { await pipeTarget2.CopyFromAsync(origin2, cts.Token).ConfigureAwait(continueOnCapturedContext: false); } catch { cts.Cancel(); throw; } })); try { using IMemoryOwner<byte> buffer = MemoryPool<byte>.Shared.Rent(81920); while (true) { int bytesRead = await origin.ReadAsync(buffer.Memory, cts.Token).ConfigureAwait(continueOnCapturedContext: false); if (bytesRead <= 0) { break; } foreach (KeyValuePair<PipeTarget, SimplexStream> item in targetSubStreams) { item.Deconstruct(out key, out value); await value.WriteAsync(buffer.Memory.Slice(0, bytesRead), cts.Token).ConfigureAwait(continueOnCapturedContext: false); } } foreach (KeyValuePair<PipeTarget, SimplexStream> item2 in targetSubStreams) { item2.Deconstruct(out key, out value); await value.ReportCompletionAsync(cts.Token).ConfigureAwait(continueOnCapturedContext: false); } } finally { await readingTask.ConfigureAwait(continueOnCapturedContext: false); } } finally { foreach (KeyValuePair<PipeTarget, SimplexStream> item3 in targetSubStreams) { item3.Deconstruct(out key, out value); await value.ToAsyncDisposable().DisposeAsync().ConfigureAwait(continueOnCapturedContext: false); } } } finally { if (cts != null) { ((IDisposable)cts).Dispose(); } } } } } namespace CliWrap.Utils { internal static class BufferSizes { public const int Stream = 81920; public const int StreamReader = 1024; } internal class Channel<T> : IDisposable { private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1); private readonly SemaphoreSlim _readLock = new SemaphoreSlim(0, 1); private bool _isItemAvailable; private T _item; public async Task PublishAsync(T item, CancellationToken cancellationToken = default(CancellationToken)) { await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); _item = item; _isItemAvailable = true; _readLock.Release(); } public async IAsyncEnumerable<T> ReceiveAsync([EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken)) { while (true) { await _readLock.WaitAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (!_isItemAvailable) { break; } yield return _item; _isItemAvailable = false; _writeLock.Release(); } } public async Task ReportCompletionAsync(CancellationToken cancellationToken = default(CancellationToken)) { await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); _item = default(T); _isItemAvailable = false; _readLock.Release(); } public void Dispose() { _writeLock.Dispose(); _readLock.Dispose(); } } internal class Disposable : IDisposable { private readonly Action _dispose; public static IDisposable Null { get; } = Create(delegate { }); public Disposable(Action dispose) { _dispose = dispose; } public void Dispose() { _dispose(); } public static IDisposable Create(Action dispose) { return new Disposable(dispose); } } internal static class EnvironmentEx { private static readonly Lazy<string?> ProcessPathLazy = new Lazy<string>(delegate { using Process process = Process.GetCurrentProcess(); return process.MainModule?.FileName; }); public static string? ProcessPath => ProcessPathLazy.Value; } internal static class NativeMethods { public static class Unix { [DllImport("libc", EntryPoint = "kill", SetLastError = true)] public static extern int Kill(int pid, int sig); } } internal class <Observable>F9A56BC066C1C55331A426EEC55B608B3C789C113870FC381D9D496607E7DCF71__SynchronizedObserver<T> : IObserver<T> { private readonly IObserver<T> _observer; private readonly object _syncRoot; public <Observable>F9A56BC066C1C55331A426EEC55B608B3C789C113870FC381D9D496607E7DCF71__SynchronizedObserver(IObserver<T> observer, object? syncRoot = null) { _observer = observer; _syncRoot = syncRoot ?? new object(); } public void OnCompleted() { lock (_syncRoot) { _observer.OnCompleted(); } } public void OnError(Exception error) { lock (_syncRoot) { _observer.OnError(error); } } public void OnNext(T value) { lock (_syncRoot) { _observer.OnNext(value); } } } internal class <Observable>F9A56BC066C1C55331A426EEC55B608B3C789C113870FC381D9D496607E7DCF71__Observable<T> : IObservable<T> { private readonly Func<IObserver<T>, IDisposable> _subscribe; public <Observable>F9A56BC066C1C55331A426EEC55B608B3C789C113870FC381D9D496607E7DCF71__Observable(Func<IObserver<T>, IDisposable> subscribe) { _subscribe = subscribe; } public IDisposable Subscribe(IObserver<T> observer) { return _subscribe(new <Observable>F9A56BC066C1C55331A426EEC55B608B3C789C113870FC381D9D496607E7DCF71__SynchronizedObserver<T>(observer)); } } internal static class Observable { public static IObservable<T> Create<T>(Func<IObserver<T>, IDisposable> subscribe) { return new <Observable>F9A56BC066C1C55331A426EEC55B608B3C789C113870FC381D9D496607E7DCF71__Observable<T>(subscribe); } } internal class ProcessEx : IDisposable { private readonly Process _nativeProcess; private readonly TaskCompletionSource<object?> _exitTcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously); public int Id => _nativeProcess.Id; public string Name => Path.GetFileName(_nativeProcess.StartInfo.FileName); public Stream StandardInput => _nativeProcess.StandardInput.BaseStream; public Stream StandardOutput => _nativeProcess.StandardOutput.BaseStream; public Stream StandardError => _nativeProcess.StandardError.BaseStream; public DateTimeOffset StartTime { get; private set; } public DateTimeOffset ExitTime { get; private set; } public int ExitCode => _nativeProcess.ExitCode; public ProcessEx(ProcessStartInfo startInfo) { _nativeProcess = new Process { StartInfo = startInfo }; } public void Start() { _nativeProcess.EnableRaisingEvents = true; _nativeProcess.Exited += delegate { ExitTime = DateTimeOffset.Now; _exitTcs.TrySetResult(null); }; try { if (!_nativeProcess.Start()) { throw new InvalidOperationException("Failed to start a process with file path '" + _nativeProcess.StartInfo.FileName + "'. Target file is not an executable or lacks execute permissions."); } StartTime = DateTimeOffset.Now; } catch (Win32Exception innerException) { throw new Win32Exception("Failed to start a process with file path '" + _nativeProcess.StartInfo.FileName + "'. Target file or working directory doesn't exist, or the provided credentials are invalid.", innerException); } } public void Interrupt() { if (!TryInterrupt()) { Kill(); } bool TryInterrupt() { try { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { using (WindowsSignaler windowsSignaler = WindowsSignaler.Deploy()) { return windowsSignaler.TrySend(_nativeProcess.Id, 0); } } if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { return NativeMethods.Unix.Kill(_nativeProcess.Id, 2) == 0; } return false; } catch { return false; } } } public void Kill() { try { PolyfillExtensions.Kill(_nativeProcess, entireProcessTree: true); } catch when (_nativeProcess.HasExited) { } catch { } } public async Task WaitUntilExitAsync(CancellationToken cancellationToken = default(CancellationToken)) { await using (cancellationToken.Register(delegate { _exitTcs.TrySetCanceled(cancellationToken); }).ToAsyncDisposable()) { await _exitTcs.Task.ConfigureAwait(continueOnCapturedContext: false); } } public void Dispose() { _nativeProcess.Dispose(); } } internal class SimplexStream : Stream { private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1); private readonly SemaphoreSlim _readLock = new SemaphoreSlim(0, 1); private IMemoryOwner<byte> _sharedBuffer = MemoryPool<byte>.Shared.Rent(81920); private int _sharedBufferBytes; private int _sharedBufferBytesRead; [ExcludeFromCodeCoverage] public override bool CanRead => true; [ExcludeFromCodeCoverage] public override bool CanSeek => false; [ExcludeFromCodeCoverage] public override bool CanWrite => true; [ExcludeFromCodeCoverage] public override long Position { get; set; } [ExcludeFromCodeCoverage] public override long Length { get { throw new NotSupportedException(); } } public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (_sharedBuffer.Memory.Length < count) { _sharedBuffer.Dispose(); _sharedBuffer = MemoryPool<byte>.Shared.Rent(count); } buffer.AsSpan(offset, count).CopyTo(_sharedBuffer.Memory.Span); _sharedBufferBytes = count; _sharedBufferBytesRead = 0; _readLock.Release(); } public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { await _readLock.WaitAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); int num = Math.Min(count, _sharedBufferBytes - _sharedBufferBytesRead); _sharedBuffer.Memory.Slice(_sharedBufferBytesRead, num).CopyTo(buffer.AsMemory(offset, num)); _sharedBufferBytesRead += num; if (_sharedBufferBytesRead >= _sharedBufferBytes) { _writeLock.Release(); } else { _readLock.Release(); } return num; } public async Task ReportCompletionAsync(CancellationToken cancellationToken = default(CancellationToken)) { await WriteAsync(Array.Empty<byte>(), 0, 0, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } protected override void Dispose(bool disposing) { if (disposing) { _readLock.Dispose(); _writeLock.Dispose(); _sharedBuffer.Dispose(); } base.Dispose(disposing); } [ExcludeFromCodeCoverage] public override int Read(byte[] buffer, int offset, int count) { return ReadAsync(buffer, offset, count).GetAwaiter().GetResult(); } [ExcludeFromCodeCoverage] public override void Write(byte[] buffer, int offset, int count) { WriteAsync(buffer, offset, count).GetAwaiter().GetResult(); } [ExcludeFromCodeCoverage] public override void Flush() { throw new NotSupportedException(); } [ExcludeFromCodeCoverage] public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } [ExcludeFromCodeCoverage] public override void SetLength(long value) { throw new NotSupportedException(); } } internal class WindowsSignaler : IDisposable { private readonly string _filePath; public WindowsSignaler(string filePath) { _filePath = filePath; } public bool TrySend(int processId, int signalId) { Process process = new Process(); ProcessStartInfo processStartInfo = new ProcessStartInfo(); processStartInfo.FileName = _filePath; processStartInfo.Arguments = processId.ToString(CultureInfo.InvariantCulture) + " " + signalId.ToString(CultureInfo.InvariantCulture); processStartInfo.CreateNoWindow = true; processStartInfo.UseShellExecute = false; processStartInfo.Environment["COMPLUS_OnlyUseLatestCLR"] = "1"; process.StartInfo = processStartInfo; using Process process2 = process; if (!process2.Start()) { return false; } if (!process2.WaitForExit(30000)) { return false; } return process2.ExitCode == 0; } public void Dispose() { try { File.Delete(_filePath); } catch { } } public static WindowsSignaler Deploy() { string text = Path.ChangeExtension(Path.GetTempFileName(), "exe"); Assembly.GetExecutingAssembly().ExtractManifestResource("CliWrap.Signaler.exe", text); return new WindowsSignaler(text); } } } namespace CliWrap.Utils.Extensions { internal static class AssemblyExtensions { public static void ExtractManifestResource(this Assembly assembly, string resourceName, string destFilePath) { Stream stream = assembly.GetManifestResourceStream(resourceName) ?? throw new MissingManifestResourceException("Could not find resource '" + resourceName + "'."); using FileStream destination = File.Create(destFilePath); stream.CopyTo(destination); } } internal static class AsyncDisposableExtensions { private readonly struct AsyncDisposableAdapter : IAsyncDisposable { private readonly IDisposable _target; public AsyncDisposableAdapter(IDisposable target) { _target = target; } public async ValueTask DisposeAsync() { if (_target is IAsyncDisposable asyncDisposable) { await asyncDisposable.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false); } else { _target.Dispose(); } } } public static IAsyncDisposable ToAsyncDisposable(this IDisposable disposable) { return new AsyncDisposableAdapter(disposable); } } internal static class CancellationTokenExtensions { public static void ThrowIfCancellationRequested(this CancellationToken cancellationToken, string message) { if (!cancellationToken.IsCancellationRequested) { return; } throw new OperationCanceledException(message, cancellationToken); } } internal static class ExceptionExtensions { public static Exception? TryGetSingle(this AggregateException exception) { ReadOnlyCollection<Exception> innerExceptions = exception.Flatten().InnerExceptions; if (innerExceptions.Count != 1) { return null; } return innerExceptions.Single(); } } internal static class StreamExtensions { public static async Task CopyToAsync(this Stream source, Stream destination, bool autoFlush, CancellationToken cancellationToken = default(CancellationToken)) { using IMemoryOwner<byte> buffer = MemoryPool<byte>.Shared.Rent(81920); while (true) { int num = await source.ReadAsync(buffer.Memory, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (num <= 0) { break; } await destination.WriteAsync(buffer.Memory.Slice(0, num), cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (autoFlush) { await destination.FlushAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } } } public static async IAsyncEnumerable<string> ReadAllLinesAsync(this StreamReader reader, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken)) { StringBuilder lineBuffer = new StringBuilder(); using IMemoryOwner<char> buffer = MemoryPool<char>.Shared.Rent(1024); bool isLastCaretReturn = false; while (true) { int charsRead = await reader.ReadAsync(buffer.Memory, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (charsRead <= 0) { break; } for (int i = 0; i < charsRead; i++) { char c = buffer.Memory.Span[i]; if (isLastCaretReturn && c == '\n') { isLastCaretReturn = false; continue; } char c2 = c; if ((c2 == '\n' || c2 == '\r') ? true : false) { yield return lineBuffer.ToString(); lineBuffer.Clear(); } else { lineBuffer.Append(c); } isLastCaretReturn = c == '\r'; } } if (lineBuffer.Length > 0) { yield return lineBuffer.ToString(); } } } internal static class StringExtensions { public static SecureString ToSecureString(this string str) { SecureString secureString = new SecureString(); foreach (char c in str) { secureString.AppendChar(c); } secureString.MakeReadOnly(); return secureString; } } internal static class TaskExtensions { public static async Task<TDestination> Select<TSource, TDestination>(this Task<TSource> task, Func<TSource, TDestination> transform) { return transform(await task.ConfigureAwait(continueOnCapturedContext: false)); } } } namespace CliWrap.Exceptions { public abstract class CliWrapException : Exception { protected CliWrapException(string message, Exception? innerException) : base(message, innerException) { } [ExcludeFromCodeCoverage] protected CliWrapException(string message) : this(message, null) { } } public class CommandExecutionException : CliWrapException { public ICommandConfiguration Command { get; } public int ExitCode { get; } public CommandExecutionException(ICommandConfiguration command, int exitCode, string message, Exception? innerException) : base(message, innerException) { Command = command; ExitCode = exitCode; } [ExcludeFromCodeCoverage] public CommandExecutionException(ICommandConfiguration command, int exitCode, string message) : this(command, exitCode, message, null) { } } } namespace CliWrap.EventStream { public abstract class CommandEvent { } public class StartedCommandEvent : CommandEvent { public int ProcessId { get; } public StartedCommandEvent(int processId) { ProcessId = processId; } [ExcludeFromCodeCoverage] public override string ToString() { return $"Process ID: {ProcessId}"; } } public class StandardOutputCommandEvent : CommandEvent { public string Text { get; } public StandardOutputCommandEvent(string text) { Text = text; } [ExcludeFromCodeCoverage] public override string ToString() { return Text; } } public class StandardErrorCommandEvent : CommandEvent { public string Text { get; } public StandardErrorCommandEvent(string text) { Text = text; } [ExcludeFromCodeCoverage] public override string ToString() { return Text; } } public class ExitedCommandEvent : CommandEvent { public int ExitCode { get; } public ExitedCommandEvent(int exitCode) { ExitCode = exitCode; } [ExcludeFromCodeCoverage] public override string ToString() { return $"Exit code: {ExitCode}"; } } public static class EventStreamCommandExtensions { public static async IAsyncEnumerable<CommandEvent> ListenAsync(this Command command, Encoding standardOutputEncoding, Encoding standardErrorEncoding, [EnumeratorCancellation] CancellationToken forcefulCancellationToken, CancellationToken gracefulCancellationToken) { Channel<CommandEvent> channel = new Channel<CommandEvent>(); try { PipeTarget target = PipeTarget.Merge(command.StandardOutputPipe, PipeTarget.ToDelegate(async delegate(string line, CancellationToken innerCancellationToken) { await channel.PublishAsync(new StandardOutputCommandEvent(line), innerCancellationToken).ConfigureAwait(continueOnCapturedContext: false); }, standardOutputEncoding)); PipeTarget target2 = PipeTarget.Merge(command.StandardErrorPipe, PipeTarget.ToDelegate(async delegate(string line, CancellationToken innerCancellationToken) { await channel.PublishAsync(new StandardErrorCommandEvent(line), innerCancellationToken).ConfigureAwait(continueOnCapturedContext: false); }, standardErrorEncoding)); Command command2 = command.WithStandardOutputPipe(target).WithStandardErrorPipe(target2); CommandTask<CommandResult> commandTask = command2.ExecuteAsync(forcefulCancellationToken, gracefulCancellationToken); yield return new StartedCommandEvent(commandTask.ProcessId); commandTask.Task.ContinueWith((Func<Task<CommandResult>, Task>)async delegate { await channel.ReportCompletionAsync(forcefulCancellationToken).ConfigureAwait(continueOnCapturedContext: false); }, TaskContinuationOptions.None); await foreach (CommandEvent item in channel.ReceiveAsync(forcefulCancellationToken).ConfigureAwait(continueOnCapturedContext: false)) { yield return item; } yield return new ExitedCommandEvent(await commandTask.Select((CommandResult r) => r.ExitCode).ConfigureAwait(continueOnCapturedContext: false)); } finally { if (channel != null) { ((IDisposable)channel).Dispose(); } } } public static IAsyncEnumerable<CommandEvent> ListenAsync(this Command command, Encoding standardOutputEncoding, Encoding standardErrorEncoding, CancellationToken cancellationToken = default(CancellationToken)) { return command.ListenAsync(standardOutputEncoding, standardErrorEncoding, cancellationToken, CancellationToken.None); } public static IAsyncEnumerable<CommandEvent> ListenAsync(this Command command, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken)) { return command.ListenAsync(encoding, encoding, cancellationToken); } public static IAsyncEnumerable<CommandEvent> ListenAsync(this Command command, CancellationToken cancellationToken = default(CancellationToken)) { return command.ListenAsync(Console.OutputEncoding, cancellationToken); } public static IObservable<CommandEvent> Observe(this Command command, Encoding standardOutputEncoding, Encoding standardErrorEncoding, CancellationToken forcefulCancellationToken, CancellationToken gracefulCancellationToken) { Command command2 = command; Encoding standardOutputEncoding2 = standardOutputEncoding; Encoding standardErrorEncoding2 = standardErrorEncoding; return Observable.Create(delegate(IObserver<CommandEvent> observer) { IObserver<CommandEvent> observer2 = observer; PipeTarget target = PipeTarget.Merge(command2.StandardOutputPipe, PipeTarget.ToDelegate(delegate(string line) { observer2.OnNext(new StandardOutputCommandEvent(line)); }, standardOutputEncoding2)); PipeTarget target2 = PipeTarget.Merge(command2.StandardErrorPipe, PipeTarget.ToDelegate(delegate(string line) { observer2.OnNext(new StandardErrorCommandEvent(line)); }, standardErrorEncoding2)); CommandTask<CommandResult> commandTask = command2.WithStandardOutputPipe(target).WithStandardErrorPipe(target2).ExecuteAsync(forcefulCancellationToken, gracefulCancellationToken); observer2.OnNext(new StartedCommandEvent(commandTask.ProcessId)); commandTask.Task.ContinueWith(delegate(Task<CommandResult> t) { if (t.IsCanceled) { observer2.OnError(new TaskCanceledException(t)); } else if (t.Exception != null) { observer2.OnError(t.Exception.TryGetSingle() ?? t.Exception); } else { observer2.OnNext(new ExitedCommandEvent(t.Result.ExitCode)); observer2.OnCompleted(); } }, TaskContinuationOptions.None); return Disposable.Null; }); } public static IObservable<CommandEvent> Observe(this Command command, Encoding standardOutputEncoding, Encoding standardErrorEncoding, CancellationToken cancellationToken = default(CancellationToken)) { return command.Observe(standardOutputEncoding, standardErrorEncoding, cancellationToken, CancellationToken.None); } public static IObservable<CommandEvent> Observe(this Command command, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken)) { return command.Observe(encoding, encoding, cancellationToken); } public static IObservable<CommandEvent> Observe(this Command command, CancellationToken cancellationToken = default(CancellationToken)) { return command.Observe(Console.OutputEncoding, cancellationToken); } } } namespace CliWrap.Builders { public class ArgumentsBuilder { private static readonly IFormatProvider DefaultFormatProvider = CultureInfo.InvariantCulture; private readonly StringBuilder _buffer = new StringBuilder(); public ArgumentsBuilder Add(string value, bool escape) { if (_buffer.Length > 0) { _buffer.Append(' '); } _buffer.Append(escape ? Escape(value) : value); return this; } public ArgumentsBuilder Add(string value) { return Add(value, escape: true); } public ArgumentsBuilder Add(IEnumerable<string> values, bool escape) { foreach (string value in values) { Add(value, escape); } return this; } public ArgumentsBuilder Add(IEnumerable<string> values) { return Add(values, escape: true); } public ArgumentsBuilder Add(IFormattable value, IFormatProvider formatProvider, bool escape = true) { return Add(value.ToString(null, formatProvider), escape); } public ArgumentsBuilder Add(IFormattable value, CultureInfo cultureInfo, bool escape) { return Add(value, (IFormatProvider)cultureInfo, escape); } public ArgumentsBuilder Add(IFormattable value, CultureInfo cultureInfo) { return Add(value, cultureInfo, escape: true); } public ArgumentsBuilder Add(IFormattable value, bool escape) { return Add(value, DefaultFormatProvider, escape); } public ArgumentsBuilder Add(IFormattable value) { return Add(value, escape: true); } public ArgumentsBuilder Add(IEnumerable<IFormattable> values, IFormatProvider formatProvider, bool escape = true) { foreach (IFormattable value in values) { Add(value, formatProvider, escape); } return this; } public ArgumentsBuilder Add(IEnumerable<IFormattable> values, CultureInfo cultureInfo, bool escape) { return Add(values, (IFormatProvider)cultureInfo, escape); } public ArgumentsBuilder Add(IEnumerable<IFormattable> values, CultureInfo cultureInfo) { return Add(values, cultureInfo, escape: true); } public ArgumentsBuilder Add(IEnumerable<IFormattable> values, bool escape) { return Add(values, DefaultFormatProvider, escape); } public ArgumentsBuilder Add(IEnumerable<IFormattable> values) { return Add(values, escape: true); } public string Build() { return _buffer.ToString(); } private static string Escape(string argument) { if (argument.Length > 0 && argument.All((char c) => !char.IsWhiteSpace(c) && c != '"')) { return argument; } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append('"'); int i = 0; while (i < argument.Length) { char c2 = argument[i++]; switch (c2) { case '\\': { int num = 1; for (; i < argument.Length && argument[i] == '\\'; i++) { num++; } if (i == argument.Length) { stringBuilder.Append('\\', num * 2); } else if (argument[i] == '"') { stringBuilder.Append('\\', num * 2 + 1).Append('"'); i++; } else { stringBuilder.Append('\\', num); } break; } case '"': stringBuilder.Append('\\').Append('"'); break; default: stringBuilder.Append(c2); break; } } stringBuilder.Append('"'); return stringBuilder.ToString(); } } public class CredentialsBuilder { private string? _domain; private string? _userName; private string? _password; private bool _loadUserProfile; public CredentialsBuilder SetDomain(string? domain) { _domain = domain; return this; } public CredentialsBuilder SetUserName(string? userName) { _userName = userName; return this; } public CredentialsBuilder SetPassword(string? password) { _password = password; return this; } public CredentialsBuilder LoadUserProfile(bool loadUserProfile = true) { _loadUserProfile = loadUserProfile; return this; } public Credentials Build() { return new Credentials(_domain, _userName, _password, _loadUserProfile); } } public class EnvironmentVariablesBuilder { private readonly Dictionary<string, string?> _envVars = new Dictionary<string, string>(StringComparer.Ordinal); public EnvironmentVariablesBuilder Set(string name, string? value) { _envVars[name] = value; return this; } public EnvironmentVariablesBuilder Set(IEnumerable<KeyValuePair<string, string?>> variables) { foreach (var (name, value) in variables) { Set(name, value); } return this; } public EnvironmentVariablesBuilder Set(IReadOnlyDictionary<string, string?> variables) { return Set((IEnumerable<KeyValuePair<string, string?>>)variables); } public IReadOnlyDictionary<string, string?> Build() { return new Dictionary<string, string>(_envVars, _envVars.Comparer); } } } namespace CliWrap.Buffered { public static class BufferedCommandExtensions { public static CommandTask<BufferedCommandResult> ExecuteBufferedAsync(this Command command, Encoding standardOutputEncoding, Encoding standardErrorEncoding, CancellationToken forcefulCancellationToken, CancellationToken gracefulCancellationToken) { StringBuilder stdOutBuffer = new StringBuilder(); StringBuilder stdErrBuffer = new StringBuilder(); PipeTarget target = PipeTarget.Merge(command.StandardOutputPipe, PipeTarget.ToStringBuilder(stdOutBuffer, standardOutputEncoding)); PipeTarget target2 = PipeTarget.Merge(command.StandardErrorPipe, PipeTarget.ToStringBuilder(stdErrBuffer, standardErrorEncoding)); return command.WithStandardOutputPipe(target).WithStandardErrorPipe(target2).ExecuteAsync(forcefulCancellationToken, gracefulCancellationToken) .Bind(async delegate(Task<CommandResult> task) { try { CommandResult commandResult = await task; return new BufferedCommandResult(commandResult.ExitCode, commandResult.StartTime, commandResult.ExitTime, stdOutBuffer.ToString(), stdErrBuffer.ToString()); } catch (CommandExecutionException ex) { throw new CommandExecutionException(ex.Command, ex.ExitCode, "Command execution failed, see the inner exception for details.\r\n\r\nStandard error:\r\n" + stdErrBuffer.ToString().Trim(), ex); } }); } public static CommandTask<BufferedCommandResult> ExecuteBufferedAsync(this Command command, Encoding standardOutputEncoding, Encoding standardErrorEncoding, CancellationToken cancellationToken = default(CancellationToken)) { return command.ExecuteBufferedAsync(standardOutputEncoding, standardErrorEncoding, cancellationToken, CancellationToken.None); } public static CommandTask<BufferedCommandResult> ExecuteBufferedAsync(this Command command, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken)) { return command.ExecuteBufferedAsync(encoding, encoding, cancellationToken); } public static CommandTask<BufferedCommandResult> ExecuteBufferedAsync(this Command command, CancellationToken cancellationToken = default(CancellationToken)) { return command.ExecuteBufferedAsync(Console.OutputEncoding, cancellationToken); } } public class BufferedCommandResult : CommandResult { public string StandardOutput { get; } public string StandardError { get; } public BufferedCommandResult(int exitCode, DateTimeOffset startTime, DateTimeOffset exitTime, string standardOutput, string standardError) : base(exitCode, startTime, exitTime) { StandardOutput = standardOutput; StandardError = standardError; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Constructor)] [ExcludeFromCodeCoverage] internal class SetsRequiredMembersAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)] [ExcludeFromCodeCoverage] internal class StringSyntaxAttribute : Attribute { public const string CompositeFormat = "CompositeFormat"; public const string DateOnlyFormat = "DateOnlyFormat"; public const string DateTimeFormat = "DateTimeFormat"; public const string EnumFormat = "EnumFormat"; public const string GuidFormat = "GuidFormat"; public const string Json = "Json"; public const string NumericFormat = "NumericFormat"; public const string Regex = "Regex"; public const string TimeOnlyFormat = "TimeOnlyFormat"; public const string TimeSpanFormat = "TimeSpanFormat"; public const string Uri = "Uri"; public const string Xml = "Xml"; public string Syntax { get; } public object?[] Arguments { get; } public StringSyntaxAttribute(string syntax, params object?[] arguments) { Syntax = syntax; Arguments = arguments; } public StringSyntaxAttribute(string syntax) : this(syntax, new object[0]) { } } } namespace System.Linq { internal static class PolyfillExtensions { public static T ElementAt<T>(this IEnumerable<T> source, Index index) { if (index.IsFromEnd) { ICollection<T> collection = (source as ICollection<T>) ?? source.ToArray(); return collection.ElementAt(collection.Count - index.Value); } return source.ElementAt(index.Value); } public static T? ElementAtOrDefault<T>(this IEnumerable<T> source, Index index) { if (index.IsFromEnd) { ICollection<T> collection = (source as ICollection<T>) ?? source.ToArray(); return collection.ElementAtOrDefault(collection.Count - index.Value); } return source.ElementAtOrDefault(index.Value); } public static T FirstOrDefault<T>(this IEnumerable<T> source, T defaultValue) { using IEnumerator<T> enumerator = source.GetEnumerator(); if (enumerator.MoveNext()) { return enumerator.Current; } return defaultValue; } public static T FirstOrDefault<T>(this IEnumerable<T> source, Func<T, bool> predicate, T defaultValue) { foreach (T item in source) { if (predicate(item)) { return item; } } return defaultValue; } public static T LastOrDefault<T>(this IEnumerable<T> source, T defaultValue) { T result = defaultValue; foreach (T item in source) { result = item; } return result; } public static T LastOrDefault<T>(this IEnumerable<T> source, Func<T, bool> predicate, T defaultValue) { T result = defaultValue; foreach (T item in source) { if (predicate(item)) { result = item; } } return result; } public static T SingleOrDefault<T>(this IEnumerable<T> source, T defaultValue) { T result = defaultValue; bool flag = false; foreach (T item in source) { if (flag) { throw new InvalidOperationException("Sequence contains more than one element."); } result = item; flag = true; } return result; } public static T SingleOrDefault<T>(this IEnumerable<T> source, Func<T, bool> predicate, T defaultValue) { T result = defaultValue; bool flag = false; foreach (T item in source) { if (predicate(item)) { if (flag) { throw new InvalidOperationException("Sequence contains more than one element."); } result = item; flag = true; } } return result; } public static IEnumerable<T> Take<T>(this IEnumerable<T> source, Range range) { ICollection<T> collection = (source as ICollection<T>) ?? source.ToArray(); var (count, count2) = range.GetOffsetAndLength(collection.Count); return collection.Skip(count).Take(count2); } public static T? Min<T>(this IEnumerable<T> source, IComparer<T>? comparer) { return source.OrderBy((T x) => x, comparer).FirstOrDefault(); } public static T? MinBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector, IComparer<TKey>? comparer) { return source.OrderBy(keySelector, comparer).FirstOrDefault(); } public static T? MinBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector) { return MinBy(source, keySelector, Comparer<TKey>.Default); } public static T? Max<T>(this IEnumerable<T> source, IComparer<T>? comparer) { return source.OrderByDescending((T x) => x, comparer).FirstOrDefault(); } public static T? MaxBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector, IComparer<TKey>? comparer) { return source.OrderByDescending(keySelector, comparer).FirstOrDefault(); } public static T? MaxBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector) { return MaxBy(source, keySelector, Comparer<TKey>.Default); } public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector, IEqualityComparer<TKey>? comparer) { return from x in source.GroupBy(keySelector, comparer) select x.First(); } public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector) { return DistinctBy(source, keySelector, EqualityComparer<TKey>.Default); } public static IEnumerable<T> ExceptBy<T, TKey>(this IEnumerable<T> source, IEnumerable<TKey> other, Func<T, TKey> keySelector, IEqualityComparer<TKey>? comparer) { HashSet<TKey> set = new HashSet<TKey>(other, comparer); foreach (T item in source) { if (!set.Contains(keySelector(item))) { yield return item; } } } public static IEnumerable<T> ExceptBy<T, TKey>(this IEnumerable<T> source, IEnumerable<TKey> other, Func<T, TKey> keySelector) { return ExceptBy(source, other, keySelector, EqualityComparer<TKey>.Default); } public static IEnumerable<T> IntersectBy<T, TKey>(this IEnumerable<T> source, IEnumerable<TKey> other, Func<T, TKey> keySelector, IEqualityComparer<TKey>? comparer) { HashSet<TKey> set = new HashSet<TKey>(other, comparer); foreach (T item in source) { if (set.Contains(keySelector(item))) { yield return item; } } } public static IEnumerable<T> IntersectBy<T, TKey>(this IEnumerable<T> source, IEnumerable<TKey> other, Func<T, TKey> keySelector) { return IntersectBy(source, other, keySelector, EqualityComparer<TKey>.Default); } public static IEnumerable<T> UnionBy<T, TKey>(this IEnumerable<T> source, IEnumerable<T> other, Func<T, TKey> keySelector, IEqualityComparer<TKey>? comparer) { HashSet<TKey> set = new HashSet<TKey>(comparer); foreach (T item in source) { if (set.Add(keySelector(item))) { yield return item; } } foreach (T item2 in other) { if (set.Add(keySelector(item2))) { yield return item2; } } } public static IEnumerable<T> UnionBy<T, TKey>(this IEnumerable<T> source, IEnumerable<T> other, Func<T, TKey> keySelector) { return UnionBy(source, other, keySelector, EqualityComparer<TKey>.Default); } public static IEnumerable<T[]> Chunk<T>(this IEnumerable<T> source, int size) { List<T> chunk = new List<T>(size); foreach (T item in source) { chunk.Add(item); if (chunk.Count == size) { yield return chunk.ToArray(); chunk.Clear(); } } if (chunk.Count > 0) { yield return chunk.ToArray(); } } public static IOrderedEnumerable<T> Order<T>(this IEnumerable<T> source, IComparer<T>? comparer) { return source.OrderBy((T x) => x, comparer); } public static IOrderedEnumerable<T> Order<T>(this IEnumerable<T> source) { return source.Order(Comparer<T>.Default); } public static IOrderedEnumerable<T> OrderDescending<T>(this IEnumerable<T> source, IComparer<T>? comparer) { return source.OrderByDescending((T x) => x, comparer); } public static IOrderedEnumerable<T> OrderDescending<T>(this IEnumerable<T> source) { return source.OrderDescending(Comparer<T>.Default); } public static IEnumerable<(TFirst left, TSecond right)> Zip<TFirst, TSecond>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second) { return first.Zip(second, (TFirst x, TSecond y) => (x, y)); } } } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, Inherited = false)] [ExcludeFromCodeCoverage] internal class LibraryImportAttribute : Attribute { public string LibraryName { get; } public string? EntryPoint { get; init; } public bool SetLastError { get; init; } public StringMarshalling StringMarshalling { get; init; } public Type? StringMarshallingCustomType { get; init; } public LibraryImportAttribute(string libraryName) { LibraryName = libraryName; } } internal enum StringMarshalling { Custom, Utf8, Utf16 } } namespace System.Runtime.CompilerServices { [ExcludeFromCodeCoverage] internal static class IsExternalInit { } [AttributeUsage(AttributeTargets.Method, Inherited = false)] [ExcludeFromCodeCoverage] internal class ModuleInitializerAttribute : Attribute { } [AttributeUsage(AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Interface, Inherited = false)] [ExcludeFromCodeCoverage] internal class SkipLocalsInitAttribute : Attribute { } [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] [ExcludeFromCodeCoverage] internal class CompilerFeatureRequiredAttribute : Attribute { public const string RefStructs = "RefStructs"; public const string RequiredMembers = "RequiredMembers"; public string FeatureName { get; } public bool IsOptional { get; init; } public CompilerFeatureRequiredAttribute(string featureName) { FeatureName = featureName; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field, Inherited = false)] [ExcludeFromCodeCoverage] internal class RequiredMemberAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter)] [ExcludeFromCodeCoverage] internal class CallerArgumentExpressionAttribute : Attribute { public string ParameterName { get; } public CallerArgumentExpressionAttribute(string parameterName) { ParameterName = parameterName; } } } namespace System.Threading.Tasks { internal static class PolyfillExtensions { } } namespace System.Net.Http { internal static class PolyfillExtensions { } } namespace System.Management { internal static class PolyfillExtensions { } } namespace System.IO { internal static class PolyfillExtensions { } }
CustomRadio.dll
Decompiled 2 years agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using BepInEx; using BepInEx.Configuration; using CustomRadio.Configuration; using Microsoft.CodeAnalysis; using YoutubeExplode; using YoutubeExplode.Common; using YoutubeExplode.Converter; using YoutubeExplode.Playlists; using YoutubeExplode.Videos; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("CustomRadio")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("My first plugin")] [assembly: AssemblyFileVersion("0.0.1.0")] [assembly: AssemblyInformationalVersion("0.0.1")] [assembly: AssemblyProduct("CustomRadio")] [assembly: AssemblyTitle("CustomRadio")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.0.1.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 CustomRadio { [BepInPlugin("com.zerouni.CustomRadio", "CustomRadio", "0.0.1")] public class Radio : BaseUnityPlugin { private string songPath = Path.Combine(Paths.PluginPath, "zerouni-CustomRadio", "Custom Songs"); private string ffmpegPath = Path.Combine(Paths.PluginPath, "zerouni-CustomRadio", "ffmpeg.exe"); private string boomboxPath = Path.Combine(Paths.BepInExRootPath, "Custom Songs", "Boombox Music"); private static readonly YoutubeClient youtube = new YoutubeClient(); private async Task Awake() { ((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin CustomRadio is loaded!"); CreatePluginCustomSongsFolder(); Config.Init(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Downloading music..."); Task task = CreateMusic(); await task; ((BaseUnityPlugin)this).Logger.LogInfo((object)"Music downloaded!"); } private void CreatePluginCustomSongsFolder() { if (!Directory.Exists(songPath)) { Directory.CreateDirectory(songPath); } if (!Directory.Exists(boomboxPath)) { Directory.CreateDirectory(boomboxPath); } } private (string, string) createNamesFromTitle(PlaylistVideo video, string source) { string input = Regex.Replace(video.Title, "\\W+", "_"); input = Regex.Replace(input, "_+", "_"); string item = Path.Combine(source, input + ".mp3"); string item2 = Path.Combine(boomboxPath, input + ".mp3"); return (item, item2); } private void copyFile(string source, string destination) { ((BaseUnityPlugin)this).Logger.LogInfo((object)("Copying " + source + " to " + destination)); if (File.Exists(destination)) { ((BaseUnityPlugin)this).Logger.LogInfo((object)("Deleting " + destination)); try { File.Delete(destination); } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogError((object)("An error occurred while deleting " + destination)); ((BaseUnityPlugin)this).Logger.LogError((object)ex.Message); ((BaseUnityPlugin)this).Logger.LogError((object)ex.InnerException.Message); } } try { File.Copy(source, destination); } catch (Exception ex2) { ((BaseUnityPlugin)this).Logger.LogError((object)("An error occurred while copying " + source + " to " + destination)); ((BaseUnityPlugin)this).Logger.LogError((object)ex2.Message); ((BaseUnityPlugin)this).Logger.LogError((object)ex2.InnerException.Message); } } private async Task CreateMusic() { string playlistUrl = Config.PlaylistUrl; try { string source = songPath; ((BaseUnityPlugin)this).Logger.LogInfo((object)("Downloading music to " + source)); ((BaseUnityPlugin)this).Logger.LogInfo((object)("Downloading playlist " + playlistUrl)); string[] songNames = new string[100]; List<Task> downloadTasks = new List<Task>(); await foreach (Batch<PlaylistVideo> batch in youtube.Playlists.GetVideoBatchesAsync(PlaylistId.op_Implicit(playlistUrl), default(CancellationToken))) { foreach (PlaylistVideo video2 in batch.Items) { var (newFileName2, boomboxFileName3) = createNamesFromTitle(video2, source); if (songNames[^1] != null) { string[] temp = new string[songNames.Length + 100]; for (int i = 0; i < songNames.Length; i++) { temp[i] = songNames[i]; } songNames = temp; } songNames[Array.IndexOf(songNames, null)] = newFileName2; ((BaseUnityPlugin)this).Logger.LogInfo((object)("Downloading " + newFileName2)); if (File.Exists(newFileName2)) { ((BaseUnityPlugin)this).Logger.LogInfo((object)("Skipping " + video2.Title + " because it already exists")); copyFile(newFileName2, boomboxFileName3); continue; } ((BaseUnityPlugin)this).Logger.LogInfo((object)("Converting " + video2.Title + " to " + newFileName2)); downloadTasks.Add(ConversionExtensions.DownloadAsync(youtube.Videos, VideoId.op_Implicit(video2.Url), newFileName2, (Action<ConversionRequestBuilder>)delegate(ConversionRequestBuilder o) { o.SetPreset((ConversionPreset)3).SetContainer("mp3").SetFFmpegPath(ffmpegPath); }, (IProgress<double>)null, default(CancellationToken)).AsTask()); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Continuing"); } await Task.WhenAll(downloadTasks); foreach (PlaylistVideo video in batch.Items) { var (newFileName, boomboxFileName2) = createNamesFromTitle(video, source); copyFile(newFileName, boomboxFileName2); } } ((BaseUnityPlugin)this).Logger.LogInfo((object)"Done!"); string[] files = Directory.GetFiles(source); foreach (string file in files) { if (Array.IndexOf(songNames, file) != -1) { continue; } ((BaseUnityPlugin)this).Logger.LogInfo((object)("Deleting " + file)); try { File.Delete(file); } catch (Exception ex) { Exception e3 = ex; ((BaseUnityPlugin)this).Logger.LogError((object)("An error occurred while deleting " + file)); ((BaseUnityPlugin)this).Logger.LogError((object)e3.Message); ((BaseUnityPlugin)this).Logger.LogError((object)e3.InnerException.Message); } string boomboxFileName = Path.Combine(boomboxPath, Path.GetFileName(file)); if (File.Exists(boomboxFileName)) { ((BaseUnityPlugin)this).Logger.LogInfo((object)("Deleting " + boomboxFileName)); try { File.Delete(boomboxFileName); } catch (Exception ex) { Exception e2 = ex; ((BaseUnityPlugin)this).Logger.LogError((object)("An error occurred while deleting " + boomboxFileName)); ((BaseUnityPlugin)this).Logger.LogError((object)e2.Message); ((BaseUnityPlugin)this).Logger.LogError((object)e2.InnerException.Message); } } } } catch (Exception ex) { Exception e = ex; ((BaseUnityPlugin)this).Logger.LogError((object)"An error occurred while creating music"); ((BaseUnityPlugin)this).Logger.LogError((object)e.Message); ((BaseUnityPlugin)this).Logger.LogError((object)e.InnerException.Message); } } } public static class PluginInfo { public const string PLUGIN_GUID = "CustomRadio"; public const string PLUGIN_NAME = "CustomRadio"; public const string PLUGIN_VERSION = "0.0.1"; } } namespace CustomRadio.Configuration { internal static class Config { private const string CONFIG_FILE_NAME = "zerouni.CustomRadio.cfg"; private static ConfigFile _configFile; private static ConfigEntry<string> _playlistUrl; public static string PlaylistUrl { get { return _playlistUrl.Value ?? "https://www.youtube.com/playlist?list=PLrsKG8lXztu1oGy7A9Lu_N0Y9z_4A9mc_"; } set { _playlistUrl.Value = value; } } public static void Init() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown _configFile = new ConfigFile(Path.Combine(Paths.ConfigPath, "zerouni.CustomRadio.cfg"), true); _playlistUrl = _configFile.Bind<string>("General", "PlaylistUrl", "https://www.youtube.com/playlist?list=PLrsKG8lXztu1oGy7A9Lu_N0Y9z_4A9mc_", (ConfigDescription)null); } } }
System.Buffers.dll
Decompiled 2 years 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.Management.dll
Decompiled 2 years ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.CodeDom; using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using FxResources.System.Management; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyMetadata("NotSupported", "True")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("System.Management")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: SupportedOSPlatform("windows")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Provides access to a rich set of management information and management events about the system, devices, and applications instrumented to the Windows Management Instrumentation (WMI) infrastructure.\r\n\r\nCommonly Used Types:\r\nSystem.Management.ManagementClass\r\nSystem.Management.ManagementObject\r\nSystem.Management.SelectQuery")] [assembly: AssemblyFileVersion("8.0.23.53103")] [assembly: AssemblyInformationalVersion("8.0.0+5535e31a712343a63f5d7d796cd874e563e5ac14")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("System.Management")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.System.Management { 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 InvalidQuery => GetResourceString("InvalidQuery"); internal static string InvalidQueryDuplicatedToken => GetResourceString("InvalidQueryDuplicatedToken"); internal static string InvalidQueryNullToken => GetResourceString("InvalidQueryNullToken"); internal static string WorkerThreadWakeupFailed => GetResourceString("WorkerThreadWakeupFailed"); internal static string ClassNameNotInitializedException => GetResourceString("ClassNameNotInitializedException"); internal static string ClassNameNotFoundException => GetResourceString("ClassNameNotFoundException"); internal static string CommentAttributeProperty => GetResourceString("CommentAttributeProperty"); internal static string CommentAutoCommitProperty => GetResourceString("CommentAutoCommitProperty"); internal static string CommentClassBegin => GetResourceString("CommentClassBegin"); internal static string CommentConstructors => GetResourceString("CommentConstructors"); internal static string CommentCreatedClass => GetResourceString("CommentCreatedClass"); internal static string CommentCreatedWmiNamespace => GetResourceString("CommentCreatedWmiNamespace"); internal static string CommentCurrentObject => GetResourceString("CommentCurrentObject"); internal static string CommentDateConversionFunction => GetResourceString("CommentDateConversionFunction"); internal static string CommentEmbeddedObject => GetResourceString("CommentEmbeddedObject"); internal static string CommentEnumeratorImplementation => GetResourceString("CommentEnumeratorImplementation"); internal static string CommentFlagForEmbedded => GetResourceString("CommentFlagForEmbedded"); internal static string CommentGetInstances => GetResourceString("CommentGetInstances"); internal static string CommentIsPropNull => GetResourceString("CommentIsPropNull"); internal static string CommentLateBoundObject => GetResourceString("CommentLateBoundObject"); internal static string CommentLateBoundProperty => GetResourceString("CommentLateBoundProperty"); internal static string CommentManagementPath => GetResourceString("CommentManagementPath"); internal static string CommentManagementScope => GetResourceString("CommentManagementScope"); internal static string CommentOriginNamespace => GetResourceString("CommentOriginNamespace"); internal static string CommentPrivateAutoCommit => GetResourceString("CommentPrivateAutoCommit"); internal static string CommentPrototypeConverter => GetResourceString("CommentPrototypeConverter"); internal static string CommentResetProperty => GetResourceString("CommentResetProperty"); internal static string CommentShouldSerialize => GetResourceString("CommentShouldSerialize"); internal static string CommentStaticManagementScope => GetResourceString("CommentStaticManagementScope"); internal static string CommentStaticScopeProperty => GetResourceString("CommentStaticScopeProperty"); internal static string CommentSystemObject => GetResourceString("CommentSystemObject"); internal static string CommentSystemPropertiesClass => GetResourceString("CommentSystemPropertiesClass"); internal static string CommentTimeSpanConversionFunction => GetResourceString("CommentTimeSpanConversionFunction"); internal static string CommentToDateTime => GetResourceString("CommentToDateTime"); internal static string CommentToDmtfDateTime => GetResourceString("CommentToDmtfDateTime"); internal static string CommentToDmtfTimeInterval => GetResourceString("CommentToDmtfTimeInterval"); internal static string CommentToTimeSpan => GetResourceString("CommentToTimeSpan"); internal static string EmbeddedComment => GetResourceString("EmbeddedComment"); internal static string EmbeddedComment2 => GetResourceString("EmbeddedComment2"); internal static string EmbeddedComment3 => GetResourceString("EmbeddedComment3"); internal static string EmbeddedComment4 => GetResourceString("EmbeddedComment4"); internal static string EmbeddedComment5 => GetResourceString("EmbeddedComment5"); internal static string EmbeddedComment6 => GetResourceString("EmbeddedComment6"); internal static string EmbeddedComment7 => GetResourceString("EmbeddedComment7"); internal static string EmbeddedComment8 => GetResourceString("EmbeddedComment8"); internal static string EmbeddedCSharpComment1 => GetResourceString("EmbeddedCSharpComment1"); internal static string EmbeddedCSharpComment10 => GetResourceString("EmbeddedCSharpComment10"); internal static string EmbeddedCSharpComment11 => GetResourceString("EmbeddedCSharpComment11"); internal static string EmbeddedCSharpComment12 => GetResourceString("EmbeddedCSharpComment12"); internal static string EmbeddedCSharpComment13 => GetResourceString("EmbeddedCSharpComment13"); internal static string EmbeddedCSharpComment14 => GetResourceString("EmbeddedCSharpComment14"); internal static string EmbeddedCSharpComment15 => GetResourceString("EmbeddedCSharpComment15"); internal static string EmbeddedCSharpComment2 => GetResourceString("EmbeddedCSharpComment2"); internal static string EmbeddedCSharpComment3 => GetResourceString("EmbeddedCSharpComment3"); internal static string EmbeddedCSharpComment4 => GetResourceString("EmbeddedCSharpComment4"); internal static string EmbeddedCSharpComment5 => GetResourceString("EmbeddedCSharpComment5"); internal static string EmbeddedCSharpComment6 => GetResourceString("EmbeddedCSharpComment6"); internal static string EmbeddedCSharpComment7 => GetResourceString("EmbeddedCSharpComment7"); internal static string EmbeddedCSharpComment8 => GetResourceString("EmbeddedCSharpComment8"); internal static string EmbeddedCSharpComment9 => GetResourceString("EmbeddedCSharpComment9"); internal static string EmbeddedVisualBasicComment1 => GetResourceString("EmbeddedVisualBasicComment1"); internal static string EmbeddedVisualBasicComment10 => GetResourceString("EmbeddedVisualBasicComment10"); internal static string EmbeddedVisualBasicComment2 => GetResourceString("EmbeddedVisualBasicComment2"); internal static string EmbeddedVisualBasicComment3 => GetResourceString("EmbeddedVisualBasicComment3"); internal static string EmbeddedVisualBasicComment4 => GetResourceString("EmbeddedVisualBasicComment4"); internal static string EmbeddedVisualBasicComment5 => GetResourceString("EmbeddedVisualBasicComment5"); internal static string EmbeddedVisualBasicComment6 => GetResourceString("EmbeddedVisualBasicComment6"); internal static string EmbeddedVisualBasicComment7 => GetResourceString("EmbeddedVisualBasicComment7"); internal static string EmbeddedVisualBasicComment8 => GetResourceString("EmbeddedVisualBasicComment8"); internal static string EmbeddedVisualBasicComment9 => GetResourceString("EmbeddedVisualBasicComment9"); internal static string EmptyFilePathException => GetResourceString("EmptyFilePathException"); internal static string NamespaceNotInitializedException => GetResourceString("NamespaceNotInitializedException"); internal static string NullFilePathException => GetResourceString("NullFilePathException"); internal static string UnableToCreateCodeGeneratorException => GetResourceString("UnableToCreateCodeGeneratorException"); internal static string PlatformNotSupported_SystemManagement => GetResourceString("PlatformNotSupported_SystemManagement"); internal static string PlatformNotSupported_FullFrameworkRequired => GetResourceString("PlatformNotSupported_FullFrameworkRequired"); internal static string LoadLibraryFailed => GetResourceString("LoadLibraryFailed"); internal static string PlatformNotSupported_FrameworkUpdatedRequired => GetResourceString("PlatformNotSupported_FrameworkUpdatedRequired"); internal static string InvalidQueryTokenExpected => GetResourceString("InvalidQueryTokenExpected"); internal static bool UsingResourceKeys() { return s_usingResourceKeys; } private static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } private static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider provider, string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Management { public enum AuthenticationLevel { Unchanged = -1, Default, None, Connect, Call, Packet, PacketIntegrity, PacketPrivacy } public enum CimType { None = 0, SInt16 = 2, SInt32 = 3, Real32 = 4, Real64 = 5, String = 8, Boolean = 11, Object = 13, SInt8 = 16, UInt8 = 17, UInt16 = 18, UInt32 = 19, SInt64 = 20, UInt64 = 21, DateTime = 101, Reference = 102, Char16 = 103 } public enum CodeLanguage { CSharp, JScript, VB, VJSharp, Mcpp } [Flags] public enum ComparisonSettings { IncludeAll = 0, IgnoreQualifiers = 1, IgnoreObjectSource = 2, IgnoreDefaultValues = 4, IgnoreClass = 8, IgnoreCase = 0x10, IgnoreFlavor = 0x20 } public class CompletedEventArgs : ManagementEventArgs { public ManagementStatus Status { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public ManagementBaseObject StatusObject { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } internal CompletedEventArgs() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public delegate void CompletedEventHandler(object sender, CompletedEventArgs e); public class ConnectionOptions : ManagementOptions { public AuthenticationLevel Authentication { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public string Authority { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public bool EnablePrivileges { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public ImpersonationLevel Impersonation { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public string Locale { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public string Password { set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public SecureString SecurePassword { set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public string Username { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public ConnectionOptions() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ConnectionOptions(string locale, string username, SecureString password, string authority, ImpersonationLevel impersonation, AuthenticationLevel authentication, bool enablePrivileges, ManagementNamedValueCollection context, TimeSpan timeout) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ConnectionOptions(string locale, string username, string password, string authority, ImpersonationLevel impersonation, AuthenticationLevel authentication, bool enablePrivileges, ManagementNamedValueCollection context, TimeSpan timeout) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public override object Clone() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public class DeleteOptions : ManagementOptions { public DeleteOptions() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public DeleteOptions(ManagementNamedValueCollection context, TimeSpan timeout) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public override object Clone() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public class EnumerationOptions : ManagementOptions { public int BlockSize { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public bool DirectRead { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public bool EnsureLocatable { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public bool EnumerateDeep { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public bool PrototypeOnly { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public bool ReturnImmediately { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public bool Rewindable { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public bool UseAmendedQualifiers { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public EnumerationOptions() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public EnumerationOptions(ManagementNamedValueCollection context, TimeSpan timeout, int blockSize, bool rewindable, bool returnImmediatley, bool useAmendedQualifiers, bool ensureLocatable, bool prototypeOnly, bool directRead, bool enumerateDeep) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public override object Clone() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public class EventArrivedEventArgs : ManagementEventArgs { public ManagementBaseObject NewEvent { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } internal EventArrivedEventArgs() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public delegate void EventArrivedEventHandler(object sender, EventArrivedEventArgs e); public class EventQuery : ManagementQuery { public EventQuery() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public EventQuery(string query) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public EventQuery(string language, string query) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public override object Clone() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public class EventWatcherOptions : ManagementOptions { public int BlockSize { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public EventWatcherOptions() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public EventWatcherOptions(ManagementNamedValueCollection context, TimeSpan timeout, int blockSize) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public override object Clone() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public enum ImpersonationLevel { Default, Anonymous, Identify, Impersonate, Delegate } public class InvokeMethodOptions : ManagementOptions { public InvokeMethodOptions() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public InvokeMethodOptions(ManagementNamedValueCollection context, TimeSpan timeout) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public override object Clone() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } [ToolboxItem(false)] public class ManagementBaseObject : Component, ICloneable, ISerializable { public virtual ManagementPath ClassPath { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public object this[string propertyName] { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public virtual PropertyDataCollection Properties { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public virtual QualifierDataCollection Qualifiers { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public virtual PropertyDataCollection SystemProperties { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } private protected ManagementBaseObject() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } protected ManagementBaseObject(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public virtual object Clone() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public bool CompareTo(ManagementBaseObject otherObject, ComparisonSettings settings) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public new void Dispose() { } public override bool Equals(object obj) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public override int GetHashCode() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } protected virtual void GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public object GetPropertyQualifierValue(string propertyName, string qualifierName) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public object GetPropertyValue(string propertyName) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public object GetQualifierValue(string qualifierName) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public string GetText(TextFormat format) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public static explicit operator IntPtr(ManagementBaseObject managementObject) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void SetPropertyQualifierValue(string propertyName, string qualifierName, object qualifierValue) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void SetPropertyValue(string propertyName, object propertyValue) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void SetQualifierValue(string qualifierName, object qualifierValue) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public class ManagementClass : ManagementObject { public StringCollection Derivation { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public MethodDataCollection Methods { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public override ManagementPath Path { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public ManagementClass() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementClass(ManagementPath path) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementClass(ManagementPath path, ObjectGetOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementClass(ManagementScope scope, ManagementPath path, ObjectGetOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } protected ManagementClass(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementClass(string path) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementClass(string path, ObjectGetOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementClass(string scope, string path, ObjectGetOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public override object Clone() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementObject CreateInstance() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementClass Derive(string newClassName) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementObjectCollection GetInstances() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementObjectCollection GetInstances(EnumerationOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void GetInstances(ManagementOperationObserver watcher) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void GetInstances(ManagementOperationObserver watcher, EnumerationOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } protected override void GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementObjectCollection GetRelatedClasses() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void GetRelatedClasses(ManagementOperationObserver watcher) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void GetRelatedClasses(ManagementOperationObserver watcher, string relatedClass) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void GetRelatedClasses(ManagementOperationObserver watcher, string relatedClass, string relationshipClass, string relationshipQualifier, string relatedQualifier, string relatedRole, string thisRole, EnumerationOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementObjectCollection GetRelatedClasses(string relatedClass) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementObjectCollection GetRelatedClasses(string relatedClass, string relationshipClass, string relationshipQualifier, string relatedQualifier, string relatedRole, string thisRole, EnumerationOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementObjectCollection GetRelationshipClasses() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void GetRelationshipClasses(ManagementOperationObserver watcher) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void GetRelationshipClasses(ManagementOperationObserver watcher, string relationshipClass) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void GetRelationshipClasses(ManagementOperationObserver watcher, string relationshipClass, string relationshipQualifier, string thisRole, EnumerationOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementObjectCollection GetRelationshipClasses(string relationshipClass) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementObjectCollection GetRelationshipClasses(string relationshipClass, string relationshipQualifier, string thisRole, EnumerationOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public CodeTypeDeclaration GetStronglyTypedClassCode(bool includeSystemClassInClassDef, bool systemPropertyClass) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public bool GetStronglyTypedClassCode(CodeLanguage lang, string filePath, string classNamespace) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementObjectCollection GetSubclasses() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementObjectCollection GetSubclasses(EnumerationOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void GetSubclasses(ManagementOperationObserver watcher) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void GetSubclasses(ManagementOperationObserver watcher, EnumerationOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public sealed class ManagementDateTimeConverter { internal ManagementDateTimeConverter() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public static DateTime ToDateTime(string dmtfDate) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public static string ToDmtfDateTime(DateTime date) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public static string ToDmtfTimeInterval(TimeSpan timespan) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public static TimeSpan ToTimeSpan(string dmtfTimespan) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public abstract class ManagementEventArgs : EventArgs { public object Context { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } internal ManagementEventArgs() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } [ToolboxItem(false)] public class ManagementEventWatcher : Component { public EventWatcherOptions Options { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public EventQuery Query { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public ManagementScope Scope { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public event EventArrivedEventHandler EventArrived { add { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } remove { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public event StoppedEventHandler Stopped { add { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } remove { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public ManagementEventWatcher() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementEventWatcher(EventQuery query) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementEventWatcher(ManagementScope scope, EventQuery query) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementEventWatcher(ManagementScope scope, EventQuery query, EventWatcherOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementEventWatcher(string query) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementEventWatcher(string scope, string query) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementEventWatcher(string scope, string query, EventWatcherOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } ~ManagementEventWatcher() { } public void Start() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void Stop() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementBaseObject WaitForNextEvent() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public class ManagementException : SystemException { public ManagementStatus ErrorCode { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public ManagementBaseObject ErrorInformation { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public ManagementException() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } protected ManagementException(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementException(string message) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementException(string message, Exception innerException) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public class ManagementNamedValueCollection : NameObjectCollectionBase { public object this[string name] { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public ManagementNamedValueCollection() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } protected ManagementNamedValueCollection(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void Add(string name, object value) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementNamedValueCollection Clone() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void Remove(string name) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void RemoveAll() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public class ManagementObject : ManagementBaseObject, ICloneable { public override ManagementPath ClassPath { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public ObjectGetOptions Options { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public virtual ManagementPath Path { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public ManagementScope Scope { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public ManagementObject() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementObject(ManagementPath path) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementObject(ManagementPath path, ObjectGetOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementObject(ManagementScope scope, ManagementPath path, ObjectGetOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } protected ManagementObject(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementObject(string path) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementObject(string path, ObjectGetOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementObject(string scopeString, string pathString, ObjectGetOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public override object Clone() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void CopyTo(ManagementOperationObserver watcher, ManagementPath path) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void CopyTo(ManagementOperationObserver watcher, ManagementPath path, PutOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void CopyTo(ManagementOperationObserver watcher, string path) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void CopyTo(ManagementOperationObserver watcher, string path, PutOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementPath CopyTo(ManagementPath path) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementPath CopyTo(ManagementPath path, PutOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementPath CopyTo(string path) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementPath CopyTo(string path, PutOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void Delete() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void Delete(DeleteOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void Delete(ManagementOperationObserver watcher) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void Delete(ManagementOperationObserver watcher, DeleteOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public new void Dispose() { } public void Get() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void Get(ManagementOperationObserver watcher) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementBaseObject GetMethodParameters(string methodName) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } protected override void GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementObjectCollection GetRelated() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void GetRelated(ManagementOperationObserver watcher) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void GetRelated(ManagementOperationObserver watcher, string relatedClass) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void GetRelated(ManagementOperationObserver watcher, string relatedClass, string relationshipClass, string relationshipQualifier, string relatedQualifier, string relatedRole, string thisRole, bool classDefinitionsOnly, EnumerationOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementObjectCollection GetRelated(string relatedClass) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementObjectCollection GetRelated(string relatedClass, string relationshipClass, string relationshipQualifier, string relatedQualifier, string relatedRole, string thisRole, bool classDefinitionsOnly, EnumerationOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementObjectCollection GetRelationships() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void GetRelationships(ManagementOperationObserver watcher) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void GetRelationships(ManagementOperationObserver watcher, string relationshipClass) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void GetRelationships(ManagementOperationObserver watcher, string relationshipClass, string relationshipQualifier, string thisRole, bool classDefinitionsOnly, EnumerationOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementObjectCollection GetRelationships(string relationshipClass) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementObjectCollection GetRelationships(string relationshipClass, string relationshipQualifier, string thisRole, bool classDefinitionsOnly, EnumerationOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void InvokeMethod(ManagementOperationObserver watcher, string methodName, ManagementBaseObject inParameters, InvokeMethodOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void InvokeMethod(ManagementOperationObserver watcher, string methodName, object[] args) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementBaseObject InvokeMethod(string methodName, ManagementBaseObject inParameters, InvokeMethodOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public object InvokeMethod(string methodName, object[] args) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementPath Put() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void Put(ManagementOperationObserver watcher) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void Put(ManagementOperationObserver watcher, PutOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementPath Put(PutOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public override string ToString() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public class ManagementObjectCollection : ICollection, IEnumerable, IDisposable { public class ManagementObjectEnumerator : IEnumerator, IDisposable { public ManagementBaseObject Current { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } object IEnumerator.Current { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } internal ManagementObjectEnumerator() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void Dispose() { } ~ManagementObjectEnumerator() { } public bool MoveNext() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void Reset() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public int Count { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public bool IsSynchronized { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public object SyncRoot { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } internal ManagementObjectCollection() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void CopyTo(Array array, int index) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void CopyTo(ManagementBaseObject[] objectCollection, int index) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void Dispose() { } ~ManagementObjectCollection() { } public ManagementObjectEnumerator GetEnumerator() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } IEnumerator IEnumerable.GetEnumerator() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } [ToolboxItem(false)] public class ManagementObjectSearcher : Component { public EnumerationOptions Options { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public ObjectQuery Query { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public ManagementScope Scope { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public ManagementObjectSearcher() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementObjectSearcher(ManagementScope scope, ObjectQuery query) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementObjectSearcher(ManagementScope scope, ObjectQuery query, EnumerationOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementObjectSearcher(ObjectQuery query) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementObjectSearcher(string queryString) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementObjectSearcher(string scope, string queryString) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementObjectSearcher(string scope, string queryString, EnumerationOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementObjectCollection Get() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void Get(ManagementOperationObserver watcher) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public class ManagementOperationObserver { public event CompletedEventHandler Completed { add { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } remove { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public event ObjectPutEventHandler ObjectPut { add { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } remove { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public event ObjectReadyEventHandler ObjectReady { add { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } remove { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public event ProgressEventHandler Progress { add { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } remove { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public ManagementOperationObserver() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void Cancel() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } [TypeConverter(typeof(ExpandableObjectConverter))] public abstract class ManagementOptions : ICloneable { public static readonly TimeSpan InfiniteTimeout; public ManagementNamedValueCollection Context { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public TimeSpan Timeout { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } internal ManagementOptions() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public abstract object Clone(); } [TypeConverter(typeof(ManagementPathConverter))] public class ManagementPath : ICloneable { [RefreshProperties(RefreshProperties.All)] public string ClassName { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public static ManagementPath DefaultPath { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public bool IsClass { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public bool IsInstance { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public bool IsSingleton { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } [RefreshProperties(RefreshProperties.All)] public string NamespacePath { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } [RefreshProperties(RefreshProperties.All)] public string Path { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } [RefreshProperties(RefreshProperties.All)] public string RelativePath { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } [RefreshProperties(RefreshProperties.All)] public string Server { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public ManagementPath() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementPath(string path) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementPath Clone() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void SetAsClass() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void SetAsSingleton() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } object ICloneable.Clone() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public override string ToString() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } [TypeConverter(typeof(ManagementQueryConverter))] public abstract class ManagementQuery : ICloneable { public virtual string QueryLanguage { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public virtual string QueryString { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } internal ManagementQuery() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public abstract object Clone(); protected internal virtual void ParseQuery(string query) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } [TypeConverter(typeof(ManagementScopeConverter))] public class ManagementScope : ICloneable { public bool IsConnected { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public ConnectionOptions Options { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public ManagementPath Path { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public ManagementScope() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementScope(ManagementPath path) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementScope(ManagementPath path, ConnectionOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementScope(string path) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementScope(string path, ConnectionOptions options) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ManagementScope Clone() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void Connect() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } object ICloneable.Clone() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public enum ManagementStatus { Failed = -2147217407, NotFound = -2147217406, AccessDenied = -2147217405, ProviderFailure = -2147217404, TypeMismatch = -2147217403, OutOfMemory = -2147217402, InvalidContext = -2147217401, InvalidParameter = -2147217400, NotAvailable = -2147217399, CriticalError = -2147217398, InvalidStream = -2147217397, NotSupported = -2147217396, InvalidSuperclass = -2147217395, InvalidNamespace = -2147217394, InvalidObject = -2147217393, InvalidClass = -2147217392, ProviderNotFound = -2147217391, InvalidProviderRegistration = -2147217390, ProviderLoadFailure = -2147217389, InitializationFailure = -2147217388, TransportFailure = -2147217387, InvalidOperation = -2147217386, InvalidQuery = -2147217385, InvalidQueryType = -2147217384, AlreadyExists = -2147217383, OverrideNotAllowed = -2147217382, PropagatedQualifier = -2147217381, PropagatedProperty = -2147217380, Unexpected = -2147217379, IllegalOperation = -2147217378, CannotBeKey = -2147217377, IncompleteClass = -2147217376, InvalidSyntax = -2147217375, NondecoratedObject = -2147217374, ReadOnly = -2147217373, ProviderNotCapable = -2147217372, ClassHasChildren = -2147217371, ClassHasInstances = -2147217370, QueryNotImplemented = -2147217369, IllegalNull = -2147217368, InvalidQualifierType = -2147217367, InvalidPropertyType = -2147217366, ValueOutOfRange = -2147217365, CannotBeSingleton = -2147217364, InvalidCimType = -2147217363, InvalidMethod = -2147217362, InvalidMethodParameters = -2147217361, SystemProperty = -2147217360, InvalidProperty = -2147217359, CallCanceled = -2147217358, ShuttingDown = -2147217357, PropagatedMethod = -2147217356, UnsupportedParameter = -2147217355, MissingParameterID = -2147217354, InvalidParameterID = -2147217353, NonconsecutiveParameterIDs = -2147217352, ParameterIDOnRetval = -2147217351, InvalidObjectPath = -2147217350, OutOfDiskSpace = -2147217349, BufferTooSmall = -2147217348, UnsupportedPutExtension = -2147217347, UnknownObjectType = -2147217346, UnknownPacketType = -2147217345, MarshalVersionMismatch = -2147217344, MarshalInvalidSignature = -2147217343, InvalidQualifier = -2147217342, InvalidDuplicateParameter = -2147217341, TooMuchData = -2147217340, ServerTooBusy = -2147217339, InvalidFlavor = -2147217338, CircularReference = -2147217337, UnsupportedClassUpdate = -2147217336, CannotChangeKeyInheritance = -2147217335, CannotChangeIndexInheritance = -2147217328, TooManyProperties = -2147217327, UpdateTypeMismatch = -2147217326, UpdateOverrideNotAllowed = -2147217325, UpdatePropagatedMethod = -2147217324, MethodNotImplemented = -2147217323, MethodDisabled = -2147217322, RefresherBusy = -2147217321, UnparsableQuery = -2147217320, NotEventClass = -2147217319, MissingGroupWithin = -2147217318, MissingAggregationList = -2147217317, PropertyNotAnObject = -2147217316, AggregatingByObject = -2147217315, UninterpretableProviderQuery = -2147217313, BackupRestoreWinmgmtRunning = -2147217312, QueueOverflow = -2147217311, PrivilegeNotHeld = -2147217310, InvalidOperator = -2147217309, LocalCredentials = -2147217308, CannotBeAbstract = -2147217307, AmendedObject = -2147217306, ClientTooSlow = -2147217305, RegistrationTooBroad = -2147213311, RegistrationTooPrecise = -2147213310, NoError = 0, False = 1, ResetToDefault = 262146, Different = 262147, Timedout = 262148, NoMoreData = 262149, OperationCanceled = 262150, Pending = 262151, DuplicateObjects = 262152, PartialResults = 262160 } public class MethodData { public ManagementBaseObject InParameters { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public string Name { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public string Origin { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public ManagementBaseObject OutParameters { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public QualifierDataCollection Qualifiers { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } internal MethodData() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public class MethodDataCollection : ICollection, IEnumerable { public class MethodDataEnumerator : IEnumerator { public MethodData Current { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } object IEnumerator.Current { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } internal MethodDataEnumerator() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public bool MoveNext() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void Reset() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public int Count { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public bool IsSynchronized { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public virtual MethodData this[string methodName] { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public object SyncRoot { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } internal MethodDataCollection() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public virtual void Add(string methodName) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public virtual void Add(string methodName, ManagementBaseObject inParameters, ManagementBaseObject outParameters) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void CopyTo(Array array, int index) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void CopyTo(MethodData[] methodArray, int index) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public MethodDataEnumerator GetEnumerator() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public virtual void Remove(string methodName) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } IEnumerator IEnumerable.GetEnumerator() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public class ObjectGetOptions : ManagementOptions { public bool UseAmendedQualifiers { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public ObjectGetOptions() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ObjectGetOptions(ManagementNamedValueCollection context) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ObjectGetOptions(ManagementNamedValueCollection context, TimeSpan timeout, bool useAmendedQualifiers) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public override object Clone() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public class ObjectPutEventArgs : ManagementEventArgs { public ManagementPath Path { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } internal ObjectPutEventArgs() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public delegate void ObjectPutEventHandler(object sender, ObjectPutEventArgs e); public class ObjectQuery : ManagementQuery { public ObjectQuery() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ObjectQuery(string query) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public ObjectQuery(string language, string query) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public override object Clone() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public class ObjectReadyEventArgs : ManagementEventArgs { public ManagementBaseObject NewObject { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } internal ObjectReadyEventArgs() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public delegate void ObjectReadyEventHandler(object sender, ObjectReadyEventArgs e); public class ProgressEventArgs : ManagementEventArgs { public int Current { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public string Message { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public int UpperBound { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } internal ProgressEventArgs() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public delegate void ProgressEventHandler(object sender, ProgressEventArgs e); public class PropertyData { public bool IsArray { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public bool IsLocal { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public string Name { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public string Origin { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public QualifierDataCollection Qualifiers { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public CimType Type { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public object Value { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } internal PropertyData() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public class PropertyDataCollection : ICollection, IEnumerable { public class PropertyDataEnumerator : IEnumerator { public PropertyData Current { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } object IEnumerator.Current { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } internal PropertyDataEnumerator() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public bool MoveNext() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void Reset() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public int Count { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public bool IsSynchronized { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public virtual PropertyData this[string propertyName] { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public object SyncRoot { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } internal PropertyDataCollection() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void Add(string propertyName, CimType propertyType, bool isArray) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public virtual void Add(string propertyName, object propertyValue) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void Add(string propertyName, object propertyValue, CimType propertyType) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void CopyTo(Array array, int index) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void CopyTo(PropertyData[] propertyArray, int index) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public PropertyDataEnumerator GetEnumerator() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public virtual void Remove(string propertyName) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } IEnumerator IEnumerable.GetEnumerator() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public class PutOptions : ManagementOptions { public PutType Type { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public bool UseAmendedQualifiers { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public PutOptions() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public PutOptions(ManagementNamedValueCollection context) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public PutOptions(ManagementNamedValueCollection context, TimeSpan timeout, bool useAmendedQualifiers, PutType putType) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public override object Clone() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public enum PutType { None, UpdateOnly, CreateOnly, UpdateOrCreate } public class QualifierData { public bool IsAmended { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public bool IsLocal { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public bool IsOverridable { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public string Name { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public bool PropagatesToInstance { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public bool PropagatesToSubclass { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public object Value { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } internal QualifierData() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public class QualifierDataCollection : ICollection, IEnumerable { public class QualifierDataEnumerator : IEnumerator { public QualifierData Current { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } object IEnumerator.Current { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } internal QualifierDataEnumerator() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public bool MoveNext() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void Reset() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public int Count { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public bool IsSynchronized { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public virtual QualifierData this[string qualifierName] { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public object SyncRoot { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } internal QualifierDataCollection() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public virtual void Add(string qualifierName, object qualifierValue) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public virtual void Add(string qualifierName, object qualifierValue, bool isAmended, bool propagatesToInstance, bool propagatesToSubclass, bool isOverridable) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void CopyTo(Array array, int index) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public void CopyTo(QualifierData[] qualifierArray, int index) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public QualifierDataEnumerator GetEnumerator() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public virtual void Remove(string qualifierName) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } IEnumerator IEnumerable.GetEnumerator() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public class RelatedObjectQuery : WqlObjectQuery { public bool ClassDefinitionsOnly { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public bool IsSchemaQuery { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public string RelatedClass { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public string RelatedQualifier { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public string RelatedRole { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public string RelationshipClass { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public string RelationshipQualifier { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public string SourceObject { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public string ThisRole { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public RelatedObjectQuery() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public RelatedObjectQuery(bool isSchemaQuery, string sourceObject, string relatedClass, string relationshipClass, string relatedQualifier, string relationshipQualifier, string relatedRole, string thisRole) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public RelatedObjectQuery(string queryOrSourceObject) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public RelatedObjectQuery(string sourceObject, string relatedClass) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public RelatedObjectQuery(string sourceObject, string relatedClass, string relationshipClass, string relatedQualifier, string relationshipQualifier, string relatedRole, string thisRole, bool classDefinitionsOnly) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } protected internal void BuildQuery() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public override object Clone() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } protected internal override void ParseQuery(string query) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public class RelationshipQuery : WqlObjectQuery { public bool ClassDefinitionsOnly { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public bool IsSchemaQuery { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public string RelationshipClass { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public string RelationshipQualifier { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public string SourceObject { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public string ThisRole { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public RelationshipQuery() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public RelationshipQuery(bool isSchemaQuery, string sourceObject, string relationshipClass, string relationshipQualifier, string thisRole) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public RelationshipQuery(string queryOrSourceObject) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public RelationshipQuery(string sourceObject, string relationshipClass) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public RelationshipQuery(string sourceObject, string relationshipClass, string relationshipQualifier, string thisRole, bool classDefinitionsOnly) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } protected internal void BuildQuery() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public override object Clone() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } protected internal override void ParseQuery(string query) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public class SelectQuery : WqlObjectQuery { public string ClassName { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public string Condition { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public bool IsSchemaQuery { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public override string QueryString { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public StringCollection SelectedProperties { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public SelectQuery() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public SelectQuery(bool isSchemaQuery, string condition) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public SelectQuery(string queryOrClassName) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public SelectQuery(string className, string condition) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public SelectQuery(string className, string condition, string[] selectedProperties) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } protected internal void BuildQuery() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public override object Clone() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } protected internal override void ParseQuery(string query) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public class StoppedEventArgs : ManagementEventArgs { public ManagementStatus Status { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } internal StoppedEventArgs() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public delegate void StoppedEventHandler(object sender, StoppedEventArgs e); public enum TextFormat { Mof, CimDtd20, WmiDtd20 } public class WqlEventQuery : EventQuery { public string Condition { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public string EventClassName { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public StringCollection GroupByPropertyList { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public TimeSpan GroupWithinInterval { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public string HavingCondition { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public override string QueryLanguage { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public override string QueryString { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public TimeSpan WithinInterval { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public WqlEventQuery() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public WqlEventQuery(string queryOrEventClassName) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public WqlEventQuery(string eventClassName, string condition) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public WqlEventQuery(string eventClassName, string condition, TimeSpan groupWithinInterval) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public WqlEventQuery(string eventClassName, string condition, TimeSpan groupWithinInterval, string[] groupByPropertyList) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public WqlEventQuery(string eventClassName, TimeSpan withinInterval) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public WqlEventQuery(string eventClassName, TimeSpan withinInterval, string condition) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public WqlEventQuery(string eventClassName, TimeSpan withinInterval, string condition, TimeSpan groupWithinInterval, string[] groupByPropertyList, string havingCondition) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } protected internal void BuildQuery() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public override object Clone() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } protected internal override void ParseQuery(string query) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public class WqlObjectQuery : ObjectQuery { public override string QueryLanguage { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } public WqlObjectQuery() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public WqlObjectQuery(string query) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } public override object Clone() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_SystemManagement); } } internal sealed class ManagementPathConverter { } internal sealed class ManagementQueryConverter { } internal sealed class ManagementScopeConverter { } } 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)
System.Memory.dll
Decompiled 2 years 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 2 years 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.26515.06")] [assembly: AssemblyInformationalVersion("4.6.26515.06 @BuiltBy: dlab-DDVSOWINAGE059 @Branch: release/2.1 @SrcCode: https://github.com/dotnet/corefx/tree/30ab651fcb4354552bd4891619a0bdd81e0ebdbf")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.1.4.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 Pow(float x, float y) { return (float)Math.Pow(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 static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(ResourceType)); internal static Type ResourceType { get; } = typeof(SR); 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 string Arg_InsufficientNumberOfElements => GetResourceString("Arg_InsufficientNumberOfElements", 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.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Field, Inherited = false)] internal sealed class IntrinsicAttribute : Attribute { } [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; } } [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; } [System.Runtime.CompilerServices.Intrinsic] 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> s_zero = default(Vector<T>); private static readonly Vector<T> s_one = new Vector<T>(GetOneValue()); private static readonly Vector<T> s_allOnes = new Vector<T>(GetAllBitsSetValue()); public static int Count { [System.Runtime.CompilerServices.Intrinsic] get { return s_count; } } public static Vector<T> Zero { [System.Runtime.CompilerServices.Intrinsic] get { return s_zero; } } public static Vector<T> One { [System.Runtime.CompilerServices.Intrinsic] get { return s_one; } } internal static Vector<T> AllOnes => s_allOnes; public unsafe T this[int index] { [System.Runtime.CompilerServices.Intrinsic] 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; } [System.Runtime.CompilerServices.Intrinsic] 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; } } [System.Runtime.CompilerServices.Intrinsic] 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(System.SR.Format(System.SR.Arg_InsufficientNumberOfElements, Count, "values")); } 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; } [System.Runtime.CompilerServices.Intrinsic] public void CopyTo(T[] destination) { CopyTo(destination, 0); } [System.Runtime.CompilerServices.Intrinsic] 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); } [System.Runtime.CompilerServices.Intrinsic] 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)(uint)Count]; 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)(uint)Count]; 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)(uint)Count]; 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)(uint)Count]; 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)(uint)Count]; 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)(uint)Count]; 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)(uint)Count]; 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)(uint)Count]; 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; } [System.Runtime.CompilerServices.Intrinsic] 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; } [System.Runtime.CompilerServices.Intrinsic] 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; } [System.Runtime.CompilerServices.Intrinsic] 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 s_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); } [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector<byte>(Vector<T> value) { return new Vector<byte>(ref value.register); } [CLSCompliant(false)] [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector<sbyte>(Vector<T> value) { return new Vector<sbyte>(ref value.register); } [CLSCompliant(false)] [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector<ushort>(Vector<T> value) { return new Vector<ushort>(ref value.register); } [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector<short>(Vector<T> value) { return new Vector<short>(ref value.register); } [CLSCompliant(false)] [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector<uint>(Vector<T> value) { return new Vector<uint>(ref value.register); } [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector<int>(Vector<T> value) { return new Vector<int>(ref value.register); } [CLSCompliant(false)] [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector<ulong>(Vector<T> value) { return new Vector<ulong>(ref value.register); } [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector<long>(Vector<T> value) { return new Vector<long>(ref value.register); } [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector<float>(Vector<T> value) { return new Vector<float>(ref value.register); } [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector<double>(Vector<T> value) { return new Vector<double>(ref value.register); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] 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)(uint)Count]; fo
System.Runtime.CompilerServices.Unsafe.dll
Decompiled 2 years 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.Json.dll
Decompiled 2 years 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.Text; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Numerics; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text.Encodings.Web; using System.Text.Json.Nodes; using System.Text.Json.Reflection; using System.Text.Json.Serialization; using System.Text.Json.Serialization.Converters; using System.Text.Json.Serialization.Metadata; using System.Threading; using System.Threading.Tasks; using FxResources.System.Text.Json; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("System.Text.Json")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Provides high-performance and low-allocating types that serialize objects to JavaScript Object Notation (JSON) text and deserialize JSON text to objects, with UTF-8 support built-in. Also provides types to read and write JSON text encoded as UTF-8, and to create an in-memory document object model (DOM), that is read-only, for random access of the JSON elements within a structured view of the data.\r\n\r\nThe System.Text.Json library is built-in as part of the shared framework in .NET Runtime. The package can be installed when you need to use it in other target frameworks.")] [assembly: AssemblyFileVersion("8.0.23.53103")] [assembly: AssemblyInformationalVersion("8.0.0+5535e31a712343a63f5d7d796cd874e563e5ac14")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("System.Text.Json")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("8.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [module: System.Runtime.CompilerServices.NullablePublicOnly(false)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsUnmanagedAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsByRefLikeAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] internal sealed class ScopedRefAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.System.Text.Json { internal static class SR { } } namespace System { internal static class HexConverter { public enum Casing : uint { Upper = 0u, Lower = 8224u } public static ReadOnlySpan<byte> CharToHexLookup => new byte[256] { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ToBytesBuffer(byte value, Span<byte> buffer, int startingIndex = 0, Casing casing = Casing.Upper) { uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209); uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing; buffer[startingIndex + 1] = (byte)num2; buffer[startingIndex] = (byte)(num2 >> 8); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ToCharsBuffer(byte value, Span<char> buffer, int startingIndex = 0, Casing casing = Casing.Upper) { uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209); uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing; buffer[startingIndex + 1] = (char)(num2 & 0xFFu); buffer[startingIndex] = (char)(num2 >> 8); } public static void EncodeToUtf16(ReadOnlySpan<byte> bytes, Span<char> chars, Casing casing = Casing.Upper) { for (int i = 0; i < bytes.Length; i++) { ToCharsBuffer(bytes[i], chars, i * 2, casing); } } public static string ToString(ReadOnlySpan<byte> bytes, Casing casing = Casing.Upper) { Span<char> span = ((bytes.Length <= 16) ? stackalloc char[bytes.Length * 2] : new char[bytes.Length * 2].AsSpan()); Span<char> buffer = span; int num = 0; ReadOnlySpan<byte> readOnlySpan = bytes; for (int i = 0; i < readOnlySpan.Length; i++) { byte value = readOnlySpan[i]; ToCharsBuffer(value, buffer, num, casing); num += 2; } return buffer.ToString(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static char ToCharUpper(int value) { value &= 0xF; value += 48; if (value > 57) { value += 7; } return (char)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static char ToCharLower(int value) { value &= 0xF; value += 48; if (value > 57) { value += 39; } return (char)value; } public static bool TryDecodeFromUtf16(ReadOnlySpan<char> chars, Span<byte> bytes) { int charsProcessed; return TryDecodeFromUtf16(chars, bytes, out charsProcessed); } public static bool TryDecodeFromUtf16(ReadOnlySpan<char> chars, Span<byte> bytes, out int charsProcessed) { int num = 0; int num2 = 0; int num3 = 0; int num4 = 0; while (num2 < bytes.Length) { num3 = FromChar(chars[num + 1]); num4 = FromChar(chars[num]); if ((num3 | num4) == 255) { break; } bytes[num2++] = (byte)((num4 << 4) | num3); num += 2; } if (num3 == 255) { num++; } charsProcessed = num; return (num3 | num4) != 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromChar(int c) { if (c < CharToHexLookup.Length) { return CharToHexLookup[c]; } return 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromUpperChar(int c) { if (c <= 71) { return CharToHexLookup[c]; } return 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromLowerChar(int c) { switch (c) { case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: return c - 48; case 97: case 98: case 99: case 100: case 101: case 102: return c - 97 + 10; default: return 255; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexChar(int c) { if (IntPtr.Size == 8) { ulong num = (uint)(c - 48); ulong num2 = (ulong)(-17875860044349952L << (int)num); ulong num3 = num - 64; return (long)(num2 & num3) < 0L; } return FromChar(c) != 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexUpperChar(int c) { if ((uint)(c - 48) > 9u) { return (uint)(c - 65) <= 5u; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexLowerChar(int c) { if ((uint)(c - 48) > 9u) { return (uint)(c - 97) <= 5u; } return true; } } internal static class Obsoletions { internal const string SharedUrlFormat = "https://aka.ms/dotnet-warnings/{0}"; internal const string SystemTextEncodingUTF7Message = "The UTF-7 encoding is insecure and should not be used. Consider using UTF-8 instead."; internal const string SystemTextEncodingUTF7DiagId = "SYSLIB0001"; internal const string PrincipalPermissionAttributeMessage = "PrincipalPermissionAttribute is not honored by the runtime and must not be used."; internal const string PrincipalPermissionAttributeDiagId = "SYSLIB0002"; internal const string CodeAccessSecurityMessage = "Code Access Security is not supported or honored by the runtime."; internal const string CodeAccessSecurityDiagId = "SYSLIB0003"; internal const string ConstrainedExecutionRegionMessage = "The Constrained Execution Region (CER) feature is not supported."; internal const string ConstrainedExecutionRegionDiagId = "SYSLIB0004"; internal const string GlobalAssemblyCacheMessage = "The Global Assembly Cache is not supported."; internal const string GlobalAssemblyCacheDiagId = "SYSLIB0005"; internal const string ThreadAbortMessage = "Thread.Abort is not supported and throws PlatformNotSupportedException."; internal const string ThreadResetAbortMessage = "Thread.ResetAbort is not supported and throws PlatformNotSupportedException."; internal const string ThreadAbortDiagId = "SYSLIB0006"; internal const string DefaultCryptoAlgorithmsMessage = "The default implementation of this cryptography algorithm is not supported."; internal const string DefaultCryptoAlgorithmsDiagId = "SYSLIB0007"; internal const string CreatePdbGeneratorMessage = "The CreatePdbGenerator API is not supported and throws PlatformNotSupportedException."; internal const string CreatePdbGeneratorDiagId = "SYSLIB0008"; internal const string AuthenticationManagerMessage = "The AuthenticationManager Authenticate and PreAuthenticate methods are not supported and throw PlatformNotSupportedException."; internal const string AuthenticationManagerDiagId = "SYSLIB0009"; internal const string RemotingApisMessage = "This Remoting API is not supported and throws PlatformNotSupportedException."; internal const string RemotingApisDiagId = "SYSLIB0010"; internal const string BinaryFormatterMessage = "BinaryFormatter serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for more information."; internal const string BinaryFormatterDiagId = "SYSLIB0011"; internal const string CodeBaseMessage = "Assembly.CodeBase and Assembly.EscapedCodeBase are only included for .NET Framework compatibility. Use Assembly.Location instead."; internal const string CodeBaseDiagId = "SYSLIB0012"; internal const string EscapeUriStringMessage = "Uri.EscapeUriString can corrupt the Uri string in some cases. Consider using Uri.EscapeDataString for query string components instead."; internal const string EscapeUriStringDiagId = "SYSLIB0013"; internal const string WebRequestMessage = "WebRequest, HttpWebRequest, ServicePoint, and WebClient are obsolete. Use HttpClient instead."; internal const string WebRequestDiagId = "SYSLIB0014"; internal const string DisablePrivateReflectionAttributeMessage = "DisablePrivateReflectionAttribute has no effect in .NET 6.0+."; internal const string DisablePrivateReflectionAttributeDiagId = "SYSLIB0015"; internal const string GetContextInfoMessage = "Use the Graphics.GetContextInfo overloads that accept arguments for better performance and fewer allocations."; internal const string GetContextInfoDiagId = "SYSLIB0016"; internal const string StrongNameKeyPairMessage = "Strong name signing is not supported and throws PlatformNotSupportedException."; internal const string StrongNameKeyPairDiagId = "SYSLIB0017"; internal const string ReflectionOnlyLoadingMessage = "ReflectionOnly loading is not supported and throws PlatformNotSupportedException."; internal const string ReflectionOnlyLoadingDiagId = "SYSLIB0018"; internal const string RuntimeEnvironmentMessage = "RuntimeEnvironment members SystemConfigurationFile, GetRuntimeInterfaceAsIntPtr, and GetRuntimeInterfaceAsObject are not supported and throw PlatformNotSupportedException."; internal const string RuntimeEnvironmentDiagId = "SYSLIB0019"; internal const string JsonSerializerOptionsIgnoreNullValuesMessage = "JsonSerializerOptions.IgnoreNullValues is obsolete. To ignore null values when serializing, set DefaultIgnoreCondition to JsonIgnoreCondition.WhenWritingNull."; internal const string JsonSerializerOptionsIgnoreNullValuesDiagId = "SYSLIB0020"; internal const string DerivedCryptographicTypesMessage = "Derived cryptographic types are obsolete. Use the Create method on the base type instead."; internal const string DerivedCryptographicTypesDiagId = "SYSLIB0021"; internal const string RijndaelMessage = "The Rijndael and RijndaelManaged types are obsolete. Use Aes instead."; internal const string RijndaelDiagId = "SYSLIB0022"; internal const string RNGCryptoServiceProviderMessage = "RNGCryptoServiceProvider is obsolete. To generate a random number, use one of the RandomNumberGenerator static methods instead."; internal const string RNGCryptoServiceProviderDiagId = "SYSLIB0023"; internal const string AppDomainCreateUnloadMessage = "Creating and unloading AppDomains is not supported and throws an exception."; internal const string AppDomainCreateUnloadDiagId = "SYSLIB0024"; internal const string SuppressIldasmAttributeMessage = "SuppressIldasmAttribute has no effect in .NET 6.0+."; internal const string SuppressIldasmAttributeDiagId = "SYSLIB0025"; internal const string X509CertificateImmutableMessage = "X509Certificate and X509Certificate2 are immutable. Use the appropriate constructor to create a new certificate."; internal const string X509CertificateImmutableDiagId = "SYSLIB0026"; internal const string PublicKeyPropertyMessage = "PublicKey.Key is obsolete. Use the appropriate method to get the public key, such as GetRSAPublicKey."; internal const string PublicKeyPropertyDiagId = "SYSLIB0027"; internal const string X509CertificatePrivateKeyMessage = "X509Certificate2.PrivateKey is obsolete. Use the appropriate method to get the private key, such as GetRSAPrivateKey, or use the CopyWithPrivateKey method to create a new instance with a private key."; internal const string X509CertificatePrivateKeyDiagId = "SYSLIB0028"; internal const string ProduceLegacyHmacValuesMessage = "ProduceLegacyHmacValues is obsolete. Producing legacy HMAC values is not supported."; internal const string ProduceLegacyHmacValuesDiagId = "SYSLIB0029"; internal const string UseManagedSha1Message = "HMACSHA1 always uses the algorithm implementation provided by the platform. Use a constructor without the useManagedSha1 parameter."; internal const string UseManagedSha1DiagId = "SYSLIB0030"; internal const string CryptoConfigEncodeOIDMessage = "EncodeOID is obsolete. Use the ASN.1 functionality provided in System.Formats.Asn1."; internal const string CryptoConfigEncodeOIDDiagId = "SYSLIB0031"; internal const string CorruptedStateRecoveryMessage = "Recovery from corrupted process state exceptions is not supported; HandleProcessCorruptedStateExceptionsAttribute is ignored."; internal const string CorruptedStateRecoveryDiagId = "SYSLIB0032"; internal const string Rfc2898CryptDeriveKeyMessage = "Rfc2898DeriveBytes.CryptDeriveKey is obsolete and is not supported. Use PasswordDeriveBytes.CryptDeriveKey instead."; internal const string Rfc2898CryptDeriveKeyDiagId = "SYSLIB0033"; internal const string CmsSignerCspParamsCtorMessage = "CmsSigner(CspParameters) is obsolete and is not supported. Use an alternative constructor instead."; internal const string CmsSignerCspParamsCtorDiagId = "SYSLIB0034"; internal const string SignerInfoCounterSigMessage = "ComputeCounterSignature without specifying a CmsSigner is obsolete and is not supported. Use the overload that accepts a CmsSigner."; internal const string SignerInfoCounterSigDiagId = "SYSLIB0035"; internal const string RegexCompileToAssemblyMessage = "Regex.CompileToAssembly is obsolete and not supported. Use the GeneratedRegexAttribute with the regular expression source generator instead."; internal const string RegexCompileToAssemblyDiagId = "SYSLIB0036"; internal const string AssemblyNameMembersMessage = "AssemblyName members HashAlgorithm, ProcessorArchitecture, and VersionCompatibility are obsolete and not supported."; internal const string AssemblyNameMembersDiagId = "SYSLIB0037"; internal const string SystemDataSerializationFormatBinaryMessage = "SerializationFormat.Binary is obsolete and should not be used. See https://aka.ms/serializationformat-binary-obsolete for more information."; internal const string SystemDataSerializationFormatBinaryDiagId = "SYSLIB0038"; internal const string TlsVersion10and11Message = "TLS versions 1.0 and 1.1 have known vulnerabilities and are not recommended. Use a newer TLS version instead, or use SslProtocols.None to defer to OS defaults."; internal const string TlsVersion10and11DiagId = "SYSLIB0039"; internal const string EncryptionPolicyMessage = "EncryptionPolicy.NoEncryption and AllowEncryption significantly reduce security and should not be used in production code."; internal const string EncryptionPolicyDiagId = "SYSLIB0040"; internal const string Rfc2898OutdatedCtorMessage = "The default hash algorithm and iteration counts in Rfc2898DeriveBytes constructors are outdated and insecure. Use a constructor that accepts the hash algorithm and the number of iterations."; internal const string Rfc2898OutdatedCtorDiagId = "SYSLIB0041"; internal const string EccXmlExportImportMessage = "ToXmlString and FromXmlString have no implementation for ECC types, and are obsolete. Use a standard import and export format such as ExportSubjectPublicKeyInfo or ImportSubjectPublicKeyInfo for public keys and ExportPkcs8PrivateKey or ImportPkcs8PrivateKey for private keys."; internal const string EccXmlExportImportDiagId = "SYSLIB0042"; internal const string EcDhPublicKeyBlobMessage = "ECDiffieHellmanPublicKey.ToByteArray() and the associated constructor do not have a consistent and interoperable implementation on all platforms. Use ECDiffieHellmanPublicKey.ExportSubjectPublicKeyInfo() instead."; internal const string EcDhPublicKeyBlobDiagId = "SYSLIB0043"; internal const string AssemblyNameCodeBaseMessage = "AssemblyName.CodeBase and AssemblyName.EscapedCodeBase are obsolete. Using them for loading an assembly is not supported."; internal const string AssemblyNameCodeBaseDiagId = "SYSLIB0044"; internal const string CryptoStringFactoryMessage = "Cryptographic factory methods accepting an algorithm name are obsolete. Use the parameterless Create factory method on the algorithm type instead."; internal const string CryptoStringFactoryDiagId = "SYSLIB0045"; internal const string ControlledExecutionRunMessage = "ControlledExecution.Run method may corrupt the process and should not be used in production code."; internal const string ControlledExecutionRunDiagId = "SYSLIB0046"; internal const string XmlSecureResolverMessage = "XmlSecureResolver is obsolete. Use XmlResolver.ThrowingResolver instead when attempting to forbid XML external entity resolution."; internal const string XmlSecureResolverDiagId = "SYSLIB0047"; internal const string RsaEncryptDecryptValueMessage = "RSA.EncryptValue and DecryptValue are not supported and throw NotSupportedException. Use RSA.Encrypt and RSA.Decrypt instead."; internal const string RsaEncryptDecryptDiagId = "SYSLIB0048"; internal const string JsonSerializerOptionsAddContextMessage = "JsonSerializerOptions.AddContext is obsolete. To register a JsonSerializerContext, use either the TypeInfoResolver or TypeInfoResolverChain properties."; internal const string JsonSerializerOptionsAddContextDiagId = "SYSLIB0049"; internal const string LegacyFormatterMessage = "Formatter-based serialization is obsolete and should not be used."; internal const string LegacyFormatterDiagId = "SYSLIB0050"; internal const string LegacyFormatterImplMessage = "This API supports obsolete formatter-based serialization. It should not be called or extended by application code."; internal const string LegacyFormatterImplDiagId = "SYSLIB0051"; internal const string RegexExtensibilityImplMessage = "This API supports obsolete mechanisms for Regex extensibility. It is not supported."; internal const string RegexExtensibilityDiagId = "SYSLIB0052"; internal const string AesGcmTagConstructorMessage = "AesGcm should indicate the required tag size for encryption and decryption. Use a constructor that accepts the tag size."; internal const string AesGcmTagConstructorDiagId = "SYSLIB0053"; } internal 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 ArrayDepthTooLarge => GetResourceString("ArrayDepthTooLarge"); internal static string CallFlushToAvoidDataLoss => GetResourceString("CallFlushToAvoidDataLoss"); internal static string CannotReadIncompleteUTF16 => GetResourceString("CannotReadIncompleteUTF16"); internal static string CannotReadInvalidUTF16 => GetResourceString("CannotReadInvalidUTF16"); internal static string CannotStartObjectArrayAfterPrimitiveOrClose => GetResourceString("CannotStartObjectArrayAfterPrimitiveOrClose"); internal static string CannotStartObjectArrayWithoutProperty => GetResourceString("CannotStartObjectArrayWithoutProperty"); internal static string CannotTranscodeInvalidUtf8 => GetResourceString("CannotTranscodeInvalidUtf8"); internal static string CannotDecodeInvalidBase64 => GetResourceString("CannotDecodeInvalidBase64"); internal static string CannotTranscodeInvalidUtf16 => GetResourceString("CannotTranscodeInvalidUtf16"); internal static string CannotEncodeInvalidUTF16 => GetResourceString("CannotEncodeInvalidUTF16"); internal static string CannotEncodeInvalidUTF8 => GetResourceString("CannotEncodeInvalidUTF8"); internal static string CannotWritePropertyWithinArray => GetResourceString("CannotWritePropertyWithinArray"); internal static string CannotWritePropertyAfterProperty => GetResourceString("CannotWritePropertyAfterProperty"); internal static string CannotWriteValueAfterPrimitiveOrClose => GetResourceString("CannotWriteValueAfterPrimitiveOrClose"); internal static string CannotWriteValueWithinObject => GetResourceString("CannotWriteValueWithinObject"); internal static string DepthTooLarge => GetResourceString("DepthTooLarge"); internal static string DestinationTooShort => GetResourceString("DestinationTooShort"); internal static string EmptyJsonIsInvalid => GetResourceString("EmptyJsonIsInvalid"); internal static string EndOfCommentNotFound => GetResourceString("EndOfCommentNotFound"); internal static string EndOfStringNotFound => GetResourceString("EndOfStringNotFound"); internal static string ExpectedEndAfterSingleJson => GetResourceString("ExpectedEndAfterSingleJson"); internal static string ExpectedEndOfDigitNotFound => GetResourceString("ExpectedEndOfDigitNotFound"); internal static string ExpectedFalse => GetResourceString("ExpectedFalse"); internal static string ExpectedJsonTokens => GetResourceString("ExpectedJsonTokens"); internal static string ExpectedOneCompleteToken => GetResourceString("ExpectedOneCompleteToken"); internal static string ExpectedNextDigitEValueNotFound => GetResourceString("ExpectedNextDigitEValueNotFound"); internal static string ExpectedNull => GetResourceString("ExpectedNull"); internal static string ExpectedSeparatorAfterPropertyNameNotFound => GetResourceString("ExpectedSeparatorAfterPropertyNameNotFound"); internal static string ExpectedStartOfPropertyNotFound => GetResourceString("ExpectedStartOfPropertyNotFound"); internal static string ExpectedStartOfPropertyOrValueNotFound => GetResourceString("ExpectedStartOfPropertyOrValueNotFound"); internal static string ExpectedStartOfValueNotFound => GetResourceString("ExpectedStartOfValueNotFound"); internal static string ExpectedTrue => GetResourceString("ExpectedTrue"); internal static string ExpectedValueAfterPropertyNameNotFound => GetResourceString("ExpectedValueAfterPropertyNameNotFound"); internal static string FailedToGetLargerSpan => GetResourceString("FailedToGetLargerSpan"); internal static string FoundInvalidCharacter => GetResourceString("FoundInvalidCharacter"); internal static string InvalidCast => GetResourceString("InvalidCast"); internal static string InvalidCharacterAfterEscapeWithinString => GetResourceString("InvalidCharacterAfterEscapeWithinString"); internal static string InvalidCharacterWithinString => GetResourceString("InvalidCharacterWithinString"); internal static string InvalidEnumTypeWithSpecialChar => GetResourceString("InvalidEnumTypeWithSpecialChar"); internal static string InvalidEndOfJsonNonPrimitive => GetResourceString("InvalidEndOfJsonNonPrimitive"); internal static string InvalidHexCharacterWithinString => GetResourceString("InvalidHexCharacterWithinString"); internal static string JsonDocumentDoesNotSupportComments => GetResourceString("JsonDocumentDoesNotSupportComments"); internal static string JsonElementHasWrongType => GetResourceString("JsonElementHasWrongType"); internal static string DefaultTypeInfoResolverImmutable => GetResourceString("DefaultTypeInfoResolverImmutable"); internal static string TypeInfoResolverChainImmutable => GetResourceString("TypeInfoResolverChainImmutable"); internal static string TypeInfoImmutable => GetResourceString("TypeInfoImmutable"); internal static string MaxDepthMustBePositive => GetResourceString("MaxDepthMustBePositive"); internal static string CommentHandlingMustBeValid => GetResourceString("CommentHandlingMustBeValid"); internal static string MismatchedObjectArray => GetResourceString("MismatchedObjectArray"); internal static string CannotWriteEndAfterProperty => GetResourceString("CannotWriteEndAfterProperty"); internal static string ObjectDepthTooLarge => GetResourceString("ObjectDepthTooLarge"); internal static string PropertyNameTooLarge => GetResourceString("PropertyNameTooLarge"); internal static string FormatDecimal => GetResourceString("FormatDecimal"); internal static string FormatDouble => GetResourceString("FormatDouble"); internal static string FormatInt32 => GetResourceString("FormatInt32"); internal static string FormatInt64 => GetResourceString("FormatInt64"); internal static string FormatSingle => GetResourceString("FormatSingle"); internal static string FormatUInt32 => GetResourceString("FormatUInt32"); internal static string FormatUInt64 => GetResourceString("FormatUInt64"); internal static string RequiredDigitNotFoundAfterDecimal => GetResourceString("RequiredDigitNotFoundAfterDecimal"); internal static string RequiredDigitNotFoundAfterSign => GetResourceString("RequiredDigitNotFoundAfterSign"); internal static string RequiredDigitNotFoundEndOfData => GetResourceString("RequiredDigitNotFoundEndOfData"); internal static string SpecialNumberValuesNotSupported => GetResourceString("SpecialNumberValuesNotSupported"); internal static string ValueTooLarge => GetResourceString("ValueTooLarge"); internal static string ZeroDepthAtEnd => GetResourceString("ZeroDepthAtEnd"); internal static string DeserializeUnableToConvertValue => GetResourceString("DeserializeUnableToConvertValue"); internal static string DeserializeWrongType => GetResourceString("DeserializeWrongType"); internal static string SerializationInvalidBufferSize => GetResourceString("SerializationInvalidBufferSize"); internal static string BufferWriterAdvancedTooFar => GetResourceString("BufferWriterAdvancedTooFar"); internal static string InvalidComparison => GetResourceString("InvalidComparison"); internal static string UnsupportedFormat => GetResourceString("UnsupportedFormat"); internal static string ExpectedStartOfPropertyOrValueAfterComment => GetResourceString("ExpectedStartOfPropertyOrValueAfterComment"); internal static string TrailingCommaNotAllowedBeforeArrayEnd => GetResourceString("TrailingCommaNotAllowedBeforeArrayEnd"); internal static string TrailingCommaNotAllowedBeforeObjectEnd => GetResourceString("TrailingCommaNotAllowedBeforeObjectEnd"); internal static string SerializerOptionsReadOnly => GetResourceString("SerializerOptionsReadOnly"); internal static string SerializerOptions_InvalidChainedResolver => GetResourceString("SerializerOptions_InvalidChainedResolver"); internal static string StreamNotWritable => GetResourceString("StreamNotWritable"); internal static string CannotWriteCommentWithEmbeddedDelimiter => GetResourceString("CannotWriteCommentWithEmbeddedDelimiter"); internal static string SerializerPropertyNameConflict => GetResourceString("SerializerPropertyNameConflict"); internal static string SerializerPropertyNameNull => GetResourceString("SerializerPropertyNameNull"); internal static string SerializationDataExtensionPropertyInvalid => GetResourceString("SerializationDataExtensionPropertyInvalid"); internal static string SerializationDuplicateTypeAttribute => GetResourceString("SerializationDuplicateTypeAttribute"); internal static string ExtensionDataConflictsWithUnmappedMemberHandling => GetResourceString("ExtensionDataConflictsWithUnmappedMemberHandling"); internal static string SerializationNotSupportedType => GetResourceString("SerializationNotSupportedType"); internal static string TypeRequiresAsyncSerialization => GetResourceString("TypeRequiresAsyncSerialization"); internal static string InvalidCharacterAtStartOfComment => GetResourceString("InvalidCharacterAtStartOfComment"); internal static string UnexpectedEndOfDataWhileReadingComment => GetResourceString("UnexpectedEndOfDataWhileReadingComment"); internal static string CannotSkip => GetResourceString("CannotSkip"); internal static string NotEnoughData => GetResourceString("NotEnoughData"); internal static string UnexpectedEndOfLineSeparator => GetResourceString("UnexpectedEndOfLineSeparator"); internal static string JsonSerializerDoesNotSupportComments => GetResourceString("JsonSerializerDoesNotSupportComments"); internal static string DeserializeNoConstructor => GetResourceString("DeserializeNoConstructor"); internal static string DeserializePolymorphicInterface => GetResourceString("DeserializePolymorphicInterface"); internal static string SerializationConverterOnAttributeNotCompatible => GetResourceString("SerializationConverterOnAttributeNotCompatible"); internal static string SerializationConverterOnAttributeInvalid => GetResourceString("SerializationConverterOnAttributeInvalid"); internal static string SerializationConverterRead => GetResourceString("SerializationConverterRead"); internal static string SerializationConverterNotCompatible => GetResourceString("SerializationConverterNotCompatible"); internal static string ResolverTypeNotCompatible => GetResourceString("ResolverTypeNotCompatible"); internal static string ResolverTypeInfoOptionsNotCompatible => GetResourceString("ResolverTypeInfoOptionsNotCompatible"); internal static string SerializationConverterWrite => GetResourceString("SerializationConverterWrite"); internal static string NamingPolicyReturnNull => GetResourceString("NamingPolicyReturnNull"); internal static string SerializationDuplicateAttribute => GetResourceString("SerializationDuplicateAttribute"); internal static string SerializeUnableToSerialize => GetResourceString("SerializeUnableToSerialize"); internal static string FormatByte => GetResourceString("FormatByte"); internal static string FormatInt16 => GetResourceString("FormatInt16"); internal static string FormatSByte => GetResourceString("FormatSByte"); internal static string FormatUInt16 => GetResourceString("FormatUInt16"); internal static string SerializerCycleDetected => GetResourceString("SerializerCycleDetected"); internal static string InvalidLeadingZeroInNumber => GetResourceString("InvalidLeadingZeroInNumber"); internal static string MetadataCannotParsePreservedObjectToImmutable => GetResourceString("MetadataCannotParsePreservedObjectToImmutable"); internal static string MetadataDuplicateIdFound => GetResourceString("MetadataDuplicateIdFound"); internal static string MetadataIdIsNotFirstProperty => GetResourceString("MetadataIdIsNotFirstProperty"); internal static string MetadataInvalidReferenceToValueType => GetResourceString("MetadataInvalidReferenceToValueType"); internal static string MetadataInvalidTokenAfterValues => GetResourceString("MetadataInvalidTokenAfterValues"); internal static string MetadataPreservedArrayFailed => GetResourceString("MetadataPreservedArrayFailed"); internal static string MetadataInvalidPropertyInArrayMetadata => GetResourceString("MetadataInvalidPropertyInArrayMetadata"); internal static string MetadataStandaloneValuesProperty => GetResourceString("MetadataStandaloneValuesProperty"); internal static string MetadataReferenceCannotContainOtherProperties => GetResourceString("MetadataReferenceCannotContainOtherProperties"); internal static string MetadataReferenceNotFound => GetResourceString("MetadataReferenceNotFound"); internal static string MetadataValueWasNotString => GetResourceString("MetadataValueWasNotString"); internal static string MetadataInvalidPropertyWithLeadingDollarSign => GetResourceString("MetadataInvalidPropertyWithLeadingDollarSign"); internal static string MetadataUnexpectedProperty => GetResourceString("MetadataUnexpectedProperty"); internal static string UnmappedJsonProperty => GetResourceString("UnmappedJsonProperty"); internal static string MetadataDuplicateTypeProperty => GetResourceString("MetadataDuplicateTypeProperty"); internal static string MultipleMembersBindWithConstructorParameter => GetResourceString("MultipleMembersBindWithConstructorParameter"); internal static string ConstructorParamIncompleteBinding => GetResourceString("ConstructorParamIncompleteBinding"); internal static string ObjectWithParameterizedCtorRefMetadataNotSupported => GetResourceString("ObjectWithParameterizedCtorRefMetadataNotSupported"); internal static string SerializerConverterFactoryReturnsNull => GetResourceString("SerializerConverterFactoryReturnsNull"); internal static string SerializationNotSupportedParentType => GetResourceString("SerializationNotSupportedParentType"); internal static string ExtensionDataCannotBindToCtorParam => GetResourceString("ExtensionDataCannotBindToCtorParam"); internal static string BufferMaximumSizeExceeded => GetResourceString("BufferMaximumSizeExceeded"); internal static string CannotSerializeInvalidType => GetResourceString("CannotSerializeInvalidType"); internal static string SerializeTypeInstanceNotSupported => GetResourceString("SerializeTypeInstanceNotSupported"); internal static string JsonIncludeOnInaccessibleProperty => GetResourceString("JsonIncludeOnInaccessibleProperty"); internal static string CannotSerializeInvalidMember => GetResourceString("CannotSerializeInvalidMember"); internal static string CannotPopulateCollection => GetResourceString("CannotPopulateCollection"); internal static string ConstructorContainsNullParameterNames => GetResourceString("ConstructorContainsNullParameterNames"); internal static string DefaultIgnoreConditionAlreadySpecified => GetResourceString("DefaultIgnoreConditionAlreadySpecified"); internal static string DefaultIgnoreConditionInvalid => GetResourceString("DefaultIgnoreConditionInvalid"); internal static string DictionaryKeyTypeNotSupported => GetResourceString("DictionaryKeyTypeNotSupported"); internal static string IgnoreConditionOnValueTypeInvalid => GetResourceString("IgnoreConditionOnValueTypeInvalid"); internal static string NumberHandlingOnPropertyInvalid => GetResourceString("NumberHandlingOnPropertyInvalid"); internal static string ConverterCanConvertMultipleTypes => GetResourceString("ConverterCanConvertMultipleTypes"); internal static string MetadataReferenceOfTypeCannotBeAssignedToType => GetResourceString("MetadataReferenceOfTypeCannotBeAssignedToType"); internal static string DeserializeUnableToAssignValue => GetResourceString("DeserializeUnableToAssignValue"); internal static string DeserializeUnableToAssignNull => GetResourceString("DeserializeUnableToAssignNull"); internal static string SerializerConverterFactoryReturnsJsonConverterFactory => GetResourceString("SerializerConverterFactoryReturnsJsonConverterFactory"); internal static string SerializerConverterFactoryInvalidArgument => GetResourceString("SerializerConverterFactoryInvalidArgument"); internal static string NodeElementWrongType => GetResourceString("NodeElementWrongType"); internal static string NodeElementCannotBeObjectOrArray => GetResourceString("NodeElementCannotBeObjectOrArray"); internal static string NodeAlreadyHasParent => GetResourceString("NodeAlreadyHasParent"); internal static string NodeCycleDetected => GetResourceString("NodeCycleDetected"); internal static string NodeUnableToConvert => GetResourceString("NodeUnableToConvert"); internal static string NodeUnableToConvertElement => GetResourceString("NodeUnableToConvertElement"); internal static string NodeValueNotAllowed => GetResourceString("NodeValueNotAllowed"); internal static string NodeWrongType => GetResourceString("NodeWrongType"); internal static string NodeParentWrongType => GetResourceString("NodeParentWrongType"); internal static string NodeDuplicateKey => GetResourceString("NodeDuplicateKey"); internal static string SerializerContextOptionsReadOnly => GetResourceString("SerializerContextOptionsReadOnly"); internal static string ConverterForPropertyMustBeValid => GetResourceString("ConverterForPropertyMustBeValid"); internal static string NoMetadataForType => GetResourceString("NoMetadataForType"); internal static string AmbiguousMetadataForType => GetResourceString("AmbiguousMetadataForType"); internal static string CollectionIsReadOnly => GetResourceString("CollectionIsReadOnly"); internal static string ArrayIndexNegative => GetResourceString("ArrayIndexNegative"); internal static string ArrayTooSmall => GetResourceString("ArrayTooSmall"); internal static string NodeJsonObjectCustomConverterNotAllowedOnExtensionProperty => GetResourceString("NodeJsonObjectCustomConverterNotAllowedOnExtensionProperty"); internal static string NoMetadataForTypeProperties => GetResourceString("NoMetadataForTypeProperties"); internal static string FieldCannotBeVirtual => GetResourceString("FieldCannotBeVirtual"); internal static string MissingFSharpCoreMember => GetResourceString("MissingFSharpCoreMember"); internal static string FSharpDiscriminatedUnionsNotSupported => GetResourceString("FSharpDiscriminatedUnionsNotSupported"); internal static string Polymorphism_BaseConverterDoesNotSupportMetadata => GetResourceString("Polymorphism_BaseConverterDoesNotSupportMetadata"); internal static string Polymorphism_DerivedConverterDoesNotSupportMetadata => GetResourceString("Polymorphism_DerivedConverterDoesNotSupportMetadata"); internal static string Polymorphism_TypeDoesNotSupportPolymorphism => GetResourceString("Polymorphism_TypeDoesNotSupportPolymorphism"); internal static string Polymorphism_DerivedTypeIsNotSupported => GetResourceString("Polymorphism_DerivedTypeIsNotSupported"); internal static string Polymorphism_DerivedTypeIsAlreadySpecified => GetResourceString("Polymorphism_DerivedTypeIsAlreadySpecified"); internal static string Polymorphism_TypeDicriminatorIdIsAlreadySpecified => GetResourceString("Polymorphism_TypeDicriminatorIdIsAlreadySpecified"); internal static string Polymorphism_InvalidCustomTypeDiscriminatorPropertyName => GetResourceString("Polymorphism_InvalidCustomTypeDiscriminatorPropertyName"); internal static string Polymorphism_ConfigurationDoesNotSpecifyDerivedTypes => GetResourceString("Polymorphism_ConfigurationDoesNotSpecifyDerivedTypes"); internal static string Polymorphism_UnrecognizedTypeDiscriminator => GetResourceString("Polymorphism_UnrecognizedTypeDiscriminator"); internal static string Polymorphism_RuntimeTypeNotSupported => GetResourceString("Polymorphism_RuntimeTypeNotSupported"); internal static string Polymorphism_RuntimeTypeDiamondAmbiguity => GetResourceString("Polymorphism_RuntimeTypeDiamondAmbiguity"); internal static string InvalidJsonTypeInfoOperationForKind => GetResourceString("InvalidJsonTypeInfoOperationForKind"); internal static string CreateObjectConverterNotCompatible => GetResourceString("CreateObjectConverterNotCompatible"); internal static string JsonPropertyInfoBoundToDifferentParent => GetResourceString("JsonPropertyInfoBoundToDifferentParent"); internal static string JsonSerializerOptionsNoTypeInfoResolverSpecified => GetResourceString("JsonSerializerOptionsNoTypeInfoResolverSpecified"); internal static string JsonSerializerIsReflectionDisabled => GetResourceString("JsonSerializerIsReflectionDisabled"); internal static string JsonPolymorphismOptionsAssociatedWithDifferentJsonTypeInfo => GetResourceString("JsonPolymorphismOptionsAssociatedWithDifferentJsonTypeInfo"); internal static string JsonPropertyRequiredAndNotDeserializable => GetResourceString("JsonPropertyRequiredAndNotDeserializable"); internal static string JsonPropertyRequiredAndExtensionData => GetResourceString("JsonPropertyRequiredAndExtensionData"); internal static string JsonRequiredPropertiesMissing => GetResourceString("JsonRequiredPropertiesMissing"); internal static string ObjectCreationHandlingPopulateNotSupportedByConverter => GetResourceString("ObjectCreationHandlingPopulateNotSupportedByConverter"); internal static string ObjectCreationHandlingPropertyMustHaveAGetter => GetResourceString("ObjectCreationHandlingPropertyMustHaveAGetter"); internal static string ObjectCreationHandlingPropertyValueTypeMustHaveASetter => GetResourceString("ObjectCreationHandlingPropertyValueTypeMustHaveASetter"); internal static string ObjectCreationHandlingPropertyCannotAllowPolymorphicDeserialization => GetResourceString("ObjectCreationHandlingPropertyCannotAllowPolymorphicDeserialization"); internal static string ObjectCreationHandlingPropertyCannotAllowReadOnlyMember => GetResourceString("ObjectCreationHandlingPropertyCannotAllowReadOnlyMember"); internal static string ObjectCreationHandlingPropertyCannotAllowReferenceHandling => GetResourceString("ObjectCreationHandlingPropertyCannotAllowReferenceHandling"); internal static string ObjectCreationHandlingPropertyDoesNotSupportParameterizedConstructors => GetResourceString("ObjectCreationHandlingPropertyDoesNotSupportParameterizedConstructors"); internal static string FormatInt128 => GetResourceString("FormatInt128"); internal static string FormatUInt128 => GetResourceString("FormatUInt128"); internal static string FormatHalf => GetResourceString("FormatHalf"); internal static bool UsingResourceKeys() { return s_usingResourceKeys; } private static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } private static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider provider, string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)] internal sealed class ObsoleteAttribute : Attribute { public string Message { get; } public bool IsError { get; } public string DiagnosticId { get; set; } public string UrlFormat { get; set; } public ObsoleteAttribute() { } public ObsoleteAttribute(string message) { Message = message; } public ObsoleteAttribute(string message, bool error) { Message = message; IsError = error; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] internal sealed class DynamicDependencyAttribute : Attribute { public string MemberSignature { get; } public DynamicallyAccessedMemberTypes MemberTypes { get; } public Type Type { get; } public string TypeName { get; } public string AssemblyName { get; } public string Condition { get; set; } public DynamicDependencyAttribute(string memberSignature) { MemberSignature = memberSignature; } public DynamicDependencyAttribute(string memberSignature, Type type) { MemberSignature = memberSignature; Type = type; } public DynamicDependencyAttribute(string memberSignature, string typeName, string assemblyName) { MemberSignature = memberSignature; TypeName = typeName; AssemblyName = assemblyName; } public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, Type type) { MemberTypes = memberTypes; Type = type; } public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, string typeName, string assemblyName) { MemberTypes = memberTypes; TypeName = typeName; AssemblyName = assemblyName; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, Inherited = false)] internal sealed class DynamicallyAccessedMembersAttribute : Attribute { public DynamicallyAccessedMemberTypes MemberTypes { get; } public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes) { MemberTypes = memberTypes; } } [Flags] internal enum DynamicallyAccessedMemberTypes { None = 0, PublicParameterlessConstructor = 1, PublicConstructors = 3, NonPublicConstructors = 4, PublicMethods = 8, NonPublicMethods = 0x10, PublicFields = 0x20, NonPublicFields = 0x40, PublicNestedTypes = 0x80, NonPublicNestedTypes = 0x100, PublicProperties = 0x200, NonPublicProperties = 0x400, PublicEvents = 0x800, NonPublicEvents = 0x1000, Interfaces = 0x2000, All = -1 } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] internal sealed class RequiresUnreferencedCodeAttribute : Attribute { public string Message { get; } public string Url { get; set; } public RequiresUnreferencedCodeAttribute(string message) { Message = message; } } [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)] internal sealed class UnconditionalSuppressMessageAttribute : Attribute { public string Category { get; } public string CheckId { get; } public string Scope { get; set; } public string Target { get; set; } public string MessageId { get; set; } public string Justification { get; set; } public UnconditionalSuppressMessageAttribute(string category, string checkId) { Category = category; CheckId = checkId; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] internal sealed class StringSyntaxAttribute : Attribute { public const string CompositeFormat = "CompositeFormat"; public const string DateOnlyFormat = "DateOnlyFormat"; public const string DateTimeFormat = "DateTimeFormat"; public const string EnumFormat = "EnumFormat"; public const string GuidFormat = "GuidFormat"; public const string Json = "Json"; public const string NumericFormat = "NumericFormat"; public const string Regex = "Regex"; public const string TimeOnlyFormat = "TimeOnlyFormat"; public const string TimeSpanFormat = "TimeSpanFormat"; public const string Uri = "Uri"; public const string Xml = "Xml"; public string Syntax { get; } public object[] Arguments { get; } public StringSyntaxAttribute(string syntax) { Syntax = syntax; Arguments = Array.Empty<object>(); } public StringSyntaxAttribute(string syntax, params object[] arguments) { Syntax = syntax; Arguments = arguments; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] internal sealed class RequiresDynamicCodeAttribute : Attribute { public string Message { get; } public string Url { get; set; } public RequiresDynamicCodeAttribute(string message) { Message = message; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] internal sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] internal sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class LibraryImportAttribute : Attribute { public string LibraryName { get; } public string EntryPoint { get; set; } public StringMarshalling StringMarshalling { get; set; } public Type StringMarshallingCustomType { get; set; } public bool SetLastError { get; set; } public LibraryImportAttribute(string libraryName) { LibraryName = libraryName; } } internal enum StringMarshalling { Custom, Utf8, Utf16 } } namespace System.Runtime.Versioning { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)] internal sealed class RequiresPreviewFeaturesAttribute : Attribute { public string Message { get; } public string Url { get; set; } public RequiresPreviewFeaturesAttribute() { } public RequiresPreviewFeaturesAttribute(string message) { Message = message; } } } namespace System.Runtime.CompilerServices { [EditorBrowsable(EditorBrowsableState.Never)] internal static class IsExternalInit { } } namespace System.Collections.Generic { internal sealed class ReferenceEqualityComparer : IEqualityComparer<object>, IEqualityComparer { public static ReferenceEqualityComparer Instance { get; } = new ReferenceEqualityComparer(); private ReferenceEqualityComparer() { } public new bool Equals(object x, object y) { return x == y; } public int GetHashCode(object obj) { return RuntimeHelpers.GetHashCode(obj); } } internal static class StackExtensions { public static bool TryPeek<T>(this Stack<T> stack, [MaybeNullWhen(false)] out T result) { if (stack.Count > 0) { result = stack.Peek(); return true; } result = default(T); return false; } public static bool TryPop<T>(this Stack<T> stack, [MaybeNullWhen(false)] out T result) { if (stack.Count > 0) { result = stack.Pop(); return true; } result = default(T); return false; } } } namespace System.Buffers { internal sealed class ArrayBufferWriter<T> : IBufferWriter<T> { private const int ArrayMaxLength = 2147483591; private const int DefaultInitialBufferSize = 256; private T[] _buffer; private int _index; public ReadOnlyMemory<T> WrittenMemory => _buffer.AsMemory(0, _index); public ReadOnlySpan<T> WrittenSpan => _buffer.AsSpan(0, _index); public int WrittenCount => _index; public int Capacity => _buffer.Length; public int FreeCapacity => _buffer.Length - _index; public ArrayBufferWriter() { _buffer = Array.Empty<T>(); _index = 0; } public ArrayBufferWriter(int initialCapacity) { if (initialCapacity <= 0) { throw new ArgumentException(null, "initialCapacity"); } _buffer = new T[initialCapacity]; _index = 0; } public void Clear() { _buffer.AsSpan(0, _index).Clear(); _index = 0; } public void ResetWrittenCount() { _index = 0; } public void Advance(int count) { if (count < 0) { throw new ArgumentException(null, "count"); } if (_index > _buffer.Length - count) { ThrowInvalidOperationException_AdvancedTooFar(_buffer.Length); } _index += count; } public Memory<T> GetMemory(int sizeHint = 0) { CheckAndResizeBuffer(sizeHint); return _buffer.AsMemory(_index); } public Span<T> GetSpan(int sizeHint = 0) { CheckAndResizeBuffer(sizeHint); return _buffer.AsSpan(_index); } private void CheckAndResizeBuffer(int sizeHint) { if (sizeHint < 0) { throw new ArgumentException("sizeHint"); } if (sizeHint == 0) { sizeHint = 1; } if (sizeHint <= FreeCapacity) { return; } int num = _buffer.Length; int num2 = Math.Max(sizeHint, num); if (num == 0) { num2 = Math.Max(num2, 256); } int num3 = num + num2; if ((uint)num3 > 2147483647u) { uint num4 = (uint)(num - FreeCapacity + sizeHint); if (num4 > 2147483591) { ThrowOutOfMemoryException(num4); } num3 = 2147483591; } Array.Resize(ref _buffer, num3); } private static void ThrowInvalidOperationException_AdvancedTooFar(int capacity) { throw new InvalidOperationException(System.SR.Format(System.SR.BufferWriterAdvancedTooFar, capacity)); } private static void ThrowOutOfMemoryException(uint capacity) { throw new OutOfMemoryException(System.SR.Format(System.SR.BufferMaximumSizeExceeded, capacity)); } } } namespace System.Buffers.Text { internal enum SequenceValidity { Empty, WellFormed, Incomplete, Invalid } } namespace System.Text.Json { internal sealed class PooledByteBufferWriter : IBufferWriter<byte>, IDisposable { private byte[] _rentedBuffer; private int _index; private const int MinimumBufferSize = 256; public const int MaximumBufferSize = 2147483591; public ReadOnlyMemory<byte> WrittenMemory => _rentedBuffer.AsMemory(0, _index); public int WrittenCount => _index; public int Capacity => _rentedBuffer.Length; public int FreeCapacity => _rentedBuffer.Length - _index; private PooledByteBufferWriter() { } public PooledByteBufferWriter(int initialCapacity) : this() { _rentedBuffer = ArrayPool<byte>.Shared.Rent(initialCapacity); _index = 0; } public void Clear() { ClearHelper(); } public void ClearAndReturnBuffers() { ClearHelper(); byte[] rentedBuffer = _rentedBuffer; _rentedBuffer = null; ArrayPool<byte>.Shared.Return(rentedBuffer); } private void ClearHelper() { _rentedBuffer.AsSpan(0, _index).Clear(); _index = 0; } public void Dispose() { if (_rentedBuffer != null) { ClearHelper(); byte[] rentedBuffer = _rentedBuffer; _rentedBuffer = null; ArrayPool<byte>.Shared.Return(rentedBuffer); } } public void InitializeEmptyInstance(int initialCapacity) { _rentedBuffer = ArrayPool<byte>.Shared.Rent(initialCapacity); _index = 0; } public static PooledByteBufferWriter CreateEmptyInstanceForCaching() { return new PooledByteBufferWriter(); } public void Advance(int count) { _index += count; } public Memory<byte> GetMemory(int sizeHint = 256) { CheckAndResizeBuffer(sizeHint); return _rentedBuffer.AsMemory(_index); } public Span<byte> GetSpan(int sizeHint = 256) { CheckAndResizeBuffer(sizeHint); return _rentedBuffer.AsSpan(_index); } internal Task WriteToStreamAsync(Stream destination, CancellationToken cancellationToken) { return destination.WriteAsync(_rentedBuffer, 0, _index, cancellationToken); } internal void WriteToStream(Stream destination) { destination.Write(_rentedBuffer, 0, _index); } private void CheckAndResizeBuffer(int sizeHint) { int num = _rentedBuffer.Length; int num2 = num - _index; if (_index >= 1073741795) { sizeHint = Math.Max(sizeHint, 2147483591 - num); } if (sizeHint <= num2) { return; } int num3 = Math.Max(sizeHint, num); int num4 = num + num3; if ((uint)num4 > 2147483591u) { num4 = num + sizeHint; if ((uint)num4 > 2147483591u) { ThrowHelper.ThrowOutOfMemoryException_BufferMaximumSizeExceeded((uint)num4); } } byte[] rentedBuffer = _rentedBuffer; _rentedBuffer = ArrayPool<byte>.Shared.Rent(num4); Span<byte> span = rentedBuffer.AsSpan(0, _index); span.CopyTo(_rentedBuffer); span.Clear(); ArrayPool<byte>.Shared.Return(rentedBuffer); } } internal static class ThrowHelper { public const string ExceptionSourceValueToRethrowAsJsonException = "System.Text.Json.Rethrowable"; [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowOutOfMemoryException_BufferMaximumSizeExceeded(uint capacity) { throw new OutOfMemoryException(System.SR.Format(System.SR.BufferMaximumSizeExceeded, capacity)); } [DoesNotReturn] public static void ThrowArgumentNullException(string parameterName) { throw new ArgumentNullException(parameterName); } [DoesNotReturn] public static void ThrowArgumentOutOfRangeException_MaxDepthMustBePositive(string parameterName) { throw GetArgumentOutOfRangeException(parameterName, System.SR.MaxDepthMustBePositive); } private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(string parameterName, string message) { return new ArgumentOutOfRangeException(parameterName, message); } [DoesNotReturn] public static void ThrowArgumentOutOfRangeException_CommentEnumMustBeInRange(string parameterName) { throw GetArgumentOutOfRangeException(parameterName, System.SR.CommentHandlingMustBeValid); } [DoesNotReturn] public static void ThrowArgumentOutOfRangeException_ArrayIndexNegative(string paramName) { throw new ArgumentOutOfRangeException(paramName, System.SR.ArrayIndexNegative); } [DoesNotReturn] public static void ThrowArgumentOutOfRangeException_JsonConverterFactory_TypeNotSupported(Type typeToConvert) { throw new ArgumentOutOfRangeException("typeToConvert", System.SR.Format(System.SR.SerializerConverterFactoryInvalidArgument, typeToConvert.FullName)); } [DoesNotReturn] public static void ThrowArgumentException_ArrayTooSmall(string paramName) { throw new ArgumentException(System.SR.ArrayTooSmall, paramName); } private static ArgumentException GetArgumentException(string message) { return new ArgumentException(message); } [DoesNotReturn] public static void ThrowArgumentException(string message) { throw GetArgumentException(message); } public static InvalidOperationException GetInvalidOperationException_CallFlushFirst(int _buffered) { return GetInvalidOperationException(System.SR.Format(System.SR.CallFlushToAvoidDataLoss, _buffered)); } [DoesNotReturn] public static void ThrowArgumentException_DestinationTooShort() { throw GetArgumentException(System.SR.DestinationTooShort); } [DoesNotReturn] public static void ThrowArgumentException_PropertyNameTooLarge(int tokenLength) { throw GetArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, tokenLength)); } [DoesNotReturn] public static void ThrowArgumentException_ValueTooLarge(long tokenLength) { throw GetArgumentException(System.SR.Format(System.SR.ValueTooLarge, tokenLength)); } [DoesNotReturn] public static void ThrowArgumentException_ValueNotSupported() { throw GetArgumentException(System.SR.SpecialNumberValuesNotSupported); } [DoesNotReturn] public static void ThrowInvalidOperationException_NeedLargerSpan() { throw GetInvalidOperationException(System.SR.FailedToGetLargerSpan); } [DoesNotReturn] public static void ThrowPropertyNameTooLargeArgumentException(int length) { throw GetArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, length)); } [DoesNotReturn] public static void ThrowArgumentException(ReadOnlySpan<byte> propertyName, ReadOnlySpan<byte> value) { if (propertyName.Length > 166666666) { ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length)); } else { ThrowArgumentException(System.SR.Format(System.SR.ValueTooLarge, value.Length)); } } [DoesNotReturn] public static void ThrowArgumentException(ReadOnlySpan<byte> propertyName, ReadOnlySpan<char> value) { if (propertyName.Length > 166666666) { ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length)); } else { ThrowArgumentException(System.SR.Format(System.SR.ValueTooLarge, value.Length)); } } [DoesNotReturn] public static void ThrowArgumentException(ReadOnlySpan<char> propertyName, ReadOnlySpan<byte> value) { if (propertyName.Length > 166666666) { ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length)); } else { ThrowArgumentException(System.SR.Format(System.SR.ValueTooLarge, value.Length)); } } [DoesNotReturn] public static void ThrowArgumentException(ReadOnlySpan<char> propertyName, ReadOnlySpan<char> value) { if (propertyName.Length > 166666666) { ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length)); } else { ThrowArgumentException(System.SR.Format(System.SR.ValueTooLarge, value.Length)); } } [DoesNotReturn] public static void ThrowInvalidOperationOrArgumentException(ReadOnlySpan<byte> propertyName, int currentDepth, int maxDepth) { currentDepth &= 0x7FFFFFFF; if (currentDepth >= maxDepth) { ThrowInvalidOperationException(System.SR.Format(System.SR.DepthTooLarge, currentDepth, maxDepth)); } else { ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length)); } } [DoesNotReturn] public static void ThrowInvalidOperationException(int currentDepth, int maxDepth) { currentDepth &= 0x7FFFFFFF; ThrowInvalidOperationException(System.SR.Format(System.SR.DepthTooLarge, currentDepth, maxDepth)); } [DoesNotReturn] public static void ThrowInvalidOperationException(string message) { throw GetInvalidOperationException(message); } private static InvalidOperationException GetInvalidOperationException(string message) { return new InvalidOperationException(message) { Source = "System.Text.Json.Rethrowable" }; } [DoesNotReturn] public static void ThrowInvalidOperationException_DepthNonZeroOrEmptyJson(int currentDepth) { throw GetInvalidOperationException(currentDepth); } private static InvalidOperationException GetInvalidOperationException(int currentDepth) { currentDepth &= 0x7FFFFFFF; if (currentDepth != 0) { return GetInvalidOperationException(System.SR.Format(System.SR.ZeroDepthAtEnd, currentDepth)); } return GetInvalidOperationException(System.SR.EmptyJsonIsInvalid); } [DoesNotReturn] public static void ThrowInvalidOperationOrArgumentException(ReadOnlySpan<char> propertyName, int currentDepth, int maxDepth) { currentDepth &= 0x7FFFFFFF; if (currentDepth >= maxDepth) { ThrowInvalidOperationException(System.SR.Format(System.SR.DepthTooLarge, currentDepth, maxDepth)); } else { ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length)); } } public static InvalidOperationException GetInvalidOperationException_ExpectedArray(JsonTokenType tokenType) { return GetInvalidOperationException("array", tokenType); } public static InvalidOperationException GetInvalidOperationException_ExpectedObject(JsonTokenType tokenType) { return GetInvalidOperationException("object", tokenType); } [DoesNotReturn] public static void ThrowInvalidOperationException_ExpectedNumber(JsonTokenType tokenType) { throw GetInvalidOperationException("number", tokenType); } [DoesNotReturn] public static void ThrowInvalidOperationException_ExpectedBoolean(JsonTokenType tokenType) { throw GetInvalidOperationException("boolean", tokenType); } [DoesNotReturn] public static void ThrowInvalidOperationException_ExpectedString(JsonTokenType tokenType) { throw GetInvalidOperationException("string", tokenType); } [DoesNotReturn] public static void ThrowInvalidOperationException_ExpectedPropertyName(JsonTokenType tokenType) { throw GetInvalidOperationException("propertyName", tokenType); } [DoesNotReturn] public static void ThrowInvalidOperationException_ExpectedStringComparison(JsonTokenType tokenType) { throw GetInvalidOperationException(tokenType); } [DoesNotReturn] public static void ThrowInvalidOperationException_ExpectedComment(JsonTokenType tokenType) { throw GetInvalidOperationException("comment", tokenType); } [DoesNotReturn] public static void ThrowInvalidOperationException_CannotSkipOnPartial() { throw GetInvalidOperationException(System.SR.CannotSkip); } private static InvalidOperationException GetInvalidOperationException(string message, JsonTokenType tokenType) { return GetInvalidOperationException(System.SR.Format(System.SR.InvalidCast, tokenType, message)); } private static InvalidOperationException GetInvalidOperationException(JsonTokenType tokenType) { return GetInvalidOperationException(System.SR.Format(System.SR.InvalidComparison, tokenType)); } [DoesNotReturn] internal static void ThrowJsonElementWrongTypeException(JsonTokenType expectedType, JsonTokenType actualType) { throw GetJsonElementWrongTypeException(expectedType.ToValueKind(), actualType.ToValueKind()); } internal static InvalidOperationException GetJsonElementWrongTypeException(JsonValueKind expectedType, JsonValueKind actualType) { return GetInvalidOperationException(System.SR.Format(System.SR.JsonElementHasWrongType, expectedType, actualType)); } internal static InvalidOperationException GetJsonElementWrongTypeException(string expectedTypeName, JsonValueKind actualType) { return GetInvalidOperationException(System.SR.Format(System.SR.JsonElementHasWrongType, expectedTypeName, actualType)); } [DoesNotReturn] public static void ThrowJsonReaderException(ref Utf8JsonReader json, ExceptionResource resource, byte nextByte = 0, ReadOnlySpan<byte> bytes = default(ReadOnlySpan<byte>)) { throw GetJsonReaderException(ref json, resource, nextByte, bytes); } [MethodImpl(MethodImplOptions.NoInlining)] public static JsonException GetJsonReaderException(ref Utf8JsonReader json, ExceptionResource resource, byte nextByte, ReadOnlySpan<byte> bytes) { string resourceString = GetResourceString(ref json, resource, nextByte, JsonHelpers.Utf8GetString(bytes)); long lineNumber = json.CurrentState._lineNumber; long bytePositionInLine = json.CurrentState._bytePositionInLine; resourceString += $" LineNumber: {lineNumber} | BytePositionInLine: {bytePositionInLine}."; return new JsonReaderException(resourceString, lineNumber, bytePositionInLine); } private static bool IsPrintable(byte value) { if (value >= 32) { return value < 127; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static string GetPrintableString(byte value) { if (!IsPrintable(value)) { return $"0x{value:X2}"; } char c = (char)value; return c.ToString(); } [MethodImpl(MethodImplOptions.NoInlining)] private static string GetResourceString(ref Utf8JsonReader json, ExceptionResource resource, byte nextByte, string characters) { string printableString = GetPrintableString(nextByte); string result = ""; switch (resource) { case ExceptionResource.ArrayDepthTooLarge: result = System.SR.Format(System.SR.ArrayDepthTooLarge, json.CurrentState.Options.MaxDepth); break; case ExceptionResource.MismatchedObjectArray: result = System.SR.Format(System.SR.MismatchedObjectArray, printableString); break; case ExceptionResource.TrailingCommaNotAllowedBeforeArrayEnd: result = System.SR.TrailingCommaNotAllowedBeforeArrayEnd; break; case ExceptionResource.TrailingCommaNotAllowedBeforeObjectEnd: result = System.SR.TrailingCommaNotAllowedBeforeObjectEnd; break; case ExceptionResource.EndOfStringNotFound: result = System.SR.EndOfStringNotFound; break; case ExceptionResource.RequiredDigitNotFoundAfterSign: result = System.SR.Format(System.SR.RequiredDigitNotFoundAfterSign, printableString); break; case ExceptionResource.RequiredDigitNotFoundAfterDecimal: result = System.SR.Format(System.SR.RequiredDigitNotFoundAfterDecimal, printableString); break; case ExceptionResource.RequiredDigitNotFoundEndOfData: result = System.SR.RequiredDigitNotFoundEndOfData; break; case ExceptionResource.ExpectedEndAfterSingleJson: result = System.SR.Format(System.SR.ExpectedEndAfterSingleJson, printableString); break; case ExceptionResource.ExpectedEndOfDigitNotFound: result = System.SR.Format(System.SR.ExpectedEndOfDigitNotFound, printableString); break; case ExceptionResource.ExpectedNextDigitEValueNotFound: result = System.SR.Format(System.SR.ExpectedNextDigitEValueNotFound, printableString); break; case ExceptionResource.ExpectedSeparatorAfterPropertyNameNotFound: result = System.SR.Format(System.SR.ExpectedSeparatorAfterPropertyNameNotFound, printableString); break; case ExceptionResource.ExpectedStartOfPropertyNotFound: result = System.SR.Format(System.SR.ExpectedStartOfPropertyNotFound, printableString); break; case ExceptionResource.ExpectedStartOfPropertyOrValueNotFound: result = System.SR.ExpectedStartOfPropertyOrValueNotFound; break; case ExceptionResource.ExpectedStartOfPropertyOrValueAfterComment: result = System.SR.Format(System.SR.ExpectedStartOfPropertyOrValueAfterComment, printableString); break; case ExceptionResource.ExpectedStartOfValueNotFound: result = System.SR.Format(System.SR.ExpectedStartOfValueNotFound, printableString); break; case ExceptionResource.ExpectedValueAfterPropertyNameNotFound: result = System.SR.ExpectedValueAfterPropertyNameNotFound; break; case ExceptionResource.FoundInvalidCharacter: result = System.SR.Format(System.SR.FoundInvalidCharacter, printableString); break; case ExceptionResource.InvalidEndOfJsonNonPrimitive: result = System.SR.Format(System.SR.InvalidEndOfJsonNonPrimitive, json.TokenType); break; case ExceptionResource.ObjectDepthTooLarge: result = System.SR.Format(System.SR.ObjectDepthTooLarge, json.CurrentState.Options.MaxDepth); break; case ExceptionResource.ExpectedFalse: result = System.SR.Format(System.SR.ExpectedFalse, characters); break; case ExceptionResource.ExpectedNull: result = System.SR.Format(System.SR.ExpectedNull, characters); break; case ExceptionResource.ExpectedTrue: result = System.SR.Format(System.SR.ExpectedTrue, characters); break; case ExceptionResource.InvalidCharacterWithinString: result = System.SR.Format(System.SR.InvalidCharacterWithinString, printableString); break; case ExceptionResource.InvalidCharacterAfterEscapeWithinString: result = System.SR.Format(System.SR.InvalidCharacterAfterEscapeWithinString, printableString); break; case ExceptionResource.InvalidHexCharacterWithinString: result = System.SR.Format(System.SR.InvalidHexCharacterWithinString, printableString); break; case ExceptionResource.EndOfCommentNotFound: result = System.SR.EndOfCommentNotFound; break; case ExceptionResource.ZeroDepthAtEnd: result = System.SR.Format(System.SR.ZeroDepthAtEnd); break; case ExceptionResource.ExpectedJsonTokens: result = System.SR.ExpectedJsonTokens; break; case ExceptionResource.NotEnoughData: result = System.SR.NotEnoughData; break; case ExceptionResource.ExpectedOneCompleteToken: result = System.SR.ExpectedOneCompleteToken; break; case ExceptionResource.InvalidCharacterAtStartOfComment: result = System.SR.Format(System.SR.InvalidCharacterAtStartOfComment, printableString); break; case ExceptionResource.UnexpectedEndOfDataWhileReadingComment: result = System.SR.Format(System.SR.UnexpectedEndOfDataWhileReadingComment); break; case ExceptionResource.UnexpectedEndOfLineSeparator: result = System.SR.Format(System.SR.UnexpectedEndOfLineSeparator); break; case ExceptionResource.InvalidLeadingZeroInNumber: result = System.SR.Format(System.SR.InvalidLeadingZeroInNumber, printableString); break; } return result; } [DoesNotReturn] public static void ThrowInvalidOperationException(ExceptionResource resource, int currentDepth, int maxDepth, byte token, JsonTokenType tokenType) { throw GetInvalidOperationException(resource, currentDepth, maxDepth, token, tokenType); } [DoesNotReturn] public static void ThrowArgumentException_InvalidCommentValue() { throw new ArgumentException(System.SR.CannotWriteCommentWithEmbeddedDelimiter); } [DoesNotReturn] public static void ThrowArgumentException_InvalidUTF8(ReadOnlySpan<byte> value) { StringBuilder stringBuilder = new StringBuilder(); int num = Math.Min(value.Length, 10); for (int i = 0; i < num; i++) { byte b = value[i]; if (IsPrintable(b)) { stringBuilder.Append((char)b); } else { stringBuilder.Append($"0x{b:X2}"); } } if (num < value.Length) { stringBuilder.Append("..."); } throw new ArgumentException(System.SR.Format(System.SR.CannotEncodeInvalidUTF8, stringBuilder)); } [DoesNotReturn] public static void ThrowArgumentException_InvalidUTF16(int charAsInt) { throw new ArgumentException(System.SR.Format(System.SR.CannotEncodeInvalidUTF16, $"0x{charAsInt:X2}")); } [DoesNotReturn] public static void ThrowInvalidOperationException_ReadInvalidUTF16(int charAsInt) { throw GetInvalidOperationException(System.SR.Format(System.SR.CannotReadInvalidUTF16, $"0x{charAsInt:X2}")); } [DoesNotReturn] public static void ThrowInvalidOperationException_ReadIncompleteUTF16() { throw GetInvalidOperationException(System.SR.CannotReadIncompleteUTF16); } public static InvalidOperationException GetInvalidOperationException_ReadInvalidUTF8(DecoderFallbackException innerException = null) { return GetInvalidOperationException(System.SR.CannotTranscodeInvalidUtf8, innerException); } public static ArgumentException GetArgumentException_ReadInvalidUTF16(EncoderFallbackException innerException) { return new ArgumentException(System.SR.CannotTranscodeInvalidUtf16, innerException); } public static InvalidOperationException GetInvalidOperationException(string message, Exception innerException) { InvalidOperationException ex = new InvalidOperationException(message, innerException); ex.Source = "System.Text.Json.Rethrowable"; return ex; } [MethodImpl(MethodImplOptions.NoInlining)] public static InvalidOperationException GetInvalidOperationException(ExceptionResource resource, int currentDepth, int maxDepth, byte token, JsonTokenType tokenType) { string resourceString = GetResourceString(resource, currentDepth, maxDepth, token, tokenType); InvalidOperationException invalidOperationException = GetInvalidOperationException(resourceString); invalidOperationException.Source = "System.Text.Json.Rethrowable"; return invalidOperationException; } [DoesNotReturn] public static void ThrowOutOfMemoryException(uint capacity) { throw new OutOfMemoryException(System.SR.Format(System.SR.BufferMaximumSizeExceeded, capacity)); } [MethodImpl(MethodImplOptions.NoInlining)] private static string GetResourceString(ExceptionResource resource, int currentDepth, int maxDepth, byte token, JsonTokenType tokenType) { string result = ""; switch (resource) { case ExceptionResource.MismatchedObjectArray: result = ((tokenType == JsonTokenType.PropertyName) ? System.SR.Format(System.SR.CannotWriteEndAfterProperty, (char)token) : System.SR.Format(System.SR.MismatchedObjectArray, (char)token)); break; case ExceptionResource.DepthTooLarge: result = System.SR.Format(System.SR.DepthTooLarge, currentDepth & 0x7FFFFFFF, maxDepth); break; case ExceptionResource.CannotStartObjectArrayWithoutProperty: result = System.SR.Format(System.SR.CannotStartObjectArrayWithoutProperty, tokenType); break; case ExceptionResource.CannotStartObjectArrayAfterPrimitiveOrClose: result = System.SR.Format(System.SR.CannotStartObjectArrayAfterPrimitiveOrClose, tokenType); break; case ExceptionResource.CannotWriteValueWithinObject: result = System.SR.Format(System.SR.CannotWriteValueWithinObject, tokenType); break; case ExceptionResource.CannotWritePropertyWithinArray: result = ((tokenType == JsonTokenType.PropertyName) ? System.SR.Format(System.SR.CannotWritePropertyAfterProperty) : System.SR.Format(System.SR.CannotWritePropertyWithinArray, tokenType)); break; case ExceptionResource.CannotWriteValueAfterPrimitiveOrClose: result = System.SR.Format(System.SR.CannotWriteValueAfterPrimitiveOrClose, tokenType); break; } return result; } [DoesNotReturn] public static void ThrowFormatException() { throw new FormatException { Source = "System.Text.Json.Rethrowable" }; } public static void ThrowFormatException(NumericType numericType) { string message = ""; switch (numericType) { case NumericType.Byte: message = System.SR.FormatByte; break; case NumericType.SByte: message = System.SR.FormatSByte; break; case NumericType.Int16: message = System.SR.FormatInt16; break; case NumericType.Int32: message = System.SR.FormatInt32; break; case NumericType.Int64: message = System.SR.FormatInt64; break; case NumericType.Int128: message = System.SR.FormatInt128; break; case NumericType.UInt16: message = System.SR.FormatUInt16; break; case NumericType.UInt32: message = System.SR.FormatUInt32; break; case NumericType.UInt64: message = System.SR.FormatUInt64; break; case NumericType.UInt128: message = System.SR.FormatUInt128; break; case NumericType.Half: message = System.SR.FormatHalf; break; case NumericType.Single: message = System.SR.FormatSingle; break; case NumericType.Double: message = System.SR.FormatDouble; break; case NumericType.Decimal: message = System.SR.FormatDecimal; break; } throw new FormatException(message) { Source = "System.Text.Json.Rethrowable" }; } [DoesNotReturn] public static void ThrowFormatException(DataType dataType) { string message = ""; switch (dataType) { case DataType.Boolean: case DataType.DateOnly: case DataType.DateTime: case DataType.DateTimeOffset: case DataType.TimeOnly: case DataType.TimeSpan: case DataType.Guid: case DataType.Version: message = System.SR.Format(System.SR.UnsupportedFormat, dataType); break; case DataType.Base64String: message = System.SR.CannotDecodeInvalidBase64; break; } throw new FormatException(message) { Source = "System.Text.Json.Rethrowable" }; } [DoesNotReturn] public static void ThrowInvalidOperationException_ExpectedChar(JsonTokenType tokenType) { throw GetInvalidOperationException("char", tokenType); } [DoesNotReturn] public static void ThrowObjectDisposedException_Utf8JsonWriter() { throw new ObjectDisposedException("Utf8JsonWriter"); } [DoesNotReturn] public static void ThrowObjectDisposedException_JsonDocument() { throw new ObjectDisposedException("JsonDocument"); } [DoesNotReturn] public static void ThrowArgumentException_NodeValueNotAllowed(string paramName) { throw new ArgumentException(System.SR.NodeValueNotAllowed, paramName); } [DoesNotReturn] public static void ThrowArgumentException_DuplicateKey(string paramName, string propertyName) { throw new ArgumentException(System.SR.Format(System.SR.NodeDuplicateKey, propertyName), paramName); } [DoesNotReturn] public static void ThrowInvalidOperationException_NodeAlreadyHasParent() { throw new InvalidOperationException(System.SR.NodeAlreadyHasParent); } [DoesNotReturn] public static void ThrowInvalidOperationException_NodeCycleDetected() { throw new InvalidOperationException(System.SR.NodeCycleDetected); } [DoesNotReturn] public static void ThrowInvalidOperationException_NodeElementCannotBeObjectOrArray() { throw new InvalidOperationException(System.SR.NodeElementCannotBeObjectOrArray); } [DoesNotReturn] public static void ThrowNotSupportedException_CollectionIsReadOnly() { throw GetNotSupportedException_CollectionIsReadOnly(); } [DoesNotReturn] public static void ThrowInvalidOperationException_NodeWrongType(string typeName) { throw new InvalidOperationException(System.SR.Format(System.SR.NodeWrongType, typeName)); } [DoesNotReturn] public static void ThrowInvalidOperationException_NodeParentWrongType(string typeName) { throw new InvalidOperationException(System.SR.Format(System.SR.NodeParentWrongType, typeName)); } public static NotSupportedException GetNotSupportedException_CollectionIsReadOnly() { return new NotSupportedException(System.SR.CollectionIsReadOnly); } [DoesNotReturn] public static void ThrowArgumentException_DeserializeWrongType(Type type, object value) { throw new ArgumentException(System.SR.Format(System.SR.DeserializeWrongType, type, value.GetType())); } [DoesNotReturn] public static void ThrowArgumentException_SerializerDoesNotSupportComments(string paramName) { throw new ArgumentException(System.SR.JsonSerializerDoesNotSupportComments, paramName); } [DoesNotReturn] public static void ThrowNotSupportedException_SerializationNotSupported(Type propertyType) { throw new NotSupportedException(System.SR.Format(System.SR.SerializationNotSupportedType, propertyType)); } [DoesNotReturn] public static void ThrowNotSupportedException_TypeRequiresAsyncSerialization(Type propertyType) { throw new NotSupportedException(System.SR.Format(System.SR.TypeRequiresAsyncSerialization, propertyType)); } [DoesNotReturn] public static void ThrowNotSupportedException_DictionaryKeyTypeNotSupported(Type keyType, JsonConverter converter) { throw new NotSupportedException(System.SR.Format(System.SR.DictionaryKeyTypeNotSupported, keyType, converter.GetType())); } [DoesNotReturn] public static void ThrowJsonException_DeserializeUnableToConvertValue(Type propertyType) { throw new JsonException(System.SR.Format(System.SR.DeserializeUnableToConvertValue, propertyType)) { AppendPathInformation = true }; } [DoesNotReturn] public static void ThrowInvalidCastException_DeserializeUnableToAssignValue(Type typeOfValue, Type declaredType) { throw new InvalidCastException(System.SR.Format(System.SR.DeserializeUnableToAssignValue, typeOfValue, declaredType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_DeserializeUnableToAssignNull(Type declaredType) { throw new InvalidOperationException(System.SR.Format(System.SR.DeserializeUnableToAssignNull, declaredType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_ObjectCreationHandlingPopulateNotSupportedByConverter(JsonPropertyInfo propertyInfo) { throw new InvalidOperationException(System.SR.Format(System.SR.ObjectCreationHandlingPopulateNotSupportedByConverter, propertyInfo.Name, propertyInfo.DeclaringType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_ObjectCreationHandlingPropertyMustHaveAGetter(JsonPropertyInfo propertyInfo) { throw new InvalidOperationException(System.SR.Format(System.SR.ObjectCreationHandlingPropertyMustHaveAGetter, propertyInfo.Name, propertyInfo.DeclaringType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_ObjectCreationHandlingPropertyValueTypeMustHaveASetter(JsonPropertyInfo propertyInfo) { throw new InvalidOperationException(System.SR.Format(System.SR.ObjectCreationHandlingPropertyValueTypeMustHaveASetter, propertyInfo.Name, propertyInfo.DeclaringType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_ObjectCreationHandlingPropertyCannotAllowPolymorphicDeserialization(JsonPropertyInfo propertyInfo) { throw new InvalidOperationException(System.SR.Format(System.SR.ObjectCreationHandlingPropertyCannotAllowPolymorphicDeserialization, propertyInfo.Name, propertyInfo.DeclaringType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_ObjectCreationHandlingPropertyCannotAllowReadOnlyMember(JsonPropertyInfo propertyInfo) { throw new InvalidOperationException(System.SR.Format(System.SR.ObjectCreationHandlingPropertyCannotAllowReadOnlyMember, propertyInfo.Name, propertyInfo.DeclaringType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_ObjectCreationHandlingPropertyCannotAllowReferenceHandling() { throw new InvalidOperationException(System.SR.ObjectCreationHandlingPropertyCannotAllowReferenceHandling); } [DoesNotReturn] public static void ThrowNotSupportedException_ObjectCreationHandlingPropertyDoesNotSupportParameterizedConstructors() { throw new NotSupportedException(System.SR.ObjectCreationHandlingPropertyDoesNotSupportParameterizedConstructors); } [DoesNotReturn] public static void ThrowJsonException_SerializationConverterRead(JsonConverter converter) { throw new JsonException(System.SR.Format(System.SR.SerializationConverterRead, converter)) { AppendPathInformation = true }; } [DoesNotReturn] public static void ThrowJsonException_SerializationConverterWrite(JsonConverter converter) { throw new JsonException(System.SR.Format(System.SR.SerializationConverterWrite, converter)) { AppendPathInformation = true }; } [DoesNotReturn] public static void ThrowJsonException_SerializerCycleDetected(int maxDepth) { throw new JsonException(System.SR.Format(System.SR.SerializerCycleDetected, maxDepth)) { AppendPathInformation = true }; } [DoesNotReturn] public static void ThrowJsonException(string message = null) { throw new JsonException(message) { AppendPathInformation = true }; } [DoesNotReturn] public static void ThrowArgumentException_CannotSerializeInvalidType(string paramName, Type typeToConvert, Type declaringType, string propertyName) { if (declaringType == null) { throw new ArgumentException(System.SR.Format(System.SR.CannotSerializeInvalidType, typeToConvert), paramName); } throw new ArgumentException(System.SR.Format(System.SR.CannotSerializeInvalidMember, typeToConvert, propertyName, declaringType), paramName); } [DoesNotReturn] public static void ThrowInvalidOperationException_CannotSerializeInvalidType(Type typeToConvert, Type declaringType, MemberInfo memberInfo) { if (declaringType == null) { throw new InvalidOperationException(System.SR.Format(System.SR.CannotSerializeInvalidType, typeToConvert)); } throw new InvalidOperationException(System.SR.Format(System.SR.CannotSerializeInvalidMember, typeToConvert, memberInfo.Name, declaringType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationConverterNotCompatible(Type converterType, Type type) { throw new InvalidOperationException(System.SR.Format(System.SR.SerializationConverterNotCompatible, converterType, type)); } [DoesNotReturn] public static void ThrowInvalidOperationException_ResolverTypeNotCompatible(Type requestedType, Type actualType) { throw new InvalidOperationException(System.SR.Format(System.SR.ResolverTypeNotCompatible, actualType, requestedType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_ResolverTypeInfoOptionsNotCompatible() { throw new InvalidOperationException(System.SR.ResolverTypeInfoOptionsNotCompatible); } [DoesNotReturn] public static void ThrowInvalidOperationException_JsonSerializerOptionsNoTypeInfoResolverSpecified() { throw new InvalidOperationException(System.SR.JsonSerializerOptionsNoTypeInfoResolverSpecified); } [DoesNotReturn] public static void ThrowInvalidOperationException_JsonSerializerIsReflectionDisabled() { throw new InvalidOperationException(System.SR.JsonSerializerIsReflectionDisabled); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationConverterOnAttributeInvalid(Type classType, MemberInfo memberInfo) { string text = classType.ToString(); if (memberInfo != null) { text = text + "." + memberInfo.Name; } throw new InvalidOperationException(System.SR.Format(System.SR.SerializationConverterOnAttributeInvalid, text)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationConverterOnAttributeNotCompatible(Type classTypeAttributeIsOn, MemberInfo memberInfo, Type typeToConvert) { string text = classTypeAttributeIsOn.ToString(); if (memberInfo != null) { text = text + "." + memberInfo.Name; } throw new InvalidOperationException(System.SR.Format(System.SR.SerializationConverterOnAttributeNotCompatible, text, typeToConvert)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializerOptionsReadOnly(JsonSerializerContext context) { string message = ((context == null) ? System.SR.SerializerOptionsReadOnly : System.SR.SerializerContextOptionsReadOnly); throw new InvalidOperationException(message); } [DoesNotReturn] public static void ThrowInvalidOperationException_DefaultTypeInfoResolverImmutable() { throw new InvalidOperationException(System.SR.DefaultTypeInfoResolverImmutable); } [DoesNotReturn] public static void ThrowInvalidOperationException_TypeInfoResolverChainImmutable() { throw new InvalidOperationException(System.SR.TypeInfoResolverChainImmutable); } [DoesNotReturn] public static void ThrowInvalidOperationException_TypeInfoImmutable() { throw new InvalidOperationException(System.SR.TypeInfoImmutable); } [DoesNotReturn] public static void ThrowInvalidOperationException_InvalidChainedResolver() { throw new InvalidOperationException(System.SR.SerializerOptions_InvalidChainedResolver); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializerPropertyNameConflict(Type type, string propertyName) { throw new InvalidOperationException(System.SR.Format(System.SR.SerializerPropertyNameConflict, type, propertyName)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializerPropertyNameNull(JsonPropertyInfo jsonPropertyInfo) { throw new InvalidOperationException(System.SR.Format(System.SR.SerializerPropertyNameNull, jsonPropertyInfo.DeclaringType, jsonPropertyInfo.MemberName)); } [DoesNotReturn] public static void ThrowInvalidOperationException_JsonPropertyRequiredAndNotDeserializable(JsonPropertyInfo jsonPropertyInfo) { throw new InvalidOperationException(System.SR.Format(System.SR.JsonPropertyRequiredAndNotDeserializable, jsonPropertyInfo.Name, jsonPropertyInfo.DeclaringType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_JsonPropertyRequiredAndExtensionData(JsonPropertyInfo jsonPropertyInfo) { throw new InvalidOperationException(System.SR.Format(System.SR.JsonPropertyRequiredAndExtensionData, jsonPropertyInfo.Name, jsonPropertyInfo.DeclaringType)); } [DoesNotReturn] public static void ThrowJsonException_JsonRequiredPropertyMissing(JsonTypeInfo parent, BitArray requiredPropertiesSet) { StringBuilder stringBuilder = new StringBuilder(); bool flag = true; foreach (KeyValuePair<string, JsonPropertyInfo> item in parent.PropertyCache.List) { JsonPropertyInfo value = item.Value; if (value.IsRequired && !requiredPropertiesSet[value.RequiredPropertyIndex]) { if (!flag) { stringBuilder.Append(CultureInfo.CurrentUICulture.TextInfo.ListSeparator); stringBuilder.Append(' '); } stringBuilder.Append(value.Name); flag = false; if (stringBuilder.Length >= 50) { break; } } } throw new JsonException(System.SR.Format(System.SR.JsonRequiredPropertiesMissing, parent.Type, stringBuilder.ToString())); } [DoesNotReturn] public static void ThrowInvalidOperationException_NamingPolicyReturnNull(JsonNamingPolicy namingPolicy) { throw new InvalidOperationException(System.SR.Format(System.SR.NamingPolicyReturnNull, namingPolicy)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializerConverterFactoryReturnsNull(Type converterType) { throw new InvalidOperationException(System.SR.Format(System.SR
YoutubeExplode.Converter.dll
Decompiled 2 years agousing System; 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.Management; using System.Net.Http; 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 CliWrap; using CliWrap.Builders; using CliWrap.Exceptions; using Microsoft.CodeAnalysis; using YoutubeExplode.Converter.Utils; using YoutubeExplode.Converter.Utils.Extensions; using YoutubeExplode.Videos; using YoutubeExplode.Videos.ClosedCaptions; using YoutubeExplode.Videos.Streams; [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("Tyrrrz")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright (C) Oleksii Holub")] [assembly: AssemblyDescription("Extension for YoutubeExplode that provides an interface to download and convert videos using FFmpeg")] [assembly: AssemblyFileVersion("6.3.9.0")] [assembly: AssemblyInformationalVersion("6.3.9+41b4c289ceb64cc930aedcdb039d01bdf830b435")] [assembly: AssemblyProduct("YoutubeExplode.Converter")] [assembly: AssemblyTitle("YoutubeExplode.Converter")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/Tyrrrz/YoutubeExplode")] [assembly: AssemblyVersion("6.3.9.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } internal static class PolyfillExtensions { public static async Task<Stream> GetStreamAsync(this HttpClient httpClient, string requestUri, CancellationToken cancellationToken = default(CancellationToken)) { _ = 1; try { HttpResponseMessage obj = await httpClient.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); obj.EnsureSuccessStatusCode(); return await ReadAsStreamAsync(obj.Content, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } catch (OperationCanceledException ex) when (ex.CancellationToken != cancellationToken && cancellationToken.IsCancellationRequested) { throw new OperationCanceledException(ex.Message, ex.InnerException, cancellationToken); } } public static async Task<Stream> GetStreamAsync(this HttpClient httpClient, Uri requestUri, CancellationToken cancellationToken = default(CancellationToken)) { return await GetStreamAsync(httpClient, requestUri.ToString(), cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static async Task<byte[]> GetByteArrayAsync(this HttpClient httpClient, string requestUri, CancellationToken cancellationToken = default(CancellationToken)) { _ = 1; try { using HttpResponseMessage response = await httpClient.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); response.EnsureSuccessStatusCode(); return await ReadAsByteArrayAsync(response.Content, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } catch (OperationCanceledException ex) when (ex.CancellationToken != cancellationToken && cancellationToken.IsCancellationRequested) { throw new OperationCanceledException(ex.Message, ex.InnerException, cancellationToken); } } public static async Task<byte[]> GetByteArrayAsync(this HttpClient httpClient, Uri requestUri, CancellationToken cancellationToken = default(CancellationToken)) { return await GetByteArrayAsync(httpClient, requestUri.ToString(), cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static async Task<string> GetStringAsync(this HttpClient httpClient, string requestUri, CancellationToken cancellationToken = default(CancellationToken)) { _ = 1; try { using HttpResponseMessage response = await httpClient.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); response.EnsureSuccessStatusCode(); return await ReadAsStringAsync(response.Content, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } catch (OperationCanceledException ex) when (ex.CancellationToken != cancellationToken && cancellationToken.IsCancellationRequested) { throw new OperationCanceledException(ex.Message, ex.InnerException, cancellationToken); } } public static async Task<string> GetStringAsync(this HttpClient httpClient, Uri requestUri, CancellationToken cancellationToken = default(CancellationToken)) { return await GetStringAsync(httpClient, requestUri.ToString(), cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static async Task<Stream> ReadAsStreamAsync(this HttpContent httpContent, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); return await httpContent.ReadAsStreamAsync().ConfigureAwait(continueOnCapturedContext: false); } public static async Task<byte[]> ReadAsByteArrayAsync(this HttpContent httpContent, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); return await httpContent.ReadAsByteArrayAsync().ConfigureAwait(continueOnCapturedContext: false); } public static async Task<string> ReadAsStringAsync(this HttpContent httpContent, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); return await httpContent.ReadAsStringAsync().ConfigureAwait(continueOnCapturedContext: false); } public static async Task WaitForExitAsync(this Process process, CancellationToken cancellationToken = default(CancellationToken)) { TaskCompletionSource<object?> tcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously); try { process.EnableRaisingEvents = true; } catch when (process.HasExited) { return; } process.Exited += HandleExited; try { using (cancellationToken.Register(delegate { tcs.TrySetCanceled(cancellationToken); })) { await tcs.Task; } } finally { process.Exited -= HandleExited; } void HandleExited(object? sender, EventArgs args) { tcs.TrySetResult(null); } } public static bool IsAssignableTo(this Type type, Type? otherType) { return otherType?.IsAssignableFrom(type) ?? false; } public static async Task WaitAsync(this Task task, TimeSpan timeout, CancellationToken cancellationToken) { Task cancellationTask = Task.Delay(timeout, cancellationToken); Task finishedTask = await Task.WhenAny(new Task[2] { task, cancellationTask }).ConfigureAwait(continueOnCapturedContext: false); await finishedTask.ConfigureAwait(continueOnCapturedContext: false); if (finishedTask == cancellationTask) { throw new TimeoutException("The operation has timed out."); } } public static async Task WaitAsync(this Task task, CancellationToken cancellationToken) { await WaitAsync(task, Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static async Task WaitAsync(this Task task, TimeSpan timeout) { await WaitAsync(task, timeout, CancellationToken.None).ConfigureAwait(continueOnCapturedContext: false); } public static async Task<T> WaitAsync<T>(this Task<T> task, TimeSpan timeout, CancellationToken cancellationToken) { Task cancellationTask = Task.Delay(timeout, cancellationToken); Task finishedTask = await Task.WhenAny(new Task[2] { task, cancellationTask }).ConfigureAwait(continueOnCapturedContext: false); await finishedTask.ConfigureAwait(continueOnCapturedContext: false); if (finishedTask == cancellationTask) { throw new TimeoutException("The operation has timed out."); } return task.Result; } public static async Task<T> WaitAsync<T>(this Task<T> task, CancellationToken cancellationToken) { return await WaitAsync(task, Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static async Task<T> WaitAsync<T>(this Task<T> task, TimeSpan timeout) { return await WaitAsync(task, timeout, CancellationToken.None).ConfigureAwait(continueOnCapturedContext: false); } public static int ReadAtLeast(this Stream stream, byte[] buffer, int minimumBytes, bool throwOnEndOfStream = true) { int i; int num; for (i = 0; i < buffer.Length; i += num) { num = stream.Read(buffer, i, Math.Min(minimumBytes, buffer.Length - i)); if (num <= 0) { break; } } if (i < minimumBytes && throwOnEndOfStream) { throw new EndOfStreamException(); } return i; } public static void ReadExactly(this Stream stream, byte[] buffer, int offset, int count) { int num; for (int i = 0; i < count; i += num) { num = stream.Read(buffer, offset + i, count - i); if (num <= 0) { throw new EndOfStreamException(); } } } public static void ReadExactly(this Stream stream, byte[] buffer) { stream.ReadExactly(buffer, 0, buffer.Length); } public static async Task<int> ReadAtLeastAsync(this Stream stream, byte[] buffer, int minimumBytes, bool throwOnEndOfStream = true, CancellationToken cancellationToken = default(CancellationToken)) { int totalBytesRead; int num; for (totalBytesRead = 0; totalBytesRead < buffer.Length; totalBytesRead += num) { num = await stream.ReadAsync(buffer, totalBytesRead, Math.Min(minimumBytes, buffer.Length - totalBytesRead), cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (num <= 0) { break; } } if (totalBytesRead < minimumBytes && throwOnEndOfStream) { throw new EndOfStreamException(); } return totalBytesRead; } public static async Task ReadExactlyAsync(this Stream stream, byte[] buffer, int offset, int count, CancellationToken cancellationToken = default(CancellationToken)) { int num; for (int totalBytesRead = 0; totalBytesRead < count; totalBytesRead += num) { num = await stream.ReadAsync(buffer, offset + totalBytesRead, count - totalBytesRead, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (num <= 0) { throw new EndOfStreamException(); } } } public static async Task ReadExactlyAsync(this Stream stream, byte[] buffer, CancellationToken cancellationToken = default(CancellationToken)) { await stream.ReadExactlyAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static int ReadAtLeast(this Stream stream, Span<byte> buffer, int minimumBytes, bool throwOnEndOfStream = true) { int i; int num; for (i = 0; i < buffer.Length; i += num) { num = stream.Read(buffer.Slice(i)); if (num <= 0) { break; } } if (i < minimumBytes && throwOnEndOfStream) { throw new EndOfStreamException(); } return i; } public static void ReadExactly(this Stream stream, Span<byte> buffer) { byte[] array = buffer.ToArray(); stream.ReadExactly(array, 0, array.Length); array.CopyTo(buffer); } public static async Task<int> ReadAtLeastAsync(this Stream stream, Memory<byte> buffer, int minimumBytes, bool throwOnEndOfStream = true, CancellationToken cancellationToken = default(CancellationToken)) { int totalBytesRead; int num; for (totalBytesRead = 0; totalBytesRead < buffer.Length; totalBytesRead += num) { num = await stream.ReadAsync(buffer.Slice(totalBytesRead), cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (num <= 0) { break; } } if (totalBytesRead < minimumBytes && throwOnEndOfStream) { throw new EndOfStreamException(); } return totalBytesRead; } public static async Task ReadExactlyAsync(this Stream stream, Memory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken)) { byte[] bufferArray = buffer.ToArray(); await stream.ReadExactlyAsync(bufferArray, 0, bufferArray.Length, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); bufferArray.CopyTo(buffer); } private static void KillProcessTree(int processId) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown ManagementObjectSearcher val = new ManagementObjectSearcher($"SELECT * FROM Win32_Process WHERE ParentProcessID={processId}"); try { ManagementObjectCollection val2 = val.Get(); try { try { using Process process = Process.GetProcessById(processId); if (!process.HasExited) { process.Kill(); } } catch { } foreach (ManagementObject item in ((IEnumerable)val2).Cast<ManagementObject>()) { KillProcessTree(Convert.ToInt32(((ManagementBaseObject)item)["ProcessID"])); } } finally { ((IDisposable)val2)?.Dispose(); } } finally { ((IDisposable)val)?.Dispose(); } } public static void Kill(this Process process, bool entireProcessTree) { if (!entireProcessTree) { process.Kill(); } else if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { process.Kill(); } else { KillProcessTree(process.Id); } } } namespace YoutubeExplode.Converter { public static class ConversionExtensions { [Obsolete("Use the Container.IsAudioOnly property instead.")] [ExcludeFromCodeCoverage] public static bool IsAudioOnly(this Container container) { return ((Container)(ref container)).IsAudioOnly; } private static async IAsyncEnumerable<IStreamInfo> GetOptimalStreamInfosAsync(this VideoClient videoClient, VideoId videoId, Container container, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken)) { //IL_000f: 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_0016: 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) StreamManifest streamManifest = await videoClient.Streams.GetManifestAsync(videoId, cancellationToken); if (!streamManifest.GetAudioOnlyStreams().Any() || !streamManifest.GetVideoOnlyStreams().Any()) { yield return (from s in streamManifest.GetMuxedStreams() orderby s.VideoQuality descending, s.Container == container descending select s).First(); yield break; } yield return (from s in streamManifest.GetAudioOnlyStreams() orderby s.Container == container descending, s.Bitrate descending select s).First(); if (!((Container)(ref container)).IsAudioOnly) { yield return (from s in streamManifest.GetVideoOnlyStreams() orderby s.VideoQuality descending, s.Container == container descending select s).First(); } } public static async ValueTask DownloadAsync(this VideoClient videoClient, IReadOnlyList<IStreamInfo> streamInfos, IReadOnlyList<ClosedCaptionTrackInfo> closedCaptionTrackInfos, ConversionRequest request, IProgress<double>? progress = null, CancellationToken cancellationToken = default(CancellationToken)) { FFmpeg ffmpeg = new FFmpeg(request.FFmpegCliFilePath); await new Converter(videoClient, ffmpeg, request.Preset).ProcessAsync(request.OutputFilePath, request.Container, streamInfos, closedCaptionTrackInfos, progress, cancellationToken); } public static async ValueTask DownloadAsync(this VideoClient videoClient, IReadOnlyList<IStreamInfo> streamInfos, ConversionRequest request, IProgress<double>? progress = null, CancellationToken cancellationToken = default(CancellationToken)) { await videoClient.DownloadAsync(streamInfos, Array.Empty<ClosedCaptionTrackInfo>(), request, progress, cancellationToken); } public static async ValueTask DownloadAsync(this VideoClient videoClient, VideoId videoId, ConversionRequest request, IProgress<double>? progress = null, CancellationToken cancellationToken = default(CancellationToken)) { //IL_0016: 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) await videoClient.DownloadAsync((IReadOnlyList<IStreamInfo>)(await videoClient.GetOptimalStreamInfosAsync(videoId, request.Container, cancellationToken)), request, progress, cancellationToken); } public static async ValueTask DownloadAsync(this VideoClient videoClient, VideoId videoId, string outputFilePath, Action<ConversionRequestBuilder> configure, IProgress<double>? progress = null, CancellationToken cancellationToken = default(CancellationToken)) { //IL_0016: 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) ConversionRequestBuilder conversionRequestBuilder = new ConversionRequestBuilder(outputFilePath); configure(conversionRequestBuilder); ConversionRequest request = conversionRequestBuilder.Build(); await videoClient.DownloadAsync(videoId, request, progress, cancellationToken); } public static async ValueTask DownloadAsync(this VideoClient videoClient, VideoId videoId, string outputFilePath, IProgress<double>? progress = null, CancellationToken cancellationToken = default(CancellationToken)) { //IL_0016: 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) await videoClient.DownloadAsync(videoId, outputFilePath, delegate { }, progress, cancellationToken); } } [Obsolete("Use YoutubeExplode.Videos.Streams.Container instead")] [ExcludeFromCodeCoverage] public readonly struct ConversionFormat { public string Name { get; } public bool IsAudioOnly => ConversionExtensions.IsAudioOnly(new Container(Name)); public ConversionFormat(string name) { Name = name; } public override string ToString() { return Name; } } public enum ConversionPreset { VerySlow = -2, Slow, Medium, Fast, VeryFast, UltraFast } public class ConversionRequest { public string FFmpegCliFilePath { get; } public string OutputFilePath { get; } public Container Container { get; } [Obsolete("Use the Container property instead.")] [ExcludeFromCodeCoverage] public ConversionFormat Format { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) Container container = Container; return new ConversionFormat(((Container)(ref container)).Name); } } public ConversionPreset Preset { get; } public ConversionRequest(string ffmpegCliFilePath, string outputFilePath, Container container, ConversionPreset preset) { //IL_0015: 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) FFmpegCliFilePath = ffmpegCliFilePath; OutputFilePath = outputFilePath; Container = container; Preset = preset; } [Obsolete("Use the other constructor overload")] [ExcludeFromCodeCoverage] public ConversionRequest(string ffmpegCliFilePath, string outputFilePath, ConversionFormat format, ConversionPreset preset) : this(ffmpegCliFilePath, outputFilePath, new Container(format.Name), preset) { }//IL_000a: Unknown result type (might be due to invalid IL or missing references) } public class ConversionRequestBuilder { private readonly string _outputFilePath; private string? _ffmpegCliFilePath; private Container? _container; private ConversionPreset _preset; public ConversionRequestBuilder(string outputFilePath) { _outputFilePath = outputFilePath; } private Container GetDefaultContainer() { //IL_0020: Unknown result type (might be due to invalid IL or missing references) return new Container(Path.GetExtension(_outputFilePath).TrimStart('.').NullIfWhiteSpace() ?? "mp4"); } public ConversionRequestBuilder SetFFmpegPath(string path) { _ffmpegCliFilePath = path; return this; } public ConversionRequestBuilder SetContainer(Container container) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) _container = container; return this; } public ConversionRequestBuilder SetContainer(string container) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return SetContainer(new Container(container)); } [Obsolete("Use SetContainer instead.")] [ExcludeFromCodeCoverage] public ConversionRequestBuilder SetFormat(ConversionFormat format) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) return SetContainer(new Container(format.Name)); } [Obsolete("Use SetContainer instead.")] [ExcludeFromCodeCoverage] public ConversionRequestBuilder SetFormat(string format) { return SetContainer(format); } public ConversionRequestBuilder SetPreset(ConversionPreset preset) { _preset = preset; return this; } public ConversionRequest Build() { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) return new ConversionRequest(_ffmpegCliFilePath ?? FFmpeg.GetFilePath(), _outputFilePath, (Container)(((??)_container) ?? GetDefaultContainer()), _preset); } } internal class Converter { private class StreamInput : IDisposable { public IStreamInfo Info { get; } public string FilePath { get; } public StreamInput(IStreamInfo info, string filePath) { Info = info; FilePath = filePath; } public void Dispose() { try { File.Delete(FilePath); } catch { } } } private class SubtitleInput : IDisposable { public ClosedCaptionTrackInfo Info { get; } public string FilePath { get; } public SubtitleInput(ClosedCaptionTrackInfo info, string filePath) { Info = info; FilePath = filePath; } public void Dispose() { try { File.Delete(FilePath); } catch { } } } private readonly VideoClient _videoClient; private readonly FFmpeg _ffmpeg; private readonly ConversionPreset _preset; public Converter(VideoClient videoClient, FFmpeg ffmpeg, ConversionPreset preset) { _videoClient = videoClient; _ffmpeg = ffmpeg; _preset = preset; } private async ValueTask ProcessAsync(string filePath, Container container, IReadOnlyList<StreamInput> streamInputs, IReadOnlyList<SubtitleInput> subtitleInputs, IProgress<double>? progress = null, CancellationToken cancellationToken = default(CancellationToken)) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) ArgumentsBuilder val = new ArgumentsBuilder(); foreach (StreamInput streamInput in streamInputs) { val.Add("-i").Add(streamInput.FilePath); } foreach (SubtitleInput subtitleInput in subtitleInputs) { val.Add("-i").Add(subtitleInput.FilePath); } for (int i = 0; i < streamInputs.Count + subtitleInputs.Count; i++) { val.Add("-map").Add((IFormattable)i); } val.Add("-f").Add(((Container)(ref container)).Name).Add("-preset") .Add((IFormattable)_preset); int num = 0; int num2 = 0; foreach (StreamInput streamInput2 in streamInputs) { IStreamInfo info = streamInput2.Info; IAudioStreamInfo val2 = (IAudioStreamInfo)(object)((info is IAudioStreamInfo) ? info : null); if (val2 != null) { if (((IStreamInfo)val2).Container == container) { val.Add($"-c:a:{num}").Add("copy"); } num++; } IStreamInfo info2 = streamInput2.Info; IVideoStreamInfo val3 = (IVideoStreamInfo)(object)((info2 is IVideoStreamInfo) ? info2 : null); if (val3 != null) { if (((IStreamInfo)val3).Container == container) { val.Add($"-c:v:{num2}").Add("copy"); } num2++; } } if (container == Container.Mp4 && subtitleInputs.Any()) { val.Add("-c:s").Add("mov_text"); } if (container == Container.Mp3) { int num3 = 0; foreach (StreamInput streamInput3 in streamInputs) { IStreamInfo info3 = streamInput3.Info; IAudioStreamInfo val4 = (IAudioStreamInfo)(object)((info3 is IAudioStreamInfo) ? info3 : null); if (val4 != null) { ArgumentsBuilder obj = val.Add($"-b:a:{num3++}"); Bitrate bitrate = ((IStreamInfo)val4).Bitrate; obj.Add(Math.Round(((Bitrate)(ref bitrate)).KiloBitsPerSecond) + "K"); } } } int num4 = 0; int num5 = 0; foreach (StreamInput streamInput4 in streamInputs) { IStreamInfo info4 = streamInput4.Info; IAudioStreamInfo val5 = (IAudioStreamInfo)(object)((info4 is IAudioStreamInfo) ? info4 : null); if (val5 != null) { val.Add($"-metadata:s:a:{num4++}").Add($"title={((IStreamInfo)val5).Bitrate}"); } IStreamInfo info5 = streamInput4.Info; IVideoStreamInfo val6 = (IVideoStreamInfo)(object)((info5 is IVideoStreamInfo) ? info5 : null); if (val6 != null) { ArgumentsBuilder obj2 = val.Add($"-metadata:s:v:{num5++}"); VideoQuality videoQuality = val6.VideoQuality; obj2.Add($"title={((VideoQuality)(ref videoQuality)).Label} | {((IStreamInfo)val6).Bitrate}"); } } foreach (var item3 in subtitleInputs.WithIndex()) { SubtitleInput item = item3.value; int item2 = item3.index; string text = item.Info.Language.TryGetThreeLetterCode(); Language language; if (text == null) { language = item.Info.Language; text = ((Language)(ref language)).Code; } string text2 = text; ArgumentsBuilder obj3 = val.Add($"-metadata:s:s:{item2}").Add("language=" + text2).Add($"-metadata:s:s:{item2}"); language = item.Info.Language; obj3.Add("title=" + ((Language)(ref language)).Name); } val.Add("-loglevel").Add("info").Add("-stats"); val.Add("-hide_banner").Add("-threads").Add((IFormattable)Environment.ProcessorCount) .Add("-nostdin") .Add("-y"); val.Add(filePath); await _ffmpeg.ExecuteAsync(val.Build(), progress, cancellationToken); } private async ValueTask PopulateStreamInputsAsync(string baseFilePath, IReadOnlyList<IStreamInfo> streamInfos, ICollection<StreamInput> streamInputs, IProgress<double>? progress = null, CancellationToken cancellationToken = default(CancellationToken)) { ProgressMuxer progressMuxer = progress?.Pipe((IProgress<double> p) => new ProgressMuxer(p)); IProgress<double>[] second = streamInfos.Select(delegate(IStreamInfo s) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) ProgressMuxer progressMuxer2 = progressMuxer; if (progressMuxer2 == null) { return null; } FileSize size = s.Size; return progressMuxer2.CreateInput(((FileSize)(ref size)).MegaBytes); }).ToArray(); int lastIndex = 0; foreach (var item3 in System.Linq.PolyfillExtensions.Zip(streamInfos, second)) { IStreamInfo item = item3.left; IProgress<double> item2 = item3.right; StreamInput streamInput = new StreamInput(item, $"{baseFilePath}.stream-{lastIndex++}.tmp"); streamInputs.Add(streamInput); await _videoClient.Streams.DownloadAsync(item, streamInput.FilePath, item2, cancellationToken); } progress?.Report(1.0); } private async ValueTask PopulateSubtitleInputsAsync(string baseFilePath, IReadOnlyList<ClosedCaptionTrackInfo> closedCaptionTrackInfos, ICollection<SubtitleInput> subtitleInputs, IProgress<double>? progress = null, CancellationToken cancellationToken = default(CancellationToken)) { ProgressMuxer progressMuxer = progress?.Pipe((IProgress<double> p) => new ProgressMuxer(p)); IProgress<double>[] second = closedCaptionTrackInfos.Select((ClosedCaptionTrackInfo _) => progressMuxer?.CreateInput()).ToArray(); int lastIndex = 0; foreach (var item3 in System.Linq.PolyfillExtensions.Zip(closedCaptionTrackInfos, second)) { ClosedCaptionTrackInfo item = item3.left; IProgress<double> item2 = item3.right; SubtitleInput subtitleInput = new SubtitleInput(item, $"{baseFilePath}.subtitles-{lastIndex++}.tmp"); subtitleInputs.Add(subtitleInput); await _videoClient.ClosedCaptions.DownloadAsync(item, subtitleInput.FilePath, item2, cancellationToken); } progress?.Report(1.0); } public async ValueTask ProcessAsync(string filePath, Container container, IReadOnlyList<IStreamInfo> streamInfos, IReadOnlyList<ClosedCaptionTrackInfo> closedCaptionTrackInfos, IProgress<double>? progress = null, CancellationToken cancellationToken = default(CancellationToken)) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) if (!streamInfos.Any()) { throw new InvalidOperationException("No streams provided."); } ProgressMuxer progressMuxer = progress?.Pipe((IProgress<double> p) => new ProgressMuxer(p)); IProgress<double> progress2 = progressMuxer?.CreateInput(); IProgress<double> subtitleDownloadProgress = progressMuxer?.CreateInput(0.01); IProgress<double> conversionProgress = progressMuxer?.CreateInput(0.05 + (double)(5 * streamInfos.Count((IStreamInfo s) => s.Container != container))); List<StreamInput> streamInputs = new List<StreamInput>(streamInfos.Count); List<SubtitleInput> subtitleInputs = new List<SubtitleInput>(closedCaptionTrackInfos.Count); try { await PopulateStreamInputsAsync(filePath, streamInfos, streamInputs, progress2, cancellationToken); await PopulateSubtitleInputsAsync(filePath, closedCaptionTrackInfos, subtitleInputs, subtitleDownloadProgress, cancellationToken); await ProcessAsync(filePath, container, streamInputs, subtitleInputs, conversionProgress, cancellationToken); } finally { foreach (StreamInput item in streamInputs) { item.Dispose(); } foreach (SubtitleInput item2 in subtitleInputs) { item2.Dispose(); } } } } internal class FFmpeg { private readonly string _filePath; public FFmpeg(string filePath) { _filePath = filePath; } public async ValueTask ExecuteAsync(string arguments, IProgress<double>? progress, CancellationToken cancellationToken = default(CancellationToken)) { StringBuilder stdErrBuffer = new StringBuilder(); PipeTarget val = PipeTarget.Merge((PipeTarget[])(object)new PipeTarget[2] { PipeTarget.ToStringBuilder(stdErrBuffer), progress?.Pipe(CreateProgressRouter) ?? PipeTarget.Null }); try { await Cli.Wrap(_filePath).WithArguments(arguments).WithStandardErrorPipe(val) .ExecuteAsync(cancellationToken); } catch (CommandExecutionException val2) { CommandExecutionException innerException = val2; throw new InvalidOperationException($"FFmpeg command-line tool failed with an error.\r\n\r\nStandard error:\r\n{stdErrBuffer}", (Exception?)(object)innerException); } } public static string GetFilePath() { return Directory.EnumerateFiles(AppDomain.CurrentDomain.BaseDirectory ?? Directory.GetCurrentDirectory()).FirstOrDefault((string f) => string.Equals(Path.GetFileNameWithoutExtension(f), "ffmpeg", StringComparison.OrdinalIgnoreCase)) ?? "ffmpeg"; } private static PipeTarget CreateProgressRouter(IProgress<double> progress) { IProgress<double> progress2 = progress; TimeSpan? totalDuration = null; return PipeTarget.ToDelegate((Action<string>)delegate(string line) { if (!totalDuration.HasValue) { Match match = Regex.Match(line, "Duration:\\s(\\d+):(\\d+):(\\d+\\.\\d+)"); if (match.Success) { int num = int.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture); int num2 = int.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture); double value = double.Parse(match.Groups[3].Value, CultureInfo.InvariantCulture); totalDuration = TimeSpan.FromHours(num) + TimeSpan.FromMinutes(num2) + TimeSpan.FromSeconds(value); } } if (totalDuration.HasValue && !(totalDuration == TimeSpan.Zero)) { Match match2 = Regex.Match(line, "time=(\\d+):(\\d+):(\\d+\\.\\d+)"); if (match2.Success) { int num3 = int.Parse(match2.Groups[1].Value, CultureInfo.InvariantCulture); int num4 = int.Parse(match2.Groups[2].Value, CultureInfo.InvariantCulture); double value2 = double.Parse(match2.Groups[3].Value, CultureInfo.InvariantCulture); TimeSpan timeSpan = TimeSpan.FromHours(num3) + TimeSpan.FromMinutes(num4) + TimeSpan.FromSeconds(value2); progress2.Report((timeSpan.TotalMilliseconds / totalDuration.Value.TotalMilliseconds).Clamp(0.0, 1.0)); } } }); } } } namespace YoutubeExplode.Converter.Utils { internal class ProgressMuxer { private readonly IProgress<double> _target; private readonly object _lock = new object(); private readonly Dictionary<int, double> _splitWeights = new Dictionary<int, double>(); private readonly Dictionary<int, double> _splitValues = new Dictionary<int, double>(); public ProgressMuxer(IProgress<double> target) { _target = target; } public IProgress<double> CreateInput(double weight = 1.0) { lock (_lock) { int index = _splitWeights.Count; _splitWeights[index] = weight; _splitValues[index] = 0.0; return new Progress<double>(delegate(double p) { lock (_lock) { _splitValues[index] = p; double num = 0.0; double num2 = 0.0; for (int i = 0; i < _splitWeights.Count; i++) { num += _splitWeights[i] * _splitValues[i]; num2 += _splitWeights[i]; } _target.Report(num / num2); } }); } } } } namespace YoutubeExplode.Converter.Utils.Extensions { internal static class AsyncCollectionExtensions { public static async ValueTask<List<T>> ToListAsync<T>(this IAsyncEnumerable<T> source) { List<T> list = new List<T>(); await foreach (T item in source) { list.Add(item); } return list; } public static ValueTaskAwaiter<List<T>> GetAwaiter<T>(this IAsyncEnumerable<T> source) { return source.ToListAsync().GetAwaiter(); } } internal static class CollectionExtensions { public static IEnumerable<(T value, int index)> WithIndex<T>(this IEnumerable<T> source) { int i = 0; foreach (T item in source) { yield return (item, i++); } } } internal static class GenericExtensions { public static TOut Pipe<TIn, TOut>(this TIn input, Func<TIn, TOut> transform) { return transform(input); } public static T Clamp<T>(this T value, T min, T max) where T : IComparable<T> { if (value.CompareTo(min) > 0) { if (value.CompareTo(max) < 0) { return value; } return max; } return min; } } internal static class LanguageExtensions { public static string? TryGetThreeLetterCode(this Language language) { string text = ((Language)(ref language)).Code.SubstringUntil("-", StringComparison.OrdinalIgnoreCase); if (text.Length == 3) { return text; } return text.ToLowerInvariant() switch { "aa" => "aar", "ab" => "abk", "ae" => "ave", "af" => "afr", "ak" => "aka", "am" => "amh", "an" => "arg", "ar" => "ara", "as" => "asm", "av" => "ava", "ay" => "aym", "az" => "aze", "ba" => "bak", "be" => "bel", "bg" => "bul", "bh" => "bih", "bi" => "bis", "bm" => "bam", "bn" => "ben", "bo" => "bod", "br" => "bre", "bs" => "bos", "ca" => "cat", "ce" => "che", "ch" => "cha", "co" => "cos", "cr" => "cre", "cs" => "cze", "cu" => "chu", "cv" => "chv", "cy" => "cym", "da" => "dan", "de" => "deu", "dv" => "div", "dz" => "dzo", "ee" => "ewe", "el" => "ell", "en" => "eng", "eo" => "epo", "es" => "spa", "et" => "est", "eu" => "eus", "fa" => "fas", "ff" => "ful", "fi" => "fin", "fj" => "fij", "fo" => "fao", "fr" => "fra", "fy" => "fry", "ga" => "gle", "gd" => "gla", "gl" => "glg", "gn" => "grn", "gu" => "guj", "gv" => "glv", "ha" => "hau", "he" => "heb", "hi" => "hin", "ho" => "hmo", "hr" => "hrv", "ht" => "hat", "hu" => "hun", "hy" => "hye", "hz" => "her", "ia" => "ina", "id" => "ind", "ie" => "ile", "ig" => "ibo", "ii" => "iii", "ik" => "ipk", "in" => "ind", "io" => "ido", "is" => "isl", "it" => "ita", "iu" => "iku", "iw" => "heb", "ja" => "jpn", "ji" => "yid", "jv" => "jav", "jw" => "jav", "ka" => "kat", "kg" => "kon", "ki" => "kik", "kj" => "kua", "kk" => "kaz", "kl" => "kal", "km" => "khm", "kn" => "kan", "ko" => "kor", "kr" => "kau", "ks" => "kas", "ku" => "kur", "kv" => "kom", "kw" => "cor", "ky" => "kir", "la" => "lat", "lb" => "ltz", "lg" => "lug", "li" => "lim", "ln" => "lin", "lo" => "lao", "lt" => "lit", "lu" => "lub", "lv" => "lav", "mg" => "mlg", "mh" => "mah", "mi" => "mri", "mk" => "mkd", "ml" => "mal", "mn" => "mon", "mo" => "ron", "mr" => "mar", "ms" => "msa", "mt" => "mlt", "my" => "mya", "na" => "nau", "nb" => "nob", "nd" => "nde", "ne" => "nep", "ng" => "ndo", "nl" => "nld", "nn" => "nno", "no" => "nor", "nr" => "nbl", "nv" => "nav", "ny" => "nya", "oc" => "oci", "oj" => "oji", "om" => "orm", "or" => "ori", "os" => "oss", "pa" => "pan", "pi" => "pli", "pl" => "pol", "ps" => "pus", "pt" => "por", "qu" => "que", "rm" => "roh", "rn" => "run", "ro" => "ron", "ru" => "rus", "rw" => "kin", "sa" => "san", "sc" => "srd", "sd" => "snd", "se" => "sme", "sg" => "sag", "sh" => "hbs", "si" => "sin", "sk" => "slo", "sl" => "slv", "sm" => "smo", "sn" => "sna", "so" => "som", "sq" => "sqi", "sr" => "srp", "ss" => "ssw", "st" => "sot", "su" => "sun", "sv" => "swe", "sw" => "swa", "ta" => "tam", "te" => "tel", "tg" => "tgk", "th" => "tha", "ti" => "tir", "tk" => "tuk", "tl" => "tgl", "tn" => "tsn", "to" => "ton", "tr" => "tur", "ts" => "tso", "tt" => "tat", "tw" => "twi", "ty" => "tah", "ug" => "uig", "uk" => "ukr", "ur" => "urd", "uz" => "uzb", "ve" => "ven", "vi" => "vie", "vo" => "vol", "wa" => "wln", "wo" => "wol", "xh" => "xho", "yi" => "yid", "yo" => "yor", "za" => "zha", "zh" => "zho", "zu" => "zul", _ => null, }; } } internal static class StringExtensions { public static string? NullIfWhiteSpace(this string s) { if (string.IsNullOrWhiteSpace(s)) { return null; } return s; } public static string SubstringUntil(this string str, string sub, StringComparison comparison = StringComparison.Ordinal) { int num = str.IndexOf(sub, comparison); if (num >= 0) { return str.Substring(0, num); } return str; } } } namespace System.Linq { internal static class PolyfillExtensions { public static T ElementAt<T>(this IEnumerable<T> source, Index index) { if (index.IsFromEnd) { ICollection<T> collection = (source as ICollection<T>) ?? source.ToArray(); return collection.ElementAt(collection.Count - index.Value); } return source.ElementAt(index.Value); } public static T? ElementAtOrDefault<T>(this IEnumerable<T> source, Index index) { if (index.IsFromEnd) { ICollection<T> collection = (source as ICollection<T>) ?? source.ToArray(); return collection.ElementAtOrDefault(collection.Count - index.Value); } return source.ElementAtOrDefault(index.Value); } public static T FirstOrDefault<T>(this IEnumerable<T> source, T defaultValue) { using IEnumerator<T> enumerator = source.GetEnumerator(); if (enumerator.MoveNext()) { return enumerator.Current; } return defaultValue; } public static T FirstOrDefault<T>(this IEnumerable<T> source, Func<T, bool> predicate, T defaultValue) { foreach (T item in source) { if (predicate(item)) { return item; } } return defaultValue; } public static T LastOrDefault<T>(this IEnumerable<T> source, T defaultValue) { T result = defaultValue; foreach (T item in source) { result = item; } return result; } public static T LastOrDefault<T>(this IEnumerable<T> source, Func<T, bool> predicate, T defaultValue) { T result = defaultValue; foreach (T item in source) { if (predicate(item)) { result = item; } } return result; } public static T SingleOrDefault<T>(this IEnumerable<T> source, T defaultValue) { T result = defaultValue; bool flag = false; foreach (T item in source) { if (flag) { throw new InvalidOperationException("Sequence contains more than one element."); } result = item; flag = true; } return result; } public static T SingleOrDefault<T>(this IEnumerable<T> source, Func<T, bool> predicate, T defaultValue) { T result = defaultValue; bool flag = false; foreach (T item in source) { if (predicate(item)) { if (flag) { throw new InvalidOperationException("Sequence contains more than one element."); } result = item; flag = true; } } return result; } public static IEnumerable<T> Take<T>(this IEnumerable<T> source, Range range) { ICollection<T> collection = (source as ICollection<T>) ?? source.ToArray(); var (count, count2) = range.GetOffsetAndLength(collection.Count); return collection.Skip(count).Take(count2); } public static T? Min<T>(this IEnumerable<T> source, IComparer<T>? comparer) { return source.OrderBy((T x) => x, comparer).FirstOrDefault(); } public static T? MinBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector, IComparer<TKey>? comparer) { return source.OrderBy(keySelector, comparer).FirstOrDefault(); } public static T? MinBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector) { return MinBy(source, keySelector, Comparer<TKey>.Default); } public static T? Max<T>(this IEnumerable<T> source, IComparer<T>? comparer) { return source.OrderByDescending((T x) => x, comparer).FirstOrDefault(); } public static T? MaxBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector, IComparer<TKey>? comparer) { return source.OrderByDescending(keySelector, comparer).FirstOrDefault(); } public static T? MaxBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector) { return MaxBy(source, keySelector, Comparer<TKey>.Default); } public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector, IEqualityComparer<TKey>? comparer) { return from x in source.GroupBy(keySelector, comparer) select x.First(); } public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector) { return DistinctBy(source, keySelector, EqualityComparer<TKey>.Default); } public static IEnumerable<T> ExceptBy<T, TKey>(this IEnumerable<T> source, IEnumerable<TKey> other, Func<T, TKey> keySelector, IEqualityComparer<TKey>? comparer) { HashSet<TKey> set = new HashSet<TKey>(other, comparer); foreach (T item in source) { if (!set.Contains(keySelector(item))) { yield return item; } } } public static IEnumerable<T> ExceptBy<T, TKey>(this IEnumerable<T> source, IEnumerable<TKey> other, Func<T, TKey> keySelector) { return ExceptBy(source, other, keySelector, EqualityComparer<TKey>.Default); } public static IEnumerable<T> IntersectBy<T, TKey>(this IEnumerable<T> source, IEnumerable<TKey> other, Func<T, TKey> keySelector, IEqualityComparer<TKey>? comparer) { HashSet<TKey> set = new HashSet<TKey>(other, comparer); foreach (T item in source) { if (set.Contains(keySelector(item))) { yield return item; } } } public static IEnumerable<T> IntersectBy<T, TKey>(this IEnumerable<T> source, IEnumerable<TKey> other, Func<T, TKey> keySelector) { return IntersectBy(source, other, keySelector, EqualityComparer<TKey>.Default); } public static IEnumerable<T> UnionBy<T, TKey>(this IEnumerable<T> source, IEnumerable<T> other, Func<T, TKey> keySelector, IEqualityComparer<TKey>? comparer) { HashSet<TKey> set = new HashSet<TKey>(comparer); foreach (T item in source) { if (set.Add(keySelector(item))) { yield return item; } } foreach (T item2 in other) { if (set.Add(keySelector(item2))) { yield return item2; } } } public static IEnumerable<T> UnionBy<T, TKey>(this IEnumerable<T> source, IEnumerable<T> other, Func<T, TKey> keySelector) { return UnionBy(source, other, keySelector, EqualityComparer<TKey>.Default); } public static IEnumerable<T[]> Chunk<T>(this IEnumerable<T> source, int size) { List<T> chunk = new List<T>(size); foreach (T item in source) { chunk.Add(item); if (chunk.Count == size) { yield return chunk.ToArray(); chunk.Clear(); } } if (chunk.Count > 0) { yield return chunk.ToArray(); } } public static IOrderedEnumerable<T> Order<T>(this IEnumerable<T> source, IComparer<T>? comparer) { return source.OrderBy((T x) => x, comparer); } public static IOrderedEnumerable<T> Order<T>(this IEnumerable<T> source) { return source.Order(Comparer<T>.Default); } public static IOrderedEnumerable<T> OrderDescending<T>(this IEnumerable<T> source, IComparer<T>? comparer) { return source.OrderByDescending((T x) => x, comparer); } public static IOrderedEnumerable<T> OrderDescending<T>(this IEnumerable<T> source) { return source.OrderDescending(Comparer<T>.Default); } public static IEnumerable<(TFirst left, TSecond right)> Zip<TFirst, TSecond>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second) { return first.Zip(second, (TFirst x, TSecond y) => (x, y)); } } } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, Inherited = false)] [ExcludeFromCodeCoverage] internal class LibraryImportAttribute : Attribute { public string LibraryName { get; } public string? EntryPoint { get; init; } public bool SetLastError { get; init; } public StringMarshalling StringMarshalling { get; init; } public Type? StringMarshallingCustomType { get; init; } public LibraryImportAttribute(string libraryName) { LibraryName = libraryName; } } internal enum StringMarshalling { Custom, Utf8, Utf16 } } namespace System.Runtime.CompilerServices { [ExcludeFromCodeCoverage] internal static class IsExternalInit { } [AttributeUsage(AttributeTargets.Method, Inherited = false)] [ExcludeFromCodeCoverage] internal class ModuleInitializerAttribute : Attribute { } [AttributeUsage(AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Interface, Inherited = false)] [ExcludeFromCodeCoverage] internal class SkipLocalsInitAttribute : Attribute { } [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] [ExcludeFromCodeCoverage] internal class CompilerFeatureRequiredAttribute : Attribute { public const string RefStructs = "RefStructs"; public const string RequiredMembers = "RequiredMembers"; public string FeatureName { get; } public bool IsOptional { get; init; } public CompilerFeatureRequiredAttribute(string featureName) { FeatureName = featureName; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field, Inherited = false)] [ExcludeFromCodeCoverage] internal class RequiredMemberAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter)] [ExcludeFromCodeCoverage] internal class CallerArgumentExpressionAttribute : Attribute { public string ParameterName { get; } public CallerArgumentExpressionAttribute(string parameterName) { ParameterName = parameterName; } } } namespace System.Diagnostics.CodeAnalysis { [Flags] internal enum DynamicallyAccessedMemberTypes { All = -1, None = 0, PublicParameterlessConstructor = 1, PublicConstructors = 3, NonPublicConstructors = 4, PublicMethods = 8, NonPublicMethods = 0x10, PublicFields = 0x20, NonPublicFields = 0x40, PublicNestedTypes = 0x80, NonPublicNestedTypes = 0x100, PublicProperties = 0x200, NonPublicProperties = 0x400, PublicEvents = 0x800, NonPublicEvents = 0x1000, Interfaces = 0x2000 } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, Inherited = false)] [ExcludeFromCodeCoverage] internal class DynamicallyAccessedMembersAttribute : Attribute { public DynamicallyAccessedMemberTypes MemberTypes { get; } public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes) { MemberTypes = memberTypes; } } [AttributeUsage(AttributeTargets.Constructor)] [ExcludeFromCodeCoverage] internal class SetsRequiredMembersAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)] [ExcludeFromCodeCoverage] internal class StringSyntaxAttribute : Attribute { public const string CompositeFormat = "CompositeFormat"; public const string DateOnlyFormat = "DateOnlyFormat"; public const string DateTimeFormat = "DateTimeFormat"; public const string EnumFormat = "EnumFormat"; public const string GuidFormat = "GuidFormat"; public const string Json = "Json"; public const string NumericFormat = "NumericFormat"; public const string Regex = "Regex"; public const string TimeOnlyFormat = "TimeOnlyFormat"; public const string TimeSpanFormat = "TimeSpanFormat"; public const string Uri = "Uri"; public const string Xml = "Xml"; public string Syntax { get; } public object?[] Arguments { get; } public StringSyntaxAttribute(string syntax, params object?[] arguments) { Syntax = syntax; Arguments = arguments; } public StringSyntaxAttribute(string syntax) : this(syntax, new object[0]) { } } } namespace System.Threading.Tasks { internal static class PolyfillExtensions { } } namespace System.Net.Http { internal static class PolyfillExtensions { } } namespace System.Management { internal static class PolyfillExtensions { } } namespace System.IO { internal static class PolyfillExtensions { } }
YoutubeExplode.dll
Decompiled 2 years 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.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using AngleSharp.Dom; using AngleSharp.Html.Dom; using AngleSharp.Html.Parser; using Deorcify; using Microsoft.CodeAnalysis; using YoutubeExplode.Bridge; using YoutubeExplode.Bridge.Cipher; using YoutubeExplode.Channels; using YoutubeExplode.Common; using YoutubeExplode.Exceptions; using YoutubeExplode.Playlists; using YoutubeExplode.Search; using YoutubeExplode.Utils; using YoutubeExplode.Utils.Extensions; using YoutubeExplode.Videos; using YoutubeExplode.Videos.ClosedCaptions; using YoutubeExplode.Videos.Streams; [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("Tyrrrz")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright (C) Oleksii Holub")] [assembly: AssemblyDescription("Abstraction layer over YouTube's internal API. Note: this package has limited availability in Russia and Belarus.")] [assembly: AssemblyFileVersion("6.3.9.0")] [assembly: AssemblyInformationalVersion("6.3.9+41b4c289ceb64cc930aedcdb039d01bdf830b435")] [assembly: AssemblyProduct("YoutubeExplode")] [assembly: AssemblyTitle("YoutubeExplode")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/Tyrrrz/YoutubeExplode")] [assembly: AssemblyVersion("6.3.9.0")] [module: RefSafetyRules(11)] internal class <Module> { static <Module>() { Initializer.Execute(); } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } internal static class PolyfillExtensions { public static async Task<Stream> GetStreamAsync(this HttpClient httpClient, string requestUri, CancellationToken cancellationToken = default(CancellationToken)) { _ = 1; try { HttpResponseMessage obj = await httpClient.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); obj.EnsureSuccessStatusCode(); return await ReadAsStreamAsync(obj.Content, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } catch (OperationCanceledException ex) when (ex.CancellationToken != cancellationToken && cancellationToken.IsCancellationRequested) { throw new OperationCanceledException(ex.Message, ex.InnerException, cancellationToken); } } public static async Task<Stream> GetStreamAsync(this HttpClient httpClient, Uri requestUri, CancellationToken cancellationToken = default(CancellationToken)) { return await GetStreamAsync(httpClient, requestUri.ToString(), cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static async Task<byte[]> GetByteArrayAsync(this HttpClient httpClient, string requestUri, CancellationToken cancellationToken = default(CancellationToken)) { _ = 1; try { using HttpResponseMessage response = await httpClient.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); response.EnsureSuccessStatusCode(); return await ReadAsByteArrayAsync(response.Content, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } catch (OperationCanceledException ex) when (ex.CancellationToken != cancellationToken && cancellationToken.IsCancellationRequested) { throw new OperationCanceledException(ex.Message, ex.InnerException, cancellationToken); } } public static async Task<byte[]> GetByteArrayAsync(this HttpClient httpClient, Uri requestUri, CancellationToken cancellationToken = default(CancellationToken)) { return await GetByteArrayAsync(httpClient, requestUri.ToString(), cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static async Task<string> GetStringAsync(this HttpClient httpClient, string requestUri, CancellationToken cancellationToken = default(CancellationToken)) { _ = 1; try { using HttpResponseMessage response = await httpClient.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); response.EnsureSuccessStatusCode(); return await ReadAsStringAsync(response.Content, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } catch (OperationCanceledException ex) when (ex.CancellationToken != cancellationToken && cancellationToken.IsCancellationRequested) { throw new OperationCanceledException(ex.Message, ex.InnerException, cancellationToken); } } public static async Task<string> GetStringAsync(this HttpClient httpClient, Uri requestUri, CancellationToken cancellationToken = default(CancellationToken)) { return await GetStringAsync(httpClient, requestUri.ToString(), cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static async Task<Stream> ReadAsStreamAsync(this HttpContent httpContent, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); return await httpContent.ReadAsStreamAsync().ConfigureAwait(continueOnCapturedContext: false); } public static async Task<byte[]> ReadAsByteArrayAsync(this HttpContent httpContent, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); return await httpContent.ReadAsByteArrayAsync().ConfigureAwait(continueOnCapturedContext: false); } public static async Task<string> ReadAsStringAsync(this HttpContent httpContent, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); return await httpContent.ReadAsStringAsync().ConfigureAwait(continueOnCapturedContext: false); } public static async Task WaitForExitAsync(this Process process, CancellationToken cancellationToken = default(CancellationToken)) { TaskCompletionSource<object?> tcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously); try { process.EnableRaisingEvents = true; } catch when (process.HasExited) { return; } process.Exited += HandleExited; try { using (cancellationToken.Register(delegate { tcs.TrySetCanceled(cancellationToken); })) { await tcs.Task; } } finally { process.Exited -= HandleExited; } void HandleExited(object? sender, EventArgs args) { tcs.TrySetResult(null); } } public static bool IsAssignableTo(this Type type, Type? otherType) { return otherType?.IsAssignableFrom(type) ?? false; } public static async Task WaitAsync(this Task task, TimeSpan timeout, CancellationToken cancellationToken) { Task cancellationTask = Task.Delay(timeout, cancellationToken); Task finishedTask = await Task.WhenAny(new Task[2] { task, cancellationTask }).ConfigureAwait(continueOnCapturedContext: false); await finishedTask.ConfigureAwait(continueOnCapturedContext: false); if (finishedTask == cancellationTask) { throw new TimeoutException("The operation has timed out."); } } public static async Task WaitAsync(this Task task, CancellationToken cancellationToken) { await WaitAsync(task, Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static async Task WaitAsync(this Task task, TimeSpan timeout) { await WaitAsync(task, timeout, CancellationToken.None).ConfigureAwait(continueOnCapturedContext: false); } public static async Task<T> WaitAsync<T>(this Task<T> task, TimeSpan timeout, CancellationToken cancellationToken) { Task cancellationTask = Task.Delay(timeout, cancellationToken); Task finishedTask = await Task.WhenAny(new Task[2] { task, cancellationTask }).ConfigureAwait(continueOnCapturedContext: false); await finishedTask.ConfigureAwait(continueOnCapturedContext: false); if (finishedTask == cancellationTask) { throw new TimeoutException("The operation has timed out."); } return task.Result; } public static async Task<T> WaitAsync<T>(this Task<T> task, CancellationToken cancellationToken) { return await WaitAsync(task, Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static async Task<T> WaitAsync<T>(this Task<T> task, TimeSpan timeout) { return await WaitAsync(task, timeout, CancellationToken.None).ConfigureAwait(continueOnCapturedContext: false); } public static int ReadAtLeast(this Stream stream, byte[] buffer, int minimumBytes, bool throwOnEndOfStream = true) { int i; int num; for (i = 0; i < buffer.Length; i += num) { num = stream.Read(buffer, i, Math.Min(minimumBytes, buffer.Length - i)); if (num <= 0) { break; } } if (i < minimumBytes && throwOnEndOfStream) { throw new EndOfStreamException(); } return i; } public static void ReadExactly(this Stream stream, byte[] buffer, int offset, int count) { int num; for (int i = 0; i < count; i += num) { num = stream.Read(buffer, offset + i, count - i); if (num <= 0) { throw new EndOfStreamException(); } } } public static void ReadExactly(this Stream stream, byte[] buffer) { stream.ReadExactly(buffer, 0, buffer.Length); } public static async Task<int> ReadAtLeastAsync(this Stream stream, byte[] buffer, int minimumBytes, bool throwOnEndOfStream = true, CancellationToken cancellationToken = default(CancellationToken)) { int totalBytesRead; int num; for (totalBytesRead = 0; totalBytesRead < buffer.Length; totalBytesRead += num) { num = await stream.ReadAsync(buffer, totalBytesRead, Math.Min(minimumBytes, buffer.Length - totalBytesRead), cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (num <= 0) { break; } } if (totalBytesRead < minimumBytes && throwOnEndOfStream) { throw new EndOfStreamException(); } return totalBytesRead; } public static async Task ReadExactlyAsync(this Stream stream, byte[] buffer, int offset, int count, CancellationToken cancellationToken = default(CancellationToken)) { int num; for (int totalBytesRead = 0; totalBytesRead < count; totalBytesRead += num) { num = await stream.ReadAsync(buffer, offset + totalBytesRead, count - totalBytesRead, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (num <= 0) { throw new EndOfStreamException(); } } } public static async Task ReadExactlyAsync(this Stream stream, byte[] buffer, CancellationToken cancellationToken = default(CancellationToken)) { await stream.ReadExactlyAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static int ReadAtLeast(this Stream stream, Span<byte> buffer, int minimumBytes, bool throwOnEndOfStream = true) { int i; int num; for (i = 0; i < buffer.Length; i += num) { num = stream.Read(buffer.Slice(i)); if (num <= 0) { break; } } if (i < minimumBytes && throwOnEndOfStream) { throw new EndOfStreamException(); } return i; } public static void ReadExactly(this Stream stream, Span<byte> buffer) { byte[] array = buffer.ToArray(); stream.ReadExactly(array, 0, array.Length); array.CopyTo(buffer); } public static async Task<int> ReadAtLeastAsync(this Stream stream, Memory<byte> buffer, int minimumBytes, bool throwOnEndOfStream = true, CancellationToken cancellationToken = default(CancellationToken)) { int totalBytesRead; int num; for (totalBytesRead = 0; totalBytesRead < buffer.Length; totalBytesRead += num) { num = await stream.ReadAsync(buffer.Slice(totalBytesRead), cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (num <= 0) { break; } } if (totalBytesRead < minimumBytes && throwOnEndOfStream) { throw new EndOfStreamException(); } return totalBytesRead; } public static async Task ReadExactlyAsync(this Stream stream, Memory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken)) { byte[] bufferArray = buffer.ToArray(); await stream.ReadExactlyAsync(bufferArray, 0, bufferArray.Length, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); bufferArray.CopyTo(buffer); } } namespace YoutubeExplode { public class YoutubeClient { public VideoClient Videos { get; } public PlaylistClient Playlists { get; } public ChannelClient Channels { get; } public SearchClient Search { get; } public YoutubeClient(HttpClient http, IReadOnlyList<Cookie> initialCookies) { HttpClient http2 = new HttpClient(new YoutubeHttpHandler(http, initialCookies), disposeHandler: true); Videos = new VideoClient(http2); Playlists = new PlaylistClient(http2); Channels = new ChannelClient(http2); Search = new SearchClient(http2); } public YoutubeClient(HttpClient http) : this(http, Array.Empty<Cookie>()) { } public YoutubeClient(IReadOnlyList<Cookie> initialCookies) : this(Http.Client, initialCookies) { } public YoutubeClient() : this(Http.Client) { } } internal class YoutubeHttpHandler : ClientDelegatingHandler { private readonly CookieContainer _cookieContainer = new CookieContainer(); public YoutubeHttpHandler(HttpClient http, IReadOnlyList<Cookie> initialCookies, bool disposeClient = false) : base(http, disposeClient) { foreach (Cookie initialCookie in initialCookies) { _cookieContainer.Add(initialCookie); } _cookieContainer.Add(new Cookie("SOCS", "CAISNQgDEitib3FfaWRlbnRpdHlmcm9udGVuZHVpc2VydmVyXzIwMjMwODI5LjA3X3AxGgJlbiACGgYIgLC_pwY") { Domain = "youtube.com" }); } private string? TryGenerateAuthHeaderValue(Uri uri) { Cookie[] source = _cookieContainer.GetCookies(uri).Cast<Cookie>().ToArray(); string text = source.FirstOrDefault((Cookie c) => string.Equals(c.Name, "__Secure-3PAPISID", StringComparison.Ordinal))?.Value ?? source.FirstOrDefault((Cookie c) => string.Equals(c.Name, "SAPISID", StringComparison.Ordinal))?.Value; if (string.IsNullOrWhiteSpace(text)) { return null; } long num = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); string domain = uri.GetDomain(); string s = $"{num} {text} {domain}"; string arg = Hash.Compute(SHA1.Create(), Encoding.UTF8.GetBytes(s)).ToHex(); return $"SAPISIDHASH {num}_{arg}"; } private HttpRequestMessage HandleRequest(HttpRequestMessage request) { if ((object)request.RequestUri == null) { return request; } if (request.RequestUri.AbsolutePath.StartsWith("/youtubei/", StringComparison.Ordinal) && !UrlEx.ContainsQueryParameter(request.RequestUri.Query, "key")) { request.RequestUri = new Uri(UrlEx.SetQueryParameter(request.RequestUri.OriginalString, "key", "AIzaSyA8eiZmM1FaDVjRy-df2KTyQ_vz_yYM39w")); } if (!UrlEx.ContainsQueryParameter(request.RequestUri.Query, "hl")) { request.RequestUri = new Uri(UrlEx.SetQueryParameter(request.RequestUri.OriginalString, "hl", "en")); } if (!request.Headers.Contains("Origin")) { request.Headers.Add("Origin", request.RequestUri.GetDomain()); } if (!request.Headers.Contains("User-Agent")) { request.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36"); } if (!request.Headers.Contains("Cookie") && _cookieContainer.Count > 0) { string cookieHeader = _cookieContainer.GetCookieHeader(request.RequestUri); if (!string.IsNullOrWhiteSpace(cookieHeader)) { request.Headers.Add("Cookie", cookieHeader); } } if (!request.Headers.Contains("Authorization")) { string text = TryGenerateAuthHeaderValue(request.RequestUri); if (text != null) { request.Headers.Add("Authorization", text); } } return request; } private HttpResponseMessage HandleResponse(HttpResponseMessage response) { if ((object)response.RequestMessage?.RequestUri == null) { return response; } if (response.StatusCode == HttpStatusCode.TooManyRequests) { throw new RequestLimitExceededException("Exceeded request rate limit. Please try again in a few hours. Alternatively, inject cookies corresponding to a pre-authenticated user when initializing an instance of `YoutubeClient`."); } if (response.Headers.TryGetValues("Set-Cookie", out IEnumerable<string> values)) { foreach (string item in values) { _cookieContainer.SetCookies(response.RequestMessage.RequestUri, item); } } return response; } protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { int retriesRemaining = 5; while (true) { try { HttpResponseMessage httpResponseMessage = HandleResponse(await base.SendAsync(HandleRequest(request), cancellationToken)); if (httpResponseMessage.StatusCode < HttpStatusCode.InternalServerError || retriesRemaining <= 0) { return httpResponseMessage; } httpResponseMessage.Dispose(); } catch (HttpRequestException) when (retriesRemaining > 0) { } retriesRemaining--; } } } } namespace YoutubeExplode.Videos { public class Engagement { public long ViewCount { get; } public long LikeCount { get; } public long DislikeCount { get; } public double AverageRating { get { if (LikeCount + DislikeCount == 0L) { return 0.0; } return 1.0 + 4.0 * (double)LikeCount / (double)(LikeCount + DislikeCount); } } public Engagement(long viewCount, long likeCount, long dislikeCount) { ViewCount = viewCount; LikeCount = likeCount; DislikeCount = dislikeCount; } [ExcludeFromCodeCoverage] public override string ToString() { return $"Rating: {AverageRating:N1}"; } } public interface IVideo { VideoId Id { get; } string Url { get; } string Title { get; } Author Author { get; } TimeSpan? Duration { get; } IReadOnlyList<Thumbnail> Thumbnails { get; } } public class Video : IVideo { public VideoId Id { get; } public string Url => $"https://www.youtube.com/watch?v={Id}"; public string Title { get; } public Author Author { get; } public DateTimeOffset UploadDate { get; } public string Description { get; } public TimeSpan? Duration { get; } public IReadOnlyList<Thumbnail> Thumbnails { get; } public IReadOnlyList<string> Keywords { get; } public Engagement Engagement { get; } public Video(VideoId id, string title, Author author, DateTimeOffset uploadDate, string description, TimeSpan? duration, IReadOnlyList<Thumbnail> thumbnails, IReadOnlyList<string> keywords, Engagement engagement) { Id = id; Title = title; Author = author; UploadDate = uploadDate; Description = description; Duration = duration; Thumbnails = thumbnails; Keywords = keywords; Engagement = engagement; } [ExcludeFromCodeCoverage] public override string ToString() { return "Video (" + Title + ")"; } } public class VideoClient { private readonly VideoController _controller; public StreamClient Streams { get; } public ClosedCaptionClient ClosedCaptions { get; } public VideoClient(HttpClient http) { _controller = new VideoController(http); Streams = new StreamClient(http); ClosedCaptions = new ClosedCaptionClient(http); } public async ValueTask<Video> GetAsync(VideoId videoId, CancellationToken cancellationToken = default(CancellationToken)) { VideoWatchPage watchPage = await _controller.GetVideoWatchPageAsync(videoId, cancellationToken); PlayerResponse playerResponse = watchPage.PlayerResponse; if (playerResponse == null) { playerResponse = await _controller.GetPlayerResponseAsync(videoId, cancellationToken); } PlayerResponse playerResponse2 = playerResponse; string title = playerResponse2.Title ?? ""; string channelTitle = playerResponse2.Author ?? throw new YoutubeExplodeException("Could not extract video author."); string text = playerResponse2.ChannelId ?? throw new YoutubeExplodeException("Could not extract video channel ID."); DateTimeOffset uploadDate = playerResponse2.UploadDate ?? watchPage.UploadDate ?? throw new YoutubeExplodeException("Could not extract video upload date."); Thumbnail[] thumbnails = playerResponse2.Thumbnails.Select(delegate(ThumbnailData t) { string? url = t.Url ?? throw new YoutubeExplodeException("Could not extract thumbnail URL."); int width = t.Width ?? throw new YoutubeExplodeException("Could not extract thumbnail width."); int height = t.Height ?? throw new YoutubeExplodeException("Could not extract thumbnail height."); Resolution resolution = new Resolution(width, height); return new Thumbnail(url, resolution); }).Concat(Thumbnail.GetDefaultSet(videoId)).ToArray(); return new Video(videoId, title, new Author(text, channelTitle), uploadDate, playerResponse2.Description ?? "", playerResponse2.Duration, thumbnails, playerResponse2.Keywords, new Engagement(playerResponse2.ViewCount.GetValueOrDefault(), watchPage.LikeCount.GetValueOrDefault(), watchPage.DislikeCount.GetValueOrDefault())); } } internal class VideoController { protected HttpClient Http { get; } public VideoController(HttpClient http) { Http = http; } public async ValueTask<VideoWatchPage> GetVideoWatchPageAsync(VideoId videoId, CancellationToken cancellationToken = default(CancellationToken)) { int retriesRemaining = 5; VideoWatchPage videoWatchPage; while (true) { videoWatchPage = VideoWatchPage.TryParse(await PolyfillExtensions.GetStringAsync(Http, $"https://www.youtube.com/watch?v={videoId}&bpctr=9999999999", cancellationToken)); if (videoWatchPage != null) { break; } if (retriesRemaining <= 0) { throw new YoutubeExplodeException("Video watch page is broken. Please try again in a few minutes."); } retriesRemaining--; } if (!videoWatchPage.IsAvailable) { throw new VideoUnavailableException($"Video '{videoId}' is not available."); } return videoWatchPage; } public async ValueTask<PlayerResponse> GetPlayerResponseAsync(VideoId videoId, CancellationToken cancellationToken = default(CancellationToken)) { using HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://www.youtube.com/youtubei/v1/player") { Content = new StringContent($"{{\r\n \"videoId\": \"{videoId}\",\r\n \"context\": {{\r\n \"client\": {{\r\n \"clientName\": \"ANDROID_TESTSUITE\",\r\n \"clientVersion\": \"1.9\",\r\n \"androidSdkVersion\": 30,\r\n \"hl\": \"en\",\r\n \"gl\": \"US\",\r\n \"utcOffsetMinutes\": 0\r\n }}\r\n }}\r\n}}") }; request.Headers.Add("User-Agent", "com.google.android.youtube/17.36.4 (Linux; U; Android 12; GB) gzip"); using HttpResponseMessage response = await Http.SendAsync(request, cancellationToken); response.EnsureSuccessStatusCode(); PlayerResponse playerResponse = PlayerResponse.Parse(await PolyfillExtensions.ReadAsStringAsync(response.Content, cancellationToken)); if (!playerResponse.IsAvailable) { throw new VideoUnavailableException($"Video '{videoId}' is not available."); } return playerResponse; } public async ValueTask<PlayerResponse> GetPlayerResponseAsync(VideoId videoId, string? signatureTimestamp, CancellationToken cancellationToken = default(CancellationToken)) { using HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://www.youtube.com/youtubei/v1/player") { Content = new StringContent(string.Format("{{\r\n \"videoId\": \"{0}\",\r\n \"context\": {{\r\n \"client\": {{\r\n \"clientName\": \"TVHTML5_SIMPLY_EMBEDDED_PLAYER\",\r\n \"clientVersion\": \"2.0\",\r\n \"hl\": \"en\",\r\n \"gl\": \"US\",\r\n \"utcOffsetMinutes\": 0\r\n }},\r\n \"thirdParty\": {{\r\n \"embedUrl\": \"https://www.youtube.com\"\r\n }}\r\n }},\r\n \"playbackContext\": {{\r\n \"contentPlaybackContext\": {{\r\n \"signatureTimestamp\": \"{1}\"\r\n }}\r\n }}\r\n}}", videoId, signatureTimestamp ?? "19369")) }; using HttpResponseMessage response = await Http.SendAsync(request, cancellationToken); response.EnsureSuccessStatusCode(); PlayerResponse playerResponse = PlayerResponse.Parse(await PolyfillExtensions.ReadAsStringAsync(response.Content, cancellationToken)); if (!playerResponse.IsAvailable) { throw new VideoUnavailableException($"Video '{videoId}' is not available."); } return playerResponse; } } public readonly struct VideoId : IEquatable<VideoId> { public string Value { get; } private VideoId(string value) { Value = value; } public override string ToString() { return Value; } private static bool IsValid(string videoId) { if (videoId.Length == 11) { return videoId.All(delegate(char c) { bool flag = char.IsLetterOrDigit(c); if (!flag) { bool flag2 = ((c == '-' || c == '_') ? true : false); flag = flag2; } return flag; }); } return false; } private static string? TryNormalize(string? videoIdOrUrl) { if (string.IsNullOrWhiteSpace(videoIdOrUrl)) { return null; } if (IsValid(videoIdOrUrl)) { return videoIdOrUrl; } string text = Regex.Match(videoIdOrUrl, "youtube\\..+?/watch.*?v=(.*?)(?:&|/|$)").Groups[1].Value.Pipe(WebUtility.UrlDecode); if (!string.IsNullOrWhiteSpace(text) && IsValid(text)) { return text; } string text2 = Regex.Match(videoIdOrUrl, "youtu\\.be/(.*?)(?:\\?|&|/|$)").Groups[1].Value.Pipe(WebUtility.UrlDecode); if (!string.IsNullOrWhiteSpace(text2) && IsValid(text2)) { return text2; } string text3 = Regex.Match(videoIdOrUrl, "youtube\\..+?/embed/(.*?)(?:\\?|&|/|$)").Groups[1].Value.Pipe(WebUtility.UrlDecode); if (!string.IsNullOrWhiteSpace(text3) && IsValid(text3)) { return text3; } string text4 = Regex.Match(videoIdOrUrl, "youtube\\..+?/shorts/(.*?)(?:\\?|&|/|$)").Groups[1].Value.Pipe(WebUtility.UrlDecode); if (!string.IsNullOrWhiteSpace(text4) && IsValid(text4)) { return text4; } string text5 = Regex.Match(videoIdOrUrl, "youtube\\..+?/live/(.*?)(?:\\?|&|/|$)").Groups[1].Value.Pipe(WebUtility.UrlDecode); if (!string.IsNullOrWhiteSpace(text5) && IsValid(text5)) { return text5; } return null; } public static VideoId? TryParse(string? videoIdOrUrl) { return TryNormalize(videoIdOrUrl)?.Pipe((string id) => new VideoId(id)); } public static VideoId Parse(string videoIdOrUrl) { return TryParse(videoIdOrUrl) ?? throw new ArgumentException("Invalid YouTube video ID or URL '" + videoIdOrUrl + "'."); } public static implicit operator VideoId(string videoIdOrUrl) { return Parse(videoIdOrUrl); } public static implicit operator string(VideoId videoId) { return videoId.ToString(); } public bool Equals(VideoId other) { return StringComparer.Ordinal.Equals(Value, other.Value); } public override bool Equals(object? obj) { if (obj is VideoId other) { return Equals(other); } return false; } public override int GetHashCode() { return StringComparer.Ordinal.GetHashCode(Value); } public static bool operator ==(VideoId left, VideoId right) { return left.Equals(right); } public static bool operator !=(VideoId left, VideoId right) { return !(left == right); } } } namespace YoutubeExplode.Videos.Streams { public class AudioOnlyStreamInfo : IAudioStreamInfo, IStreamInfo { public string Url { get; } public Container Container { get; } public FileSize Size { get; } public Bitrate Bitrate { get; } public string AudioCodec { get; } public AudioOnlyStreamInfo(string url, Container container, FileSize size, Bitrate bitrate, string audioCodec) { Url = url; Container = container; Size = size; Bitrate = bitrate; AudioCodec = audioCodec; } [ExcludeFromCodeCoverage] public override string ToString() { return $"Audio-only ({Container})"; } } public readonly struct Bitrate : IComparable<Bitrate>, IEquatable<Bitrate> { public long BitsPerSecond { get; } public double KiloBitsPerSecond => (double)BitsPerSecond / 1024.0; public double MegaBitsPerSecond => KiloBitsPerSecond / 1024.0; public double GigaBitsPerSecond => MegaBitsPerSecond / 1024.0; public Bitrate(long bitsPerSecond) { BitsPerSecond = bitsPerSecond; } private string GetLargestWholeNumberSymbol() { if (Math.Abs(GigaBitsPerSecond) >= 1.0) { return "Gbit/s"; } if (Math.Abs(MegaBitsPerSecond) >= 1.0) { return "Mbit/s"; } if (Math.Abs(KiloBitsPerSecond) >= 1.0) { return "Kbit/s"; } return "Bit/s"; } private double GetLargestWholeNumberValue() { if (Math.Abs(GigaBitsPerSecond) >= 1.0) { return GigaBitsPerSecond; } if (Math.Abs(MegaBitsPerSecond) >= 1.0) { return MegaBitsPerSecond; } if (Math.Abs(KiloBitsPerSecond) >= 1.0) { return KiloBitsPerSecond; } return BitsPerSecond; } public override string ToString() { return $"{GetLargestWholeNumberValue():0.##} {GetLargestWholeNumberSymbol()}"; } public int CompareTo(Bitrate other) { return BitsPerSecond.CompareTo(other.BitsPerSecond); } public bool Equals(Bitrate other) { return CompareTo(other) == 0; } public override bool Equals(object? obj) { if (obj is Bitrate other) { return Equals(other); } return false; } public override int GetHashCode() { return HashCode.Combine(BitsPerSecond); } public static bool operator ==(Bitrate left, Bitrate right) { return left.Equals(right); } public static bool operator !=(Bitrate left, Bitrate right) { return !(left == right); } public static bool operator >(Bitrate left, Bitrate right) { return left.CompareTo(right) > 0; } public static bool operator <(Bitrate left, Bitrate right) { return left.CompareTo(right) < 0; } } public readonly struct Container : IEquatable<Container> { public string Name { get; } public bool IsAudioOnly { get { if (!string.Equals(Name, "mp3", StringComparison.OrdinalIgnoreCase) && !string.Equals(Name, "m4a", StringComparison.OrdinalIgnoreCase) && !string.Equals(Name, "wav", StringComparison.OrdinalIgnoreCase) && !string.Equals(Name, "wma", StringComparison.OrdinalIgnoreCase) && !string.Equals(Name, "ogg", StringComparison.OrdinalIgnoreCase) && !string.Equals(Name, "aac", StringComparison.OrdinalIgnoreCase)) { return string.Equals(Name, "opus", StringComparison.OrdinalIgnoreCase); } return true; } } public static Container Mp3 { get; } = new Container("mp3"); public static Container Mp4 { get; } = new Container("mp4"); public static Container WebM { get; } = new Container("webm"); public static Container Tgpp { get; } = new Container("3gpp"); public Container(string name) { Name = name; } public override string ToString() { return Name; } public bool Equals(Container other) { return StringComparer.OrdinalIgnoreCase.Equals(Name, other.Name); } public override bool Equals(object? obj) { if (obj is Container other) { return Equals(other); } return false; } public override int GetHashCode() { return StringComparer.OrdinalIgnoreCase.GetHashCode(Name); } public static bool operator ==(Container left, Container right) { return left.Equals(right); } public static bool operator !=(Container left, Container right) { return !(left == right); } } public readonly struct FileSize : IComparable<FileSize>, IEquatable<FileSize> { public long Bytes { get; } public double KiloBytes => (double)Bytes / 1024.0; public double MegaBytes => KiloBytes / 1024.0; public double GigaBytes => MegaBytes / 1024.0; public FileSize(long bytes) { Bytes = bytes; } private string GetLargestWholeNumberSymbol() { if (Math.Abs(GigaBytes) >= 1.0) { return "GB"; } if (Math.Abs(MegaBytes) >= 1.0) { return "MB"; } if (Math.Abs(KiloBytes) >= 1.0) { return "KB"; } return "B"; } private double GetLargestWholeNumberValue() { if (Math.Abs(GigaBytes) >= 1.0) { return GigaBytes; } if (Math.Abs(MegaBytes) >= 1.0) { return MegaBytes; } if (Math.Abs(KiloBytes) >= 1.0) { return KiloBytes; } return Bytes; } public override string ToString() { return $"{GetLargestWholeNumberValue():0.##} {GetLargestWholeNumberSymbol()}"; } public int CompareTo(FileSize other) { return Bytes.CompareTo(other.Bytes); } public bool Equals(FileSize other) { return CompareTo(other) == 0; } public override bool Equals(object? obj) { if (obj is FileSize other) { return Equals(other); } return false; } public override int GetHashCode() { return HashCode.Combine(Bytes); } public static bool operator ==(FileSize left, FileSize right) { return left.Equals(right); } public static bool operator !=(FileSize left, FileSize right) { return !(left == right); } public static bool operator >(FileSize left, FileSize right) { return left.CompareTo(right) > 0; } public static bool operator <(FileSize left, FileSize right) { return left.CompareTo(right) < 0; } } public interface IAudioStreamInfo : IStreamInfo { string AudioCodec { get; } } public interface IStreamInfo { string Url { get; } Container Container { get; } FileSize Size { get; } Bitrate Bitrate { get; } } public static class StreamInfoExtensions { internal static bool IsThrottled(this IStreamInfo streamInfo) { return !string.Equals(UrlEx.TryGetQueryParameterValue(streamInfo.Url, "ratebypass"), "yes", StringComparison.OrdinalIgnoreCase); } public static IStreamInfo? TryGetWithHighestBitrate(this IEnumerable<IStreamInfo> streamInfos) { return System.Linq.PolyfillExtensions.MaxBy(streamInfos, (IStreamInfo s) => s.Bitrate); } public static IStreamInfo GetWithHighestBitrate(this IEnumerable<IStreamInfo> streamInfos) { return streamInfos.TryGetWithHighestBitrate() ?? throw new InvalidOperationException("Input stream collection is empty."); } } public interface IVideoStreamInfo : IStreamInfo { string VideoCodec { get; } VideoQuality VideoQuality { get; } Resolution VideoResolution { get; } } public static class VideoStreamInfoExtensions { public static IVideoStreamInfo? TryGetWithHighestVideoQuality(this IEnumerable<IVideoStreamInfo> streamInfos) { return System.Linq.PolyfillExtensions.MaxBy(streamInfos, (IVideoStreamInfo s) => s.VideoQuality); } public static IVideoStreamInfo GetWithHighestVideoQuality(this IEnumerable<IVideoStreamInfo> streamInfos) { return streamInfos.TryGetWithHighestVideoQuality() ?? throw new InvalidOperationException("Input stream collection is empty."); } } internal class MediaStream : Stream { private readonly HttpClient _http; private readonly IStreamInfo _streamInfo; private readonly long _segmentLength; private Stream? _segmentStream; private long _actualPosition; [ExcludeFromCodeCoverage] public override bool CanRead => true; [ExcludeFromCodeCoverage] public override bool CanSeek => true; [ExcludeFromCodeCoverage] public override bool CanWrite => false; public override long Length => _streamInfo.Size.Bytes; public override long Position { get; set; } public MediaStream(HttpClient http, IStreamInfo streamInfo) { _http = http; _streamInfo = streamInfo; _segmentLength = (streamInfo.IsThrottled() ? 9898989 : streamInfo.Size.Bytes); } private void ResetSegment() { _segmentStream?.Dispose(); _segmentStream = null; } private async ValueTask<Stream> ResolveSegmentAsync(CancellationToken cancellationToken = default(CancellationToken)) { if (_segmentStream != null) { return _segmentStream; } long position = Position; long num = Position + _segmentLength - 1; string requestUri = UrlEx.SetQueryParameter(_streamInfo.Url, "range", $"{position}-{num}"); return _segmentStream = await PolyfillExtensions.GetStreamAsync(_http, requestUri, cancellationToken); } public async ValueTask InitializeAsync(CancellationToken cancellationToken = default(CancellationToken)) { await ResolveSegmentAsync(cancellationToken); } private async ValueTask<int> ReadSegmentAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken = default(CancellationToken)) { int retriesRemaining = 5; while (true) { try { return await (await ResolveSegmentAsync(cancellationToken)).ReadAsync(buffer, offset, count, cancellationToken); } catch (IOException) when (retriesRemaining > 0) { ResetSegment(); } retriesRemaining--; } } public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { int num; while (true) { long requestedPosition = Position; if (_actualPosition != requestedPosition) { ResetSegment(); } if (requestedPosition >= Length) { return 0; } num = await ReadSegmentAsync(buffer, offset, count, cancellationToken); Position = (_actualPosition = requestedPosition + num); if (num > 0) { break; } ResetSegment(); } return num; } [ExcludeFromCodeCoverage] public override int Read(byte[] buffer, int offset, int count) { return ReadAsync(buffer, offset, count).GetAwaiter().GetResult(); } [ExcludeFromCodeCoverage] public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } [ExcludeFromCodeCoverage] public override void SetLength(long value) { throw new NotSupportedException(); } [ExcludeFromCodeCoverage] public override long Seek(long offset, SeekOrigin origin) { return Position = origin switch { SeekOrigin.Begin => offset, SeekOrigin.Current => Position + offset, SeekOrigin.End => Length + offset, _ => throw new ArgumentOutOfRangeException("origin"), }; } [ExcludeFromCodeCoverage] public override void Flush() { throw new NotSupportedException(); } protected override void Dispose(bool disposing) { if (disposing) { ResetSegment(); } base.Dispose(disposing); } } public class MuxedStreamInfo : IAudioStreamInfo, IStreamInfo, IVideoStreamInfo { public string Url { get; } public Container Container { get; } public FileSize Size { get; } public Bitrate Bitrate { get; } public string AudioCodec { get; } public string VideoCodec { get; } public VideoQuality VideoQuality { get; } public Resolution VideoResolution { get; } public MuxedStreamInfo(string url, Container container, FileSize size, Bitrate bitrate, string audioCodec, string videoCodec, VideoQuality videoQuality, Resolution resolution) { Url = url; Container = container; Size = size; Bitrate = bitrate; AudioCodec = audioCodec; VideoCodec = videoCodec; VideoQuality = videoQuality; VideoResolution = resolution; } [ExcludeFromCodeCoverage] public override string ToString() { return $"Muxed ({VideoQuality} | {Container})"; } } public class StreamClient { private readonly HttpClient _http; private readonly StreamController _controller; private CipherManifest? _cipherManifest; public StreamClient(HttpClient http) { _http = http; _controller = new StreamController(http); } private async ValueTask<CipherManifest> ResolveCipherManifestAsync(CancellationToken cancellationToken) { if (_cipherManifest != null) { return _cipherManifest; } return _cipherManifest = (await _controller.GetPlayerSourceAsync(cancellationToken)).CipherManifest ?? throw new YoutubeExplodeException("Could not get cipher manifest."); } private async IAsyncEnumerable<IStreamInfo> GetStreamInfosAsync(IEnumerable<IStreamData> streamDatas, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken)) { foreach (IStreamData streamData in streamDatas) { int itag = streamData.Itag ?? throw new YoutubeExplodeException("Could not extract stream itag."); string url = streamData.Url ?? throw new YoutubeExplodeException("Could not extract stream URL."); if (!string.IsNullOrWhiteSpace(streamData.Signature)) { CipherManifest cipherManifest = await ResolveCipherManifestAsync(cancellationToken); url = UrlEx.SetQueryParameter(url, streamData.SignatureParameter ?? "sig", cipherManifest.Decipher(streamData.Signature)); } long num = streamData.ContentLength ?? (await _http.TryGetContentLengthAsync(url, ensureSuccess: false, cancellationToken)).GetValueOrDefault(); long num2 = num; if (num2 <= 0) { continue; } Container container = (streamData.Container ?? throw new YoutubeExplodeException("Could not extract stream container.")).Pipe((string s) => new Container(s)); Bitrate bitrate = (streamData.Bitrate ?? throw new YoutubeExplodeException("Could not extract stream bitrate.")).Pipe((long s) => new Bitrate(s)); if (!string.IsNullOrWhiteSpace(streamData.VideoCodec)) { int num3 = streamData.VideoFramerate ?? 24; VideoQuality videoQuality = ((!string.IsNullOrWhiteSpace(streamData.VideoQualityLabel)) ? VideoQuality.FromLabel(streamData.VideoQualityLabel, num3) : VideoQuality.FromItag(itag, num3)); Resolution resolution = ((streamData.VideoWidth.HasValue && streamData.VideoHeight.HasValue) ? new Resolution(streamData.VideoWidth.Value, streamData.VideoHeight.Value) : videoQuality.GetDefaultVideoResolution()); if (!string.IsNullOrWhiteSpace(streamData.AudioCodec)) { yield return new MuxedStreamInfo(url, container, new FileSize(num2), bitrate, streamData.AudioCodec, streamData.VideoCodec, videoQuality, resolution); } else { yield return new VideoOnlyStreamInfo(url, container, new FileSize(num2), bitrate, streamData.VideoCodec, videoQuality, resolution); } } else { if (string.IsNullOrWhiteSpace(streamData.AudioCodec)) { throw new YoutubeExplodeException("Could not extract stream codec."); } yield return new AudioOnlyStreamInfo(url, container, new FileSize(num2), bitrate, streamData.AudioCodec); } } } private async IAsyncEnumerable<IStreamInfo> GetStreamInfosAsync(VideoId videoId, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken)) { PlayerResponse playerResponse = await _controller.GetPlayerResponseAsync(videoId, cancellationToken); if (!string.IsNullOrWhiteSpace(playerResponse.PreviewVideoId)) { throw new VideoRequiresPurchaseException($"Video '{videoId}' requires purchase and cannot be played.", playerResponse.PreviewVideoId); } if (!playerResponse.IsPlayable) { CipherManifest cipherManifest = await ResolveCipherManifestAsync(cancellationToken); playerResponse = await _controller.GetPlayerResponseAsync(videoId, cipherManifest.SignatureTimestamp, cancellationToken); } if (!playerResponse.IsPlayable) { throw new VideoUnplayableException($"Video '{videoId}' is unplayable. " + "Reason: '" + playerResponse.PlayabilityError + "'."); } await foreach (IStreamInfo item in GetStreamInfosAsync(playerResponse.Streams, cancellationToken)) { yield return item; } if (string.IsNullOrWhiteSpace(playerResponse.DashManifestUrl)) { yield break; } DashManifest dashManifest = null; try { dashManifest = await _controller.GetDashManifestAsync(playerResponse.DashManifestUrl, cancellationToken); } catch (HttpRequestException) { } if (dashManifest == null) { yield break; } await foreach (IStreamInfo item2 in GetStreamInfosAsync(dashManifest.Streams, cancellationToken)) { yield return item2; } } public async ValueTask<StreamManifest> GetManifestAsync(VideoId videoId, CancellationToken cancellationToken = default(CancellationToken)) { int retriesRemaining = 5; while (true) { List<IStreamInfo> streamInfos = await GetStreamInfosAsync(videoId, cancellationToken); if (!streamInfos.Any()) { break; } using (HttpResponseMessage httpResponseMessage = await _http.HeadAsync(streamInfos.First().Url, cancellationToken)) { if (httpResponseMessage.StatusCode != HttpStatusCode.Forbidden || retriesRemaining <= 0) { httpResponseMessage.EnsureSuccessStatusCode(); return new StreamManifest(streamInfos); } } retriesRemaining--; } throw new VideoUnplayableException($"Video '{videoId}' does not contain any playable streams."); } public async ValueTask<string> GetHttpLiveStreamUrlAsync(VideoId videoId, CancellationToken cancellationToken = default(CancellationToken)) { PlayerResponse playerResponse = await _controller.GetPlayerResponseAsync(videoId, cancellationToken); if (!playerResponse.IsPlayable) { throw new VideoUnplayableException($"Video '{videoId}' is unplayable. " + "Reason: '" + playerResponse.PlayabilityError + "'."); } if (string.IsNullOrWhiteSpace(playerResponse.HlsManifestUrl)) { throw new YoutubeExplodeException("Could not extract HTTP Live Stream manifest URL. " + $"Video '{videoId}' is likely not a live stream."); } return playerResponse.HlsManifestUrl; } public async ValueTask<Stream> GetAsync(IStreamInfo streamInfo, CancellationToken cancellationToken = default(CancellationToken)) { MediaStream stream = new MediaStream(_http, streamInfo); await stream.InitializeAsync(cancellationToken); return stream; } public async ValueTask CopyToAsync(IStreamInfo streamInfo, Stream destination, IProgress<double>? progress = null, CancellationToken cancellationToken = default(CancellationToken)) { using Stream input = await GetAsync(streamInfo, cancellationToken); await input.CopyToAsync(destination, progress, cancellationToken); } public async ValueTask DownloadAsync(IStreamInfo streamInfo, string filePath, IProgress<double>? progress = null, CancellationToken cancellationToken = default(CancellationToken)) { using FileStream destination = File.Create(filePath); await CopyToAsync(streamInfo, destination, progress, cancellationToken); } } internal class StreamController : VideoController { public StreamController(HttpClient http) : base(http) { } public async ValueTask<PlayerSource> GetPlayerSourceAsync(CancellationToken cancellationToken = default(CancellationToken)) { string value = Regex.Match(await PolyfillExtensions.GetStringAsync(base.Http, "https://www.youtube.com/iframe_api", cancellationToken), "player\\\\?/([0-9a-fA-F]{8})\\\\?/").Groups[1].Value; if (string.IsNullOrWhiteSpace(value)) { throw new YoutubeExplodeException("Could not extract player version."); } return PlayerSource.Parse(await PolyfillExtensions.GetStringAsync(base.Http, "https://www.youtube.com/s/player/" + value + "/player_ias.vflset/en_US/base.js", cancellationToken)); } public async ValueTask<DashManifest> GetDashManifestAsync(string url, CancellationToken cancellationToken = default(CancellationToken)) { return DashManifest.Parse(await PolyfillExtensions.GetStringAsync(base.Http, url, cancellationToken)); } } public class StreamManifest { public IReadOnlyList<IStreamInfo> Streams { get; } public StreamManifest(IReadOnlyList<IStreamInfo> streams) { Streams = streams; } public IEnumerable<IAudioStreamInfo> GetAudioStreams() { return Streams.OfType<IAudioStreamInfo>(); } public IEnumerable<IVideoStreamInfo> GetVideoStreams() { return Streams.OfType<IVideoStreamInfo>(); } public IEnumerable<MuxedStreamInfo> GetMuxedStreams() { return Streams.OfType<MuxedStreamInfo>(); } public IEnumerable<AudioOnlyStreamInfo> GetAudioOnlyStreams() { return GetAudioStreams().OfType<AudioOnlyStreamInfo>(); } public IEnumerable<VideoOnlyStreamInfo> GetVideoOnlyStreams() { return GetVideoStreams().OfType<VideoOnlyStreamInfo>(); } } public class VideoOnlyStreamInfo : IVideoStreamInfo, IStreamInfo { public string Url { get; } public Container Container { get; } public FileSize Size { get; } public Bitrate Bitrate { get; } public string VideoCodec { get; } public VideoQuality VideoQuality { get; } public Resolution VideoResolution { get; } public VideoOnlyStreamInfo(string url, Container container, FileSize size, Bitrate bitrate, string videoCodec, VideoQuality videoQuality, Resolution videoResolution) { Url = url; Container = container; Size = size; Bitrate = bitrate; VideoCodec = videoCodec; VideoQuality = videoQuality; VideoResolution = videoResolution; } [ExcludeFromCodeCoverage] public override string ToString() { return $"Video-only ({VideoQuality} | {Container})"; } } public readonly struct VideoQuality : IComparable<VideoQuality>, IEquatable<VideoQuality> { public string Label { get; } public int MaxHeight { get; } public int Framerate { get; } public bool IsHighDefinition => MaxHeight >= 1080; public VideoQuality(string label, int maxHeight, int framerate) { Label = label; MaxHeight = maxHeight; Framerate = framerate; } public VideoQuality(int maxHeight, int framerate) : this(FormatLabel(maxHeight, framerate), maxHeight, framerate) { } internal Resolution GetDefaultVideoResolution() { return MaxHeight switch { 144 => new Resolution(256, 144), 240 => new Resolution(426, 240), 360 => new Resolution(640, 360), 480 => new Resolution(854, 480), 720 => new Resolution(1280, 720), 1080 => new Resolution(1920, 1080), 1440 => new Resolution(2560, 1440), 2160 => new Resolution(3840, 2160), 2880 => new Resolution(5120, 2880), 3072 => new Resolution(4096, 3072), 4320 => new Resolution(7680, 4320), _ => new Resolution(16 * MaxHeight / 9, MaxHeight), }; } public override string ToString() { return Label; } private static string FormatLabel(int maxHeight, int framerate) { if (framerate <= 30) { return $"{maxHeight}p"; } int num = (int)Math.Ceiling((double)framerate / 10.0) * 10; return $"{maxHeight}p{num}"; } internal static VideoQuality FromLabel(string label, int framerateFallback) { Match match = Regex.Match(label, "^(\\d+)\\D(\\d+)?"); int maxHeight = match.Groups[1].Value.ParseInt(); return new VideoQuality(label, maxHeight, match.Groups[2].Value.NullIfWhiteSpace()?.ParseIntOrNull() ?? framerateFallback); } internal static VideoQuality FromItag(int itag, int framerate) { return new VideoQuality(itag switch { 5 => 144, 6 => 240, 13 => 144, 17 => 144, 18 => 360, 22 => 720, 34 => 360, 35 => 480, 36 => 240, 37 => 1080, 38 => 3072, 43 => 360, 44 => 480, 45 => 720, 46 => 1080, 59 => 480, 78 => 480, 82 => 360, 83 => 480, 84 => 720, 85 => 1080, 91 => 144, 92 => 240, 93 => 360, 94 => 480, 95 => 720, 96 => 1080, 100 => 360, 101 => 480, 102 => 720, 132 => 240, 151 => 144, 133 => 240, 134 => 360, 135 => 480, 136 => 720, 137 => 1080, 138 => 4320, 142 => 240, 143 => 360, 144 => 480, 145 => 720, 146 => 1080, 160 => 144, 161 => 144, 167 => 360, 168 => 480, 169 => 720, 170 => 1080, 212 => 480, 213 => 480, 214 => 720, 215 => 720, 216 => 1080, 217 => 1080, 218 => 480, 219 => 480, 222 => 480, 223 => 480, 224 => 720, 225 => 720, 226 => 1080, 227 => 1080, 242 => 240, 243 => 360, 244 => 480, 245 => 480, 246 => 480, 247 => 720, 248 => 1080, 264 => 1440, 266 => 2160, 271 => 1440, 272 => 2160, 278 => 144, 298 => 720, 299 => 1080, 302 => 720, 303 => 1080, 308 => 1440, 313 => 2160, 315 => 2160, 330 => 144, 331 => 240, 332 => 360, 333 => 480, 334 => 720, 335 => 1080, 336 => 1440, 337 => 2160, 399 => 1080, 398 => 720, 397 => 480, 396 => 360, 395 => 240, 394 => 144, _ => throw new ArgumentException($"Unrecognized itag '{itag}'.", "itag"), }, framerate); } public int CompareTo(VideoQuality other) { int num = MaxHeight.CompareTo(other.MaxHeight); if (num != 0) { return num; } int num2 = Framerate.CompareTo(other.Framerate); if (num2 != 0) { return num2; } return StringComparer.OrdinalIgnoreCase.Compare(Label, other.Label); } public bool Equals(VideoQuality other) { if (StringComparer.OrdinalIgnoreCase.Equals(Label, other.Label) && MaxHeight == other.MaxHeight) { return Framerate == other.Framerate; } return false; } public override bool Equals(object? obj) { if (obj is VideoQuality other) { return Equals(other); } return false; } public override int GetHashCode() { return HashCode.Combine(StringComparer.OrdinalIgnoreCase.GetHashCode(Label), MaxHeight, Framerate); } public static bool operator ==(VideoQuality left, VideoQuality right) { return left.Equals(right); } public static bool operator !=(VideoQuality left, VideoQuality right) { return !(left == right); } public static bool operator >(VideoQuality left, VideoQuality right) { return left.CompareTo(right) > 0; } public static bool operator <(VideoQuality left, VideoQuality right) { return left.CompareTo(right) < 0; } } } namespace YoutubeExplode.Videos.ClosedCaptions { public class ClosedCaption { public string Text { get; } public TimeSpan Offset { get; } public TimeSpan Duration { get; } public IReadOnlyList<ClosedCaptionPart> Parts { get; } public ClosedCaption(string text, TimeSpan offset, TimeSpan duration, IReadOnlyList<ClosedCaptionPart> parts) { Text = text; Offset = offset; Duration = duration; Parts = parts; } public ClosedCaptionPart? TryGetPartByTime(TimeSpan time) { return Parts.FirstOrDefault((ClosedCaptionPart p) => p.Offset >= time); } public ClosedCaptionPart GetPartByTime(TimeSpan time) { return TryGetPartByTime(time) ?? throw new InvalidOperationException($"No closed caption part found at {time}."); } [ExcludeFromCodeCoverage] public override string ToString() { return Text; } } public class ClosedCaptionClient { private readonly ClosedCaptionController _controller; public ClosedCaptionClient(HttpClient http) { _controller = new ClosedCaptionController(http); } private async IAsyncEnumerable<ClosedCaptionTrackInfo> GetClosedCaptionTrackInfosAsync(VideoId videoId, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken)) { foreach (PlayerResponse.ClosedCaptionTrackData closedCaptionTrack in (await _controller.GetPlayerResponseAsync(videoId, null, cancellationToken)).ClosedCaptionTracks) { string url = closedCaptionTrack.Url ?? throw new YoutubeExplodeException("Could not extract track URL."); string code = closedCaptionTrack.LanguageCode ?? throw new YoutubeExplodeException("Could not extract track language code."); string name = closedCaptionTrack.LanguageName ?? throw new YoutubeExplodeException("Could not extract track language name."); yield return new ClosedCaptionTrackInfo(url, new Language(code, name), closedCaptionTrack.IsAutoGenerated); } } public async ValueTask<ClosedCaptionManifest> GetManifestAsync(VideoId videoId, CancellationToken cancellationToken = default(CancellationToken)) { return new ClosedCaptionManifest(await GetClosedCaptionTrackInfosAsync(videoId, cancellationToken)); } private async IAsyncEnumerable<ClosedCaption> GetClosedCaptionsAsync(ClosedCaptionTrackInfo trackInfo, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken)) { foreach (ClosedCaptionTrackResponse.CaptionData caption in (await _controller.GetClosedCaptionTrackResponseAsync(trackInfo.Url, cancellationToken)).Captions) { string text = caption.Text; if (string.IsNullOrEmpty(text)) { continue; } TimeSpan? offset = caption.Offset; if (!offset.HasValue) { continue; } TimeSpan valueOrDefault = offset.GetValueOrDefault(); offset = caption.Duration; if (!offset.HasValue) { continue; } TimeSpan valueOrDefault2 = offset.GetValueOrDefault(); List<ClosedCaptionPart> list = new List<ClosedCaptionPart>(); foreach (ClosedCaptionTrackResponse.PartData part in caption.Parts) { string text2 = part.Text; if (!string.IsNullOrEmpty(text2)) { TimeSpan offset2 = part.Offset ?? throw new YoutubeExplodeException("Could not extract caption part offset."); ClosedCaptionPart item = new ClosedCaptionPart(text2, offset2); list.Add(item); } } yield return new ClosedCaption(text, valueOrDefault, valueOrDefault2, list); } } public async ValueTask<ClosedCaptionTrack> GetAsync(ClosedCaptionTrackInfo trackInfo, CancellationToken cancellationToken = default(CancellationToken)) { return new ClosedCaptionTrack(await GetClosedCaptionsAsync(trackInfo, cancellationToken)); } public async ValueTask WriteToAsync(ClosedCaptionTrackInfo trackInfo, TextWriter writer, IProgress<double>? progress = null, CancellationToken cancellationToken = default(CancellationToken)) { ClosedCaptionTrack track = await GetAsync(trackInfo, cancellationToken); StringBuilder buffer = new StringBuilder(); foreach (var (closedCaption, i) in track.Captions.WithIndex()) { cancellationToken.ThrowIfCancellationRequested(); buffer.AppendLine((i + 1).ToString(CultureInfo.InvariantCulture)).Append(FormatTimestamp(closedCaption.Offset)).Append(" --> ") .Append(FormatTimestamp(closedCaption.Offset + closedCaption.Duration)) .AppendLine() .AppendLine(closedCaption.Text); await writer.WriteLineAsync(buffer.ToString()); buffer.Clear(); progress?.Report(((double)i + 1.0) / (double)track.Captions.Count); } static string FormatTimestamp(TimeSpan value) { return Math.Floor(value.TotalHours).ToString("00", CultureInfo.InvariantCulture) + ":" + value.Minutes.ToString("00", CultureInfo.InvariantCulture) + ":" + value.Seconds.ToString("00", CultureInfo.InvariantCulture) + "," + value.Milliseconds.ToString("000", CultureInfo.InvariantCulture); } } public async ValueTask DownloadAsync(ClosedCaptionTrackInfo trackInfo, string filePath, IProgress<double>? progress = null, CancellationToken cancellationToken = default(CancellationToken)) { using StreamWriter writer = File.CreateText(filePath); await WriteToAsync(trackInfo, writer, progress, cancellationToken); } } internal class ClosedCaptionController : VideoController { public ClosedCaptionController(HttpClient http) : base(http) { } public async ValueTask<ClosedCaptionTrackResponse> GetClosedCaptionTrackResponseAsync(string url, CancellationToken cancellationToken = default(CancellationToken)) { string requestUri = url.Pipe((string s) => UrlEx.SetQueryParameter(s, "format", "3")).Pipe((string s) => UrlEx.SetQueryParameter(s, "fmt", "3")); return ClosedCaptionTrackResponse.Parse(await PolyfillExtensions.GetStringAsync(base.Http, requestUri, cancellationToken)); } } public class ClosedCaptionManifest { public IReadOnlyList<ClosedCaptionTrackInfo> Tracks { get; } public ClosedCaptionManifest(IReadOnlyList<ClosedCaptionTrackInfo> tracks) { Tracks = tracks; } public ClosedCaptionTrackInfo? TryGetByLanguage(string language) { string language2 = language; return Tracks.FirstOrDefault((ClosedCaptionTrackInfo t) => string.Equals(t.Language.Code, language2, StringComparison.OrdinalIgnoreCase) || string.Equals(t.Language.Name, language2, StringComparison.OrdinalIgnoreCase)); } public ClosedCaptionTrackInfo GetByLanguage(string language) { return TryGetByLanguage(language) ?? throw new InvalidOperationException("No closed caption track available for language '" + language + "'."); } } public class ClosedCaptionPart { public string Text { get; } public TimeSpan Offset { get; } public ClosedCaptionPart(string text, TimeSpan offset) { Text = text; Offset = offset; } [ExcludeFromCodeCoverage] public override string ToString() { return Text; } } public class ClosedCaptionTrack { public IReadOnlyList<ClosedCaption> Captions { get; } public ClosedCaptionTrack(IReadOnlyList<ClosedCaption> captions) { Captions = captions; } public ClosedCaption? TryGetByTime(TimeSpan time) { return Captions.FirstOrDefault((ClosedCaption c) => time >= c.Offset && time <= c.Offset + c.Duration); } public ClosedCaption GetByTime(TimeSpan time) { return TryGetByTime(time) ?? throw new InvalidOperationException($"No closed caption found at {time}."); } } public class ClosedCaptionTrackInfo { public string Url { get; } public Language Language { get; } public bool IsAutoGenerated { get; } public ClosedCaptionTrackInfo(string url, Language language, bool isAutoGenerated) { Url = url; Language = language; IsAutoGenerated = isAutoGenerated; } [ExcludeFromCodeCoverage] public override string ToString() { return $"CC Track ({Language})"; } } public readonly struct Language : IEquatable<Language> { public string Code { get; } public string Name { get; } public Language(string code, string name) { Code = code; Name = name; } [ExcludeFromCodeCoverage] public override string ToString() { return Code + " (" + Name + ")"; } public bool Equals(Language other) { return StringComparer.OrdinalIgnoreCase.Equals(Code, other.Code); } public override bool Equals(object? obj) { if (obj is Language other) { return Equals(other); } return false; } public override int GetHashCode() { return StringComparer.OrdinalIgnoreCase.GetHashCode(Code); } public static bool operator ==(Language left, Language right) { return left.Equals(right); } public static bool operator !=(Language left, Language right) { return !(left == right); } } } namespace YoutubeExplode.Utils { internal abstract class ClientDelegatingHandler : HttpMessageHandler { private readonly HttpClient _http; private readonly bool _disposeClient; protected ClientDelegatingHandler(HttpClient http, bool disposeClient = false) { _http = http; _disposeClient = disposeClient; } protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { using HttpRequestMessage clonedRequest = request.Clone(); return await _http.SendAsync(clonedRequest, HttpCompletionOption.ResponseHeadersRead, cancellationToken); } protected override void Dispose(bool disposing) { if (disposing && _disposeClient) { _http.Dispose(); } base.Dispose(disposing); } } internal static class Hash { public static byte[] Compute(HashAlgorithm algorithm, byte[] data) { using (algorithm) { return algorithm.ComputeHash(data); } } } internal static class Html { private static readonly HtmlParser HtmlParser = new HtmlParser(); public static IHtmlDocument Parse(string source) { return HtmlParser.ParseDocument(source); } } internal static class Http { private static readonly Lazy<HttpClient> HttpClientLazy = new Lazy<HttpClient>(() => new HttpClient()); public static HttpClient Client => HttpClientLazy.Value; } internal static class Json { public static string Extract(string source) { StringBuilder stringBuilder = new StringBuilder(); int num = 0; bool flag = false; foreach (var item3 in source.WithIndex()) { char item = item3.value; int item2 = item3.index; char c = ((item2 > 0) ? source[item2 - 1] : '\0'); stringBuilder.Append(item); if (item == '"' && c != '\\') { flag = !flag; } else if (item == '{' && !flag) { num++; } else if (item == '}' && !flag) { num--; } if (num == 0) { break; } } return stringBuilder.ToString(); } public static JsonElement Parse(string source) { using JsonDocument jsonDocument = JsonDocument.Parse(source); return jsonDocument.RootElement.Clone(); } public static JsonElement? TryParse(string source) { try { return Parse(source); } catch (JsonException) { return null; } } } internal static class UrlEx { private static IEnumerable<KeyValuePair<string, string>> EnumerateQueryParameters(string url) { string text = (url.Contains('?') ? url.SubstringAfter("?") : url); string[] array = text.Split('&'); foreach (string str in array) { string text2 = WebUtility.UrlDecode(str.SubstringUntil("=")); string value = WebUtility.UrlDecode(str.SubstringAfter("=")); if (!string.IsNullOrWhiteSpace(text2)) { yield return new KeyValuePair<string, string>(text2, value); } } } public static IReadOnlyDictionary<string, string> GetQueryParameters(string url) { return EnumerateQueryParameters(url).ToDictionary<KeyValuePair<string, string>, string, string>((KeyValuePair<string, string> kvp) => kvp.Key, (KeyValuePair<string, string> kvp) => kvp.Value); } private static KeyValuePair<string, string>? TryGetQueryParameter(string url, string key) { foreach (KeyValuePair<string, string> item in EnumerateQueryParameters(url)) { if (string.Equals(item.Key, key, StringComparison.Ordinal)) { return item; } } return null; } public static string? TryGetQueryParameterValue(string url, string key) { return TryGetQueryParameter(url, key)?.Value; } public static bool ContainsQueryParameter(string url, string key) { return TryGetQueryParameterValue(url, key) != null; } public static string RemoveQueryParameter(string url, string key) { if (!ContainsQueryParameter(url, key)) { return url; } UriBuilder uriBuilder = new UriBuilder(url); StringBuilder stringBuilder = new StringBuilder(); foreach (KeyValuePair<string, string> item in EnumerateQueryParameters(url)) { if (!string.Equals(item.Key, key, StringComparison.Ordinal)) { stringBuilder.Append((stringBuilder.Length > 0) ? '&' : '?'); stringBuilder.Append(WebUtility.UrlEncode(item.Key)); stringBuilder.Append('='); stringBuilder.Append(WebUtility.UrlEncode(item.Value)); } } uriBuilder.Query = stringBuilder.ToString(); return uriBuilder.ToString(); } public static string SetQueryParameter(string url, string key, string value) { string text = RemoveQueryParameter(url, key); bool flag = text.Contains('?'); return text + (flag ? '&' : '?') + WebUtility.UrlEncode(key) + "=" + WebUtility.UrlEncode(value); } } internal static class Xml { public static XElement Parse(string source) { return XElement.Parse(source, LoadOptions.PreserveWhitespace).StripNamespaces(); } } } namespace YoutubeExplode.Utils.Extensions { internal static class AsyncCollectionExtensions { public static async IAsyncEnumerable<T> TakeAsync<T>(this IAsyncEnumerable<T> source, int count) { int currentCount = 0; await foreach (T item in source) { if (currentCount >= count) { break; } yield return item; currentCount++; } } public static async IAsyncEnumerable<T> SelectManyAsync<TSource, T>(this IAsyncEnumerable<TSource> source, Func<TSource, IEnumerable<T>> transform) { await foreach (TSource item in source) { foreach (T item2 in transform(item)) { yield return item2; } } } public static async IAsyncEnumerable<T> OfTypeAsync<T>(this IAsyncEnumerable<object> source) { await foreach (object item in source) { if (item is T) { yield return (T)item; } } } public static async ValueTask<List<T>> ToListAsync<T>(this IAsyncEnumerable<T> source) { List<T> list = new List<T>(); await foreach (T item in source) { list.Add(item); } return list; } public static ValueTaskAwaiter<List<T>> GetAwaiter<T>(this IAsyncEnumerable<T> source) { return source.ToListAsync().GetAwaiter(); } } internal static class BinaryExtensions { public static string ToHex(this byte[] data, bool isUpperCase = true) { StringBuilder stringBuilder = new StringBuilder(2 * data.Length); foreach (byte b in data) { stringBuilder.Append(b.ToString(isUpperCase ? "X2" : "x2", CultureInfo.InvariantCulture)); } return stringBuilder.ToString(); } } internal static class CollectionExtensions { public static IEnumerable<(T value, int index)> WithIndex<T>(this IEnumerable<T> source) { int i = 0; foreach (T item in source) { yield return (item, i++); } } public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T?> source) where T : class { foreach (T item in source) { if (item != null) { yield return item; } } } public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T?> source) where T : struct { foreach (T? item in source) { if (item.HasValue) { yield return item.Value; } } } public static T? ElementAtOrNull<T>(this IEnumerable<T> source, int index) where T : struct { IReadOnlyList<T> readOnlyList = (source as IReadOnlyList<T>) ?? source.ToArray(); if (index >= readOnlyList.Count) { return null; } return readOnlyList[index]; } public static T? FirstOrNull<T>(this IEnumerable<T> source) where T : struct { using (IEnumerator<T> enumerator = source.GetEnumerator()) { if (enumerator.MoveNext()) { return enumerator.Current; } } return null; } } internal static class GenericExtensions { public static TOut Pipe<TIn, TOut>(this TIn input, Func<TIn, TOut> transform) { return transform(input); } } internal static class HttpExtensions { private class NonDisposableHttpContent : HttpContent { private readonly HttpContent _content; public NonDisposableHttpContent(HttpContent content) { _content = content; } protected override async Task SerializeToStreamAsync(Stream stream, TransportContext? context) { await _content.CopyToAsync(stream); } protected override bool TryComputeLength(out long length) { length = 0L; return false; } } public static HttpRequestMessage Clone(this HttpRequestMessage request) { HttpRequestMessage httpRequestMessage = new HttpRequestMessage(request.Method, request.RequestUri) { Version = request.Version, Content = ((request.Content != null) ? new NonDisposableHttpContent(request.Content) : null) }; string key; IEnumerable<string> value; foreach (KeyValuePair<string, IEnumerable<string>> header in request.Headers) { header.Deconstruct(out key, out value); string name = key; IEnumerable<string> values = value; httpRequestMessage.Headers.TryAddWithoutValidation(name, values); } if (request.Content != null && httpRequestMessage.Content != null) { foreach (KeyValuePair<string, IEnumerable<string>> header2 in request.Content.Headers) { header2.Deconstruct(out key, out value); string name2 = key; IEnumerable<string> values2 = value; httpRequestMessage.Content.Headers.TryAddWithoutValidation(name2, values2); } } return httpRequestMessage; } public static async ValueTask<HttpResponseMessage> HeadAsync(this HttpClient http, string requestUri, CancellationToken cancellationToken = default(CancellationToken)) { using HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Head, requestUri); return await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken); } public static async ValueTask<long?> TryGetContentLengthAsync(this HttpClient http, string requestUri, bool ensureSuccess = true, CancellationToken cancellationToken = default(CancellationToken)) { using HttpResponseMessage httpResponseMessage = await http.HeadAsync(requestUri, cancellationToken); if (ensureSuccess) { httpResponseMessage.EnsureSuccessStatusCode(); } return httpResponseMessage.Content.Headers.ContentLength; } } internal static class JsonExtensions { public static JsonElement? GetPropertyOrNull(this JsonElement element, string propertyName) { if (element.ValueKind != JsonValueKind.Object) { return null; } if (element.TryGetProperty(propertyName, out var value) && value.ValueKind != JsonValueKind.Null && value.ValueKind != 0) { return value; } return null; } public static string? GetStringOrNull(this JsonElement element) { if (element.ValueKind != JsonValueKind.String) { return null; } return element.GetString(); } public static int? GetInt32OrNull(this JsonElement element) { if (element.ValueKind != JsonValueKind.Number || !element.TryGetInt32(out var value)) { return null; } return value; } public static long? GetInt64OrNull(this JsonElement element) { if (element.ValueKind != JsonValueKind.Number || !element.TryGetInt64(out var value)) { return null; } return value; } public static JsonElement.ArrayEnumerator? EnumerateArrayOrNull(this JsonElement element) { if (element.ValueKind != JsonValueKind.Array) { return null; } return element.EnumerateArray(); } public static JsonElement.ArrayEnumerator EnumerateArrayOrEmpty(this JsonElement element) { return element.EnumerateArrayOrNull().GetValueOrDefault(); } public static JsonElement.ObjectEnumerator? EnumerateObjectOrNull(this JsonElement element) { if (element.ValueKind != JsonValueKind.Object) { return null; } return element.EnumerateObject(); } public static JsonElement.ObjectEnumerator EnumerateObjectOrEmpty(this JsonElement element) { return element.EnumerateObjectOrNull().GetValueOrDefault(); } public static IEnumerable<JsonElement> EnumerateDescendantProperties(this JsonElement element, string propertyName) { string propertyName2 = propertyName; JsonElement? propertyOrNull = element.GetPropertyOrNull(propertyName2); if (propertyOrNull.HasValue) { yield return propertyOrNull.Value; } IEnumerable<JsonElement> enumerable = element.EnumerateArrayOrEmpty().SelectMany((JsonElement j) => j.EnumerateDescendantProperties(propertyName2)); foreach (JsonElement item in enumerable) { yield return item; } IEnumerable<JsonElement> enumerable2 = element.EnumerateObjectOrEmpty().SelectMany((JsonProperty j) => j.Value.EnumerateDescendantProperties(propertyName2)); foreach (JsonElement item2 in enumerable2) { yield return item2; } } } internal static class StreamExtensions { public static async ValueTask CopyToAsync(this Stream source, Stream destination, IProgress<double>? progress = null, CancellationToken cancellationToken = default(CancellationToken)) { using IMemoryOwner<byte> buffer = MemoryPool<byte>.Shared.Rent(81920); long totalBytesRead = 0L; while (true) { int bytesRead = await source.ReadAsync(buffer.Memory, cancellationToken); if (bytesRead <= 0) { break; } await destination.WriteAsync(buffer.Memory.Slice(0, bytesRead), cancellationToken); totalBytesRead += bytesRead; progress?.Report(1.0 * (double)totalBytesRead / (double)source.Length); } } } internal static class StringExtensions { public static string? NullIfWhiteSpace(this string str) { if (string.IsNullOrWhiteSpace(str)) { return null; } return str; } public static string SubstringUntil(this string str, string sub, StringComparison comparison = StringComparison.Ordinal) { int num = str.IndexOf(sub, comparison); if (num >= 0) { return str.Substring(0, num); } return str; } public static string SubstringAfter(this string str, string sub, StringComparison comparison = StringComparison.Ordinal) { int num = str.IndexOf(sub, comparison); if (num >= 0) { return str.Substring(num + sub.Length, str.Length - num - sub.Length); } return string.Empty; } public static string StripNonDigit(this string str) { StringBuilder stringBuilder = new StringBuilder(); foreach (char item in str.Where(char.IsDigit)) { stringBuilder.Append(item); } return stringBuilder.ToString(); } public static string Reverse(this string str) { StringBuilder stringBuilder = new StringBuilder(str.Length); for (int num = str.Length - 1; num >= 0; num--) { stringBuilder.Append(str[num]); } return stringBuilder.ToString(); } public static string SwapChars(this string str, int firstCharIndex, int secondCharIndex) { return new StringBuilder(str) { [firstCharIndex] = str[secondCharIndex], [secondCharIndex] = str[firstCharIndex] }.ToString(); } public static int? ParseIntOrNull(this string str) { if (!int.TryParse(str, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out var result)) { return null; } return result; } public static int ParseInt(this string str) { return str.ParseIntOrNull() ?? throw new FormatException("Cannot parse integer number from string '" + str + "'."); } public static long? ParseLongOrNull(this string str) { if (!long.TryParse(str, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out var result)) { return null; } return result; } public static double? ParseDoubleOrNull(this string str) { if (!double.TryParse(str, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.InvariantInfo, out var result)) { return null; } return result; } public static TimeSpan? ParseTimeSpanOrNull(this string str, string[] formats) { if (!TimeSpan.TryParseExact(str, formats, DateTimeFormatInfo.InvariantInfo, out var result)) { return null; } return result; } public static DateTimeOffset? ParseDateTimeOffsetOrNull(this string str) { if (!DateTimeOffset.TryParse(str, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out var result)) { return null; } return result; } public static string ConcatToString<T>(this IEnumerable<T> source) { return string.Concat(source); } } internal static class UriExtensions { public static string GetDomain(this Uri uri) { return uri.Scheme + Uri.SchemeDelimiter + uri.Host; } } internal static class XElementExtensions { public static XElement StripNamespaces(this XElement element) { XElement xElement = new XElement(element); foreach (XElement item in xElement.DescendantsAndSelf()) { item.Name = XNamespace.None.GetName(item.Name.LocalName); item.ReplaceAttributes(from a in item.Attributes() where !a.IsNamespaceDeclaration where a.Name.Namespace != XNamespace.Xml && a.Name.Namespace != XNamespace.Xmlns select new XAttribute(XNamespace.None.GetName(a.Name.LocalName), a.Value)); } return xElement; } } } namespace YoutubeExplode.Search { public class ChannelSearchResult : ISearchResult, IBatchItem, IChannel { public ChannelId Id { get; } public string Url => $"https://www.youtube.com/channel/{Id}"; public string Title { get; } public IReadOnlyList<Thumbnail> Thumbnails { get; } public ChannelSearchResult(ChannelId id, string title, IReadOnlyList<Thumbnail> thumbnails) { Id = id; Title = title; Thumbnails = thumbnails; } [ExcludeFromCodeCoverage] public override string ToString() { return "Channel (" + Title + ")"; } } public interface ISearchResult : IBatchItem { string Url { get; } string Title { get; } } public class PlaylistSearchResult : ISearchResult, IBatchItem, IPlaylist { public PlaylistId Id { get; } public string Url => $"https://www.youtube.com/playlist?list={Id}"; public string Title { get; } public Author? Author { get; } public IReadOnlyList<Thumbnail> Thumbnails { get; } public PlaylistSearchResult(PlaylistId id, string title, Author? author, IReadOnlyList<Thumbnail> thumbnails) { Id = id; Title = title; Author = author; Thumbnails = thumbnails; } [ExcludeFromCodeCoverage] public override string ToString() { return "Playlist (" + Title + ")"; } } public class SearchClient { private readonly SearchController _controller; public SearchClient(HttpClient http) { _controller = new SearchController(http); } public async IAsyncEnumerable<Batch<ISearchResult>> GetResultBatchesAsync(string searchQuery, SearchFilter searchFilter, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken)) { int num = -1; HashSet<string> encounteredIds = new HashSet<string>(StringComparer.Ordinal); string text = null; do { List<ISearchResult> results = new List<ISearchResult>(); SearchResponse searchResults = await _controller.GetSearchResponseAsync(searchQuery, searchFilter, text, cancellationToken); IEnumerator<SearchResponse.VideoData> enumerator = searchResults.Videos.GetEnumerator(); try { while (enumerator.MoveNext()) { SearchResponse.VideoData current = enumerator.Current; if (searchFilter != 0 && searchFilter != SearchFilter.Video) { break; } string text2 = current.Id ?? throw new YoutubeExplodeException("Could not extract video ID."); if (encounteredIds.Add(text2)) { string title = current.Title ?? throw new YoutubeExplodeException("Could not extract video title."); string channelTitle = current.Author ?? throw new YoutubeExplodeException("Could not extract video author."); string text3 = current.ChannelId ?? throw new YoutubeExplodeException("Could not extract video channel ID."); Thumbnail[] thumbnails = current.Thumbnails.Select(delegate(ThumbnailData t) { string? url3 = t.Url ?? throw new YoutubeExplodeException("Could not extract video thumbnail URL."); int width3 = t.Width ?? throw new YoutubeExplodeException("Could not extract video thumbnail width."); int height3 = t.Height ?? throw new YoutubeExplodeException("Could not extract video thumbnail height."); Resolution resolution3 = new Resolution(width3, height3); return new Thumbnail(url3, resolution3); }).Concat(Thumbnail.GetDefaultSet(text2)).ToArray(); VideoSearchResult item = new VideoSearchResult(text2, title, new Author(text3, channelTitle), current.Duration, thumbnails); results.Add(item); } } } finally { if (num == -1) { enumerator?.Dispose(); } } IEnumerator<SearchResponse.PlaylistData> enumerator2 = searchResults.Playlists.GetEnumerator(); try { while (enumerator2.MoveNext()) { SearchResponse.PlaylistData current2 = enumerator2.Current; if (searchFilter != 0 && searchFilter != SearchFilter.Playlist) { break; } string text4 = current2.Id ?? throw new YoutubeExplodeException("Could not extract playlist ID."); if (encounteredIds.Add(text4)) { string title2 = current2.Title ?? throw new YoutubeExplodeException("Could not extract playlist title."); Author author = ((!string.IsNullOrWhiteSpace(current2.ChannelId) && !string.IsNullOrWhiteSpace(current2.Author)) ? new Author(current2.ChannelId, current2.Author) : null); Thumbnail[] thumbnails2 = current2.Thumbnails.Select(delegate(ThumbnailData t) { string? url2 = t.Url ?? throw new YoutubeExplodeException("Could not extract playlist thumbnail URL."); int width2 = t.Width ?? throw new YoutubeExplodeException("Could not extract playlist thumbnail width."); int height2 = t.Height ?? throw new YoutubeExplodeException("Could not extract playlist thumbnail height."); Resolution resolution2 = new Resolution(width2, height2); return new Thumbnail(url2, resolution2); }).ToArray(); PlaylistSearchResult item2 = new PlaylistSearchResult(text4, title2, author, thumbnails2); results.Add(item2); } } } finally { if (num == -1) { enumerator2?.Dispose(); } } IEnumerator<SearchResponse.ChannelData> enumerator3 = searchResults.Channels.GetEnumerator(); try { while (enumerator3.MoveNext()) { SearchResponse.ChannelData current3 = enumerator3.Current; if (searchFilter == SearchFilter.None || searchFilter == SearchFilter.Channel) { string text5 = current3.Id ?? throw new YoutubeExplodeException("Could not extract channel ID."); string title3 = current3.Title ?? throw new YoutubeExplodeException("Could not extract channel title."); Thumbnail[] thumbnails3 = current3.Thumbnails.Select(delegate(ThumbnailData t) { string? url = t.Url ?? throw new YoutubeExplodeException("Could not extract channel thumbnail URL."); int width = t.Width ?? throw new YoutubeExplodeException("Could not extract channel thumbnail width."); int height = t.Height ?? throw new YoutubeExplodeException("Could not extract channel thumbnail height."); Resolution resolution = new Resolution(width, height); return new Thumbnail(url, resolution); }).ToArray(); ChannelSearchResult item3 = new ChannelSearchResult(text5, title3, thumbnails3); results.Add(item3); continue; } break; } } finally { if (num == -1) { enumerator3?.Dispose(); } } yield return Batch.Create(results); num = -1; text = searchResults.ContinuationToken; } while (!string.IsNullOrWhiteSpace(text)); } public IAsyncEnumerable<Batch<ISearchResult>> GetResultBatchesAsync(string searchQuery, CancellationToken cancellationToken = default(CancellationToken)) { return GetResultBatchesAsync(searchQuery, SearchFilter.None, cancellationToken); } public IAsyncEnumerable<ISearchResult> GetResultsAsync(string searchQuery, CancellationToken cancellationToken = default(CancellationToken)) { return GetResultBatchesAsync(searchQuery, cancellationToken).FlattenAsync(); } public IAsyncEnumerable<VideoSearchResult> GetVideosAsync(string searchQuery, CancellationToken cancellationToken = default(CancellationToken)) { return GetResultBatchesAsync(searchQuery, SearchFilter.Video, cancellationToken).FlattenAsync().OfTypeAsync<VideoSearchResult>(); } public IAsyncEnumerable<PlaylistSearchResult> GetPlaylistsAsync(string searchQuery, CancellationToken cancellationToken = default(CancellationToken)) { return GetResultBatchesAsync(searchQuery, SearchFilter.Playlist, cancellationToken).FlattenAsync().OfTypeAsync<PlaylistSearchResult>(); } public IAsyncEnumerable<ChannelSearchResult> GetChannelsAsync(string searchQuery, CancellationToken cancellationToken = default(CancellationToken)) { return GetResultBatchesAsync(searchQuery, SearchFilter.Channel, cancellationToken).FlattenAsync().OfTypeAsync<ChannelSearchResult>(); } } internal class SearchController { private readonly HttpClient _http; public SearchController(HttpClient http) { _http = http; } public async ValueTask<SearchResponse> GetSearchResponseAsync(string searchQuery, SearchFilter searchFilter, string? continuationToken, CancellationToken cancellationToken = default(CancellationToken)) { HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "https://www.youtube.com/youtubei/v1/search"); HttpRequestMessage httpRequestMessage2 = httpRequestMessage; string text = searchFilter switch { SearchFilter.Video => "EgIQAQ%3D%3D", SearchFilter.Playlist => "EgIQAw%3D%3D", SearchFilter.Channel => "EgIQAg%3D%3D", _ => null, }; httpRequestMessage2.Content = new StringContent("{\r\n \"query\": \"" + searchQuery + "\",\r\n \"params\": \"" + text + "\",\r\n \"continuation\": \"" + continuationToken + "\",\r\n \"context\": {\r\n \"client\": {\r\n \"clientName\": \"WEB\",\r\n \"clientVersion\": \"2.20210408.08.00\",\r\n \"hl\": \"en\",\r\n \"gl\": \"US\",\r\n \"utcOffsetMinutes\": 0\r\n }\r\n }\r\n}"); using HttpRequestMessage request = httpRequestMessage; using HttpResponseMessage response = await _http.SendAsync(request, cancellationToken); response.EnsureSuccessStatusCode(); return SearchResponse.Parse(await PolyfillExtensions.ReadAsStringAsync(response.Content, cancellationToken)); } } public enum SearchFilter { None, Video, Playlist, Channel } public class VideoSearchResult : ISearchResult, IBatchItem, IVideo { public VideoId Id { get; } public string Url => $"https://www.youtube.com/watch?v={Id}"; public string Title { get; } public Author Author { get; } public TimeSpan? Duration { get; } public IReadOnlyList<Thumbnail> Thumbnails { get; } public VideoSearchResult(VideoId id, string title, Author author, TimeSpan? duration, IReadOnlyList<Thumbnail> thumbnails) { Id = id; Title = title; Author = author; Duration = duration; Thumbnails = thumbnails; } [ExcludeFromCodeCoverage] public override string ToString() { return "Video (" + Title + ")"; } } } namespace YoutubeExplode.Playlists { public interface IPlaylist { PlaylistId Id { get; } string Url { get; } string Title { get; } Author? Author { get; } IReadOnlyList<Thumbnail> Thumbnails { get; } } public class Playlist : IPlaylist { public PlaylistId Id { get; } public string Url => $"https://www.youtube.com/playlist?list={Id}"; public string Title { get; } public Author? Author { get; } public string Description { get; } public IReadOnlyList<Thumbnail> Thumbnails { get; } public Playlist(PlaylistId id, string title, Author? author, string description, IReadOnlyList<Thumbnail> thumbnails) { Id = id; Title = title; Author = author; Description = description; Thumbnails = thumbnails; } [ExcludeFromCodeCoverage] public override string ToString() { return "Playlist (" + Title + ")"; } } public class PlaylistClient { private readonly PlaylistController _controller; public PlaylistClient(HttpClient http) { _controller = new PlaylistController(http); } public async ValueTask<Playlist> GetAsync(PlaylistId playlistId, CancellationToken cancellationToken = default(CancellationToken)) { IPlaylistData obj = await _controller.GetPlaylistResponseAsync(playlistId, cancellationToken); string title = obj.Title ?? throw new YoutubeExplodeException("Could not extract playlist title."); string channelId = obj.ChannelId; string author = obj.Author; Author author2 = ((channelId != null && author != null) ? new Author(channelId, author) : null); string description = obj.Description ?? ""; Thumbnail[] thumbnails = obj.Thumbnails.Select(delegate(ThumbnailData t) { string? url = t.Url ?? throw new YoutubeExplodeException("Could not extract thumbnail URL."); int width = t.Width ?? throw new YoutubeExplodeException("Could not extract thumbnail width."); int height = t.Height ?? throw new YoutubeExplodeException("Could not extract thumbnail height."); Resolution resolution = new Resolution(width, height); return new Thumbnail(url, resolution); }).ToArray(); return new Playlist(playlistId, title, author2, description, thumbnails); } public async IAsyncEnumerable<Batch<PlaylistVideo>> GetVideoBatchesAsync(PlaylistId playlistId, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken)) { int num = -1; HashSet<VideoId> encounteredIds = new HashSet<VideoId>(); VideoId? lastVideoId = null; int lastVideoIndex = 0; string visitorData = null; while (true) { PlaylistNextResponse response = await _controller.GetPlaylistNextResponseAsync(playlistId, lastVideoId, lastVideoIndex, visitorData, cancellationToken); List<PlaylistVideo> list = new List<PlaylistVideo>(); IEnumerator<PlaylistVideoData> enumerator = response.Videos.GetEnumerator(); try { while (enumerator.MoveNext()) { PlaylistVideoData current = enumerator.Current; string text = current.Id ?? throw new YoutubeExplodeException("Could not extract video ID."); lastVideoId = text; lastVideoIndex = current.Index ?? throw new YoutubeExplodeException("Could not extract video index."); if (encounteredIds.Add(text)) { string title = current.Title ?? ""; string channelTitle = current.Author ?? throw new YoutubeExplodeException("Could not extract video author."); string text2 = current.ChannelId ?? throw new YoutubeExplodeException("Could not extract video channel ID."); Thumbnail[] thumbnails = current.Thumbnails.Select(delegate(ThumbnailData t) { string? url = t.Url ?? throw new YoutubeExplodeException("Could not extract thumbnail URL."); int width = t.Width ?? throw new YoutubeExplodeException("Could not extract thumbnail width."); int height = t.Height ?? throw new YoutubeExplodeException("Could not extract thumbnail height."); Resolution resolution = new Resolution(width, height); return new Thumbnail(url, resolution); }).Concat(Thumbnail.GetDefaultSet(text)).ToArray(); PlaylistVideo item = new PlaylistVideo(playlistId, text, title, new Author(text2, channelTitle), current.Duration, thumbnails); list.Add(item); } } } finally { if (num == -1) { enumerator?.Dispose(); } } if (!list.Any()) { break; } yield return Batch.Create(list); num = -1; if (visitorData == null) { visitorData = response.VisitorData; } } } public IAsyncEnumerable<PlaylistVideo> GetVideosAsync(PlaylistId playlistId, CancellationToken cancellationToken = default(CancellationToken)) { return GetVideoBatchesAsync(playlistId, cancellationToken).FlattenAsync(); } } internal class PlaylistController { private readonly HttpClient _http; public PlaylistController(HttpClient http) { _http = http; } public async ValueTask<PlaylistBrowseResponse> GetPlaylistBrowseResponseAsync(PlaylistId playlistId, CancellationToken cancellationToken = default(CancellationToken)) { using HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://www.youtube.com/youtubei/v1/browse") { Content = new StringContent($"{{\r\n \"browseId\": \"VL{playlistId}\",\r\n \"context\": {{\r\n \"client\": {{\r\n \"clientName\": \"WEB\",\r\n \"clientVersion\": \"2.20210408.08.00\",\r\n \"hl\": \"en\",\r\n \"gl\": \"US\",\r\n \"utcOffsetMinutes\": 0\r\n }}\r\n }}\r\n}}") }; using HttpResponseMessage response = await _http.SendAsync(request, cancellationToken); response.EnsureSuccessStatusCode(); PlaylistBrowseResponse playlistBrowseResponse = PlaylistBrowseResponse.Parse(await PolyfillExtensions.ReadAsStringAsync(response.Content, cancellationToken)); if (!playlistBrowseResponse.IsAvailable) { throw new PlaylistUnavailableException($"Playlist '{playlistId}' is not available."); } return playlistBrowseResponse; } public async ValueTask<PlaylistNextResponse> GetPlaylistNextResponseAsync(PlaylistId playlistId, VideoId? videoId = null, int index = 0, string? visitorData = null, CancellationToken cancellationToken = default(CancellationToken)) { int retriesRemaining = 5; while (true) { using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://www.youtube.com/youtubei/v1/next") { Content = new StringContent($"{{\r\n \"playlistId\": \"{playlistId}\",\r\n \"videoId\": \"{videoId}\",\r\n \"playlistIndex\": {index},\r\n \"context\": {{\r\n \"client\": {{\r\n \"clientName\": \"WEB\",\r\n \"clientVersion\": \"2.20210408.08.00\",\r\n \"hl\": \"en\",\r\n \"gl\": \"US\",\r\n \"utcOffsetMinutes\": 0,\r\n \"visitorData\": \"{visitorData}\"\r\n }}\r\n }}\r\n}}") }) { using HttpResponseMessage response = await _http.SendAsync(request, cancellationToken); response.EnsureSuccessStatusCode(); PlaylistNextResponse playlistNextResponse = PlaylistNextResponse.Parse(await PolyfillExtensions.ReadAsStringAsync(response.Content, cancellationToken)); if (playlistNextResponse.IsAvailable) { return playlistNextResponse; } if (index <= 0 || string.IsNullOrWhiteSpace(visitorData) || retriesRemaining <= 0) { throw new PlaylistUnavailableException($"Playlist '{playlistId}' is not available."); } } retriesRemaining--; } } public async ValueTask<IPlaylistData> GetPlaylistResponseAsync(PlaylistId playlistId, CancellationToken cancellationToken = default(CancellationToken)) { IPlaylistData result = default(IPlaylistData); int num; try { result = await GetPlaylistBrowseResponseAsync(playlistId, cancellationToken); return result; } catch (PlaylistUnavailableException) { num = 1; } if (num != 1) { return result; } return await GetPlaylistNextResponseAsync(playlistId, null, 0, null, cancellationToken); } } public readonly struct PlaylistId : IEquatable<PlaylistId> { public string Value { get; } private PlaylistId(string value) { Value = value; } public override string ToString() { return Value; } private static bool IsValid(string playlistId) { if (playlistId.Length >= 2) { return playlistId.All(delegate(char c) { bool flag = char.IsLetterOrDigit(c); if (!flag) { bool flag2 = ((c == '-' || c == '_') ? true : false); flag = flag2; } return flag; }); } return false; } private static string? TryNormalize(string? playlistIdOrUrl) { if (string.IsNullOrWhiteSpace(playlistIdOrUrl)) { return null; } if (IsValid(playlistIdOrUrl)) { return playlistIdOrUrl; } string text = Regex.Match(playlistIdOrUrl, "youtube\\..+?/playlist.*?list=(.*?)(?:&|/|$)").Groups[1].Value.Pipe(WebUtility.UrlDecode); if (!string.IsNullOrWhiteSpace(text) && IsValid(text)) { return text; } string text2 = Regex.Match(playlistIdOrUrl, "youtube\\..+?/watch.*?list=(.*?)(?:&|/|$)").Groups[1].Value.Pipe(WebUtility.UrlDecode); if (!string.IsNullOrWhiteSpace(text2) && IsValid(text2)) { return text2; } string text3 = Regex.Match(playlistIdOrUrl, "youtu\\.be/.*?/.*?list=(.*?)(?:&|/|$)").Groups[1].Value.Pipe(WebUtility.UrlDecode); if (!string.IsNullOrWhiteSpace(text3) && IsValid(text3)) { return text3; } string text4 = Regex.Match(playlistIdOrUrl, "youtube\\..+?/embed/.*?/.*?list=(.*?)(?:&|/|$)").Groups[1].Value.Pipe(WebUtility.UrlDecode); if (!string.IsNullOrWhiteSpace(text4) && IsValid(text4)) { return text4; } return null; } public static PlaylistId? TryParse(string? playlistIdOrUrl) { return TryNormalize(playlistIdOrUrl)?.Pipe((string id) => ne