commit 4f440ca0281b992d140decbe1264fce76a403046 Author: Avril Date: Thu Apr 23 18:45:08 2020 +0100 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..83ba081 --- /dev/null +++ b/.gitignore @@ -0,0 +1,360 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*[.json, .xml, .info] + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd diff --git a/exasynctools/Class1.cs b/exasynctools/Class1.cs new file mode 100644 index 0000000..94b0412 --- /dev/null +++ b/exasynctools/Class1.cs @@ -0,0 +1,200 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using System.Linq; +using System.Collections.Generic; + +namespace Tools +{ + public sealed class AsyncMutex : IDisposable + { + private readonly SemaphoreSlim sem; + + public AsyncMutex() + { + sem = new SemaphoreSlim(1, 1); + } + private AsyncMutex(SemaphoreSlim from) + { + sem = from; + } + + private class Lock : IDisposable + { + public AsyncMutex Parent { get; } + public Lock(AsyncMutex held) + { + Parent = held; + } + + public void Dispose() + { + Parent.sem.Release(); + } + } + + public IDisposable Acquire(int msTimeout, CancellationToken token = default) + { + sem.Wait(msTimeout, token); + return new Lock(this); + } + + public IDisposable Acquire(CancellationToken token) + { + sem.Wait(token); + return new Lock(this); + } + + public IDisposable Acquire() + { + sem.Wait(); + return new Lock(this); + } + + public async Task AcquireAsync(int msTimeout, CancellationToken token = default) + { + await sem.WaitAsync(msTimeout, token); + return new Lock(this); + } + + public async Task AcquireAsync(CancellationToken token = default) + { + await sem.WaitAsync(token); + return new Lock(this); + } + + public void Dispose() + { + sem.Dispose(); + } + + public static AsyncMutex Semaphore(int count, int max) + { + SemaphoreSlim sem = new SemaphoreSlim(count, max); + return new AsyncMutex(sem); + } + public static AsyncMutex Semaphore(int count) + => Semaphore(count, count); + } + + public static class ExAsyncTools + { + #region Then() + public static async Task Then(this Task t, Action lam) + { + await t; + lam(); + } + public static Task Then(this Task t, Action lam, CancellationToken token) + => Then(t, (_) => lam(), token); + public static async Task Then(this Task t, Action lam, CancellationToken token) + { + TaskCompletionSource fail = new TaskCompletionSource(); + + using (token.Register(() => fail.TrySetResult(false))) + { + if ((await Task.WhenAny(t, fail.Task)) == t) + { + lam(token); + } + token.ThrowIfCancellationRequested(); + } + } + public static async Task Then(this Task t, Func lam) + { + await t; + await lam(); + } + public static Task Then(this Task t, Func lam, CancellationToken token) + => Then(t, (_) => lam(), token); + public static async Task Then(this Task t, Func lam, CancellationToken token) + { + TaskCompletionSource fail = new TaskCompletionSource(); + + using (token.Register(() => fail.TrySetResult(false))) + { + if ((await Task.WhenAny(t, fail.Task)) == t) + { + await lam(token); + } + token.ThrowIfCancellationRequested(); + } + } + public static async Task Then(this Task t, Action lam) + { + T res = await t; + lam(res); + return res; + } + public static Task Then(this Task t, Action lam, CancellationToken token) + => Then(t, (v, _) => lam(v), token); + public static async Task Then(this Task t, Action lam, CancellationToken token) + { + TaskCompletionSource fail = new TaskCompletionSource(); + + using (token.Register(() => fail.TrySetResult(false))) + { + if ((await Task.WhenAny(t, fail.Task)) == t) + { + var res = t.Result; + lam(res, token); + return res; + } + throw new OperationCanceledException(); + } + } + public static async Task Then(this Task t, Func lam) + { + T res = await t; + return lam(res); + } + public static Task Then(this Task t, Func lam, CancellationToken token) + => Then(t, (v, _) => lam(v), token); + public static async Task Then(this Task t, Func lam, CancellationToken token) + { + TaskCompletionSource fail = new TaskCompletionSource(); + + using (token.Register(() => fail.TrySetResult(false))) + { + if ((await Task.WhenAny(t, fail.Task)) == t) + { + var res = t.Result; + res = lam(res, token); + return res; + } + throw new OperationCanceledException(); + } + } + public static async Task Then(this Task t, Func> lam) + { + return await lam(await t); + } + public static Task Then(this Task t, Func> lam, CancellationToken token) + => Then(t, (x, _) => lam(x), token); + public static async Task Then(this Task t, Func> lam, CancellationToken token) + { + TaskCompletionSource fail = new TaskCompletionSource(); + + using (token.Register(() => fail.TrySetResult(false))) + { + if ((await Task.WhenAny(t, fail.Task)) == t) + { + var res = t.Result; + res = await lam(res, token); + return res; + } + throw new OperationCanceledException(); + } + } + #endregion + + public static CancellationTokenSource Link(this in CancellationToken token, params CancellationToken[] others) + { + return CancellationTokenSource.CreateLinkedTokenSource(new CancellationToken[] { token }.Concat(others).ToArray()); + } + + + } + + +} diff --git a/exasynctools/Maybes.cs b/exasynctools/Maybes.cs new file mode 100644 index 0000000..40db266 --- /dev/null +++ b/exasynctools/Maybes.cs @@ -0,0 +1,325 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Tools.Maybes +{ + static class test + { + public static void maybe() + { + var result = Maybe.Some(false); + + if(result) + { + bool value = result; + + } + else + { + + } + + result.Match(Some: value => + { + return 10; + }, None: () => + { + return 0; + }); + + var valresult = ValueMaybe.Some(10.1f); + if(valresult) + { + float res = valresult; + } + else + { + + } + + valresult.Match(Some: value => + { + return value * 2; + }, None: () => + { + return 0; + }); + } + /* public void tresult() + { + var result = Result.Ok("hi"); + }*/ + } + + public static class ValueMaybe + { + public static ValueMaybe Some(T value) + => new ValueMaybe(value, true); + public static ValueMaybe None() + => new ValueMaybe(default, false); + } + public readonly struct ValueMaybe + { + private readonly T value; + private readonly bool hasValue; + + public bool Equals(ValueMaybe other) + { + return other.hasValue == this.hasValue && (ReferenceEquals(value, other.value) || (value?.Equals(other.value) ?? false)); + } + public override int GetHashCode() + { + return hasValue ? Math.Abs(value?.GetHashCode() ?? 0) : -1; + } + + public override bool Equals(object obj) + { + return (obj is ValueMaybe some && Equals(some)) || (hasValue && obj is T val && (ReferenceEquals(val, value) || (value?.Equals(val) ?? false))); + } + + internal ValueMaybe(T value, bool hasValue) + { + this.hasValue = hasValue; + this.value = value; + } + + public static bool operator true(ValueMaybe some) + => some.hasValue; + public static bool operator false(ValueMaybe some) + => !some.hasValue; + + public static implicit operator T(ValueMaybe input) + => input.hasValue ? input.value : throw new InvalidCastException("No value"); + public static implicit operator ValueMaybe(T input) + => ValueMaybe.Some(input); + + public T Value => value; + public bool HasValue => hasValue; + + public bool TryGetValue(out T value) + { + if(HasValue) + { + value = Value; + return true; + } + value = default; + return false; + } + + public void Match(Action Some=null, Action None=null) + { + if (hasValue) + Some?.Invoke(value); + else + None?.Invoke(); + } + public V Match(Func Some=null, Func None=null) + { + if(hasValue) + { + if (Some != null) return Some(value); + else return default; + } + else + { + if (None != null) return None(); + else return default; + } + } + + public static bool operator ==(ValueMaybe left, ValueMaybe right) + { + return left.Equals(right); + } + + public static bool operator !=(ValueMaybe left, ValueMaybe right) + { + return !(left == right); + } + } + + public sealed class Some : Maybe + { + public override T Value { get; } + internal Some(T value) + { + Value = value; + } + + public override bool Equals(object obj) + { + return obj is Some some && (ReferenceEquals(some.Value, Value) || (some.Value?.Equals(Value) ?? false)); + } + public override int GetHashCode() + { + return Math.Abs(Value?.GetHashCode() ?? 0); + } + + public override string ToString() + { + return "Some(" + (Value?.ToString() ?? "null") + ")"; + } + } + public sealed class None : Maybe + { + internal None() { } + + public override bool Equals(object obj) + { + return obj is None; + } + public override int GetHashCode() + { + return -1; + } + + public override string ToString() + { + return "None"; + } + } + public static class Maybe + { + public static Maybe Some(T value) + => new Some(value); + + public static Maybe None() + => new None(); + } + public abstract class Maybe + { + public static bool operator true(Maybe input) + => input is Some; + public static bool operator false(Maybe input) + => input is None; + + public override bool Equals(object obj) + { + throw new NotImplementedException(); + } + public override int GetHashCode() + { + throw new NotImplementedException(); + } + public override string ToString() + { + throw new NotImplementedException(); + } + + public static bool operator ==(Maybe left, T right) + => left.HasValue && (left == Maybe.Some(right)); + public static bool operator !=(Maybe left, T right) + => !(left == right); + public static bool operator ==(Maybe left, Maybe right) + { + return ReferenceEquals(left, right) || (left?.Equals(right) ?? false); + } + public static bool operator !=(Maybe left, Maybe right) + => !(left == right); + + public static implicit operator T(Maybe some) => some is Some thing ? thing : throw new InvalidCastException("No value"); + public static implicit operator Maybe(T some) => new Some(some); + + public virtual T Value => (T)this; + public bool HasValue => this is Some; + + public bool TryGetValue(out T value) + { + if(this is Some thing) + { + value = thing.Value; + return true; + } + value = default; + return false; + } + + public void Match(Action Some = null, Action None = null) + { + if (this is Some some) + { + Some?.Invoke(some.Value); + } + else if (this is None none) + None?.Invoke(); + throw new InvalidOperationException("Maybe is neither some nor none."); + } + public V Match(Func Some = null, Func None = null) + { + if (this is Some some) + { + if (Some == null) return default; + else return Some(some.Value); + } + else if (this is None none) + { + if (None == null) return default; + else + return None(); + } + throw new InvalidOperationException("Maybe is neither some nor none."); + } + } +#if REWORK && false + public class Ok : Result + { + public override T Value { get; } + public Ok(T value) + { + Value = value; + } + } + public class Err : Result + { + public override E Error { get; } + public Err(E exception) + { + Error = exception; + } + } + public static class Result + { + public static Ok Ok(T value) + => new Ok(value); + public static Err Err(E value) + => new Err(value); + } + public abstract class Result + { + public static bool operator true(Result input) + => input is Ok; + public static bool operator false(Result input) + => input is Err; + + public virtual T Value => (T)this; + public virtual E Error => (E)this; + + + public bool TryGetValue(out T value) + { + if (this is Ok thing) + { + value = thing.Value; + return true; + } + value = default; + return false; + } + public bool TryGetError(out E value) + { + if (this is Err thing) + { + value = thing.Error; + return true; + } + value = default; + return false; + } + + public static implicit operator T(Result validResult) => validResult is Ok ok ? ok.Value : throw new InvalidCastException("No value"); + public static implicit operator E(Result invalidResult) => invalidResult is Err ok ? ok.Error : throw new InvalidCastException("No exception"); + } +#endif +} diff --git a/exasynctools/exasynctools.csproj b/exasynctools/exasynctools.csproj new file mode 100644 index 0000000..72764a6 --- /dev/null +++ b/exasynctools/exasynctools.csproj @@ -0,0 +1,7 @@ + + + + netstandard2.0 + + + diff --git a/exbintools/Class1.cs b/exbintools/Class1.cs new file mode 100644 index 0000000..3ca5924 --- /dev/null +++ b/exbintools/Class1.cs @@ -0,0 +1,581 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace Tools +{ + namespace ByValData + { + namespace Fixed + { + namespace Special + { + public unsafe struct FixedSHA1Hash + { + public const int Size = 20; + public fixed byte data[Size]; + + public FixedSHA1Hash(byte[] from) + { + fixed (byte* p = data) + { + Marshal.Copy(from, 0, (IntPtr)p, Math.Min(Size, from.Length)); + } + } + + public static implicit operator byte[](FixedSHA1Hash from) + { + return from.ToByteArrayUnmanaged(); + } + public static implicit operator FixedSHA1Hash(byte[] from) + { + return from.ToUnmanaged(); + } + } + } + public unsafe struct FixedByteArray1 + { + public const int Size = 1; + public fixed byte data[Size]; + + public byte AsByte + { + get + { + fixed (byte* ptr = data) return *ptr; + } + set + { + fixed (byte* ptr = data) *ptr = value; + } + } + public sbyte AsSByte + { + get + { + fixed (byte* ptr = data) return *(sbyte*)ptr; + } + set + { + fixed (byte* ptr = data) *(sbyte*)ptr = value; + } + } + + public FixedByteArray1(byte asByte) + { + AsByte = asByte; + } + public FixedByteArray1(sbyte asSbyte) + { + AsSByte = asSbyte; + } + + public FixedByteArray1(byte[] from) + { + fixed (byte* p = data) + { + Marshal.Copy(from, 0, (IntPtr)p, Math.Min(Size, from.Length)); + } + } + + public static implicit operator byte[](FixedByteArray1 from) + { + return from.ToByteArrayUnmanaged(); + } + public static implicit operator FixedByteArray1(byte[] from) + { + return from.ToUnmanaged(); + } + } + public unsafe struct FixedByteArray2 + { + public const int Size = 2; + public fixed byte data[Size]; + + public short AsShort + { + get + { + fixed (byte* ptr = data) return *(short*)ptr; + } + set + { + fixed (byte* ptr = data) *(short*)ptr = value; + } + } + public ushort AsUShort + { + get + { + fixed (byte* ptr = data) return *(ushort*)ptr; + } + set + { + fixed (byte* ptr = data) *(ushort*)ptr = value; + } + } + + public char AsChar + { + get + { + fixed (byte* ptr = data) return *(char*)ptr; + } + set + { + fixed (byte* ptr = data) *(char*)ptr = value; + } + } + + public FixedByteArray2(char fromChar) + { + AsChar = fromChar; + } + public FixedByteArray2(short fromShort) + { + AsShort = fromShort; + } + public FixedByteArray2(ushort fromUshort) + { + AsUShort = fromUshort; + } + + public FixedByteArray2(byte[] from) + { + fixed (byte* p = data) + { + Marshal.Copy(from, 0, (IntPtr)p, Math.Min(Size, from.Length)); + } + } + + public static implicit operator byte[](FixedByteArray2 from) + { + return from.ToByteArrayUnmanaged(); + } + public static implicit operator FixedByteArray2(byte[] from) + { + return from.ToUnmanaged(); + } + } + public unsafe struct FixedByteArray4 + { + public const int Size = 4; + public fixed byte data[Size]; + + public int AsInt + { + get + { + fixed (byte* ptr = data) return *(int*)ptr; + } + set + { + fixed (byte* ptr = data) *(int*)ptr = value; + } + } + public uint AsUInt + { + get + { + fixed (byte* ptr = data) return *(uint*)ptr; + } + set + { + fixed (byte* ptr = data) *(uint*)ptr = value; + } + } + + public bool AsBool + { + get + { + fixed (byte* ptr = data) return *(bool*)ptr; + } + set + { + fixed (byte* ptr = data) *(bool*)ptr = value; + } + } + public float AsFloat + { + get + { + fixed (byte* ptr = data) return *(float*)ptr; + } + set + { + fixed (byte* ptr = data) *(float*)ptr = value; + } + } + + public FixedByteArray4(float fromFloat) + { + AsFloat = fromFloat; + } + public FixedByteArray4(bool fromBool) + { + AsBool = fromBool; + } + public FixedByteArray4(int fromInt) + { + AsInt = fromInt; + } + public FixedByteArray4(uint fromUint) + { + AsUInt = fromUint; + } + + public FixedByteArray4(byte[] from) + { + fixed (byte* p = data) + { + Marshal.Copy(from, 0, (IntPtr)p, Math.Min(Size, from.Length)); + } + } + + public static implicit operator byte[](FixedByteArray4 from) + { + return from.ToByteArrayUnmanaged(); + } + public static implicit operator FixedByteArray4(byte[] from) + { + return from.ToUnmanaged(); + } + } + public unsafe struct FixedByteArray8 + { + public const int Size = 8; + public fixed byte data[Size]; + + public long AsLong + { + get + { + fixed (byte* ptr = data) return *(long*)ptr; + } + set + { + fixed (byte* ptr = data) *(long*)ptr = value; + } + } + public ulong AsULong + { + get + { + fixed (byte* ptr = data) return *(ulong*)ptr; + } + set + { + fixed (byte* ptr = data) *(ulong*)ptr = value; + } + } + + public double AsDouble + { + get + { + fixed (byte* ptr = data) return *(double*)ptr; + } + set + { + fixed (byte* ptr = data) *(double*)ptr = value; + } + } + + public FixedByteArray8(double asDouble) + { + AsDouble = asDouble; + } + public FixedByteArray8(ulong asUlong) + { + AsULong = asUlong; + } + public FixedByteArray8(long asLong) + { + AsLong = asLong; + } + + public FixedByteArray8(byte[] from) + { + fixed (byte* p = data) + { + Marshal.Copy(from, 0, (IntPtr)p, Math.Min(Size, from.Length)); + } + } + + public static implicit operator byte[](FixedByteArray8 from) + { + return from.ToByteArrayUnmanaged(); + } + public static implicit operator FixedByteArray8(byte[] from) + { + return from.ToUnmanaged(); + } + } + public unsafe struct FixedByteArray16 + { + public const int Size = 16; + public fixed byte data[Size]; + + public decimal AsDecimal + { + get + { + fixed (byte* ptr = data) return *(decimal*)ptr; + } + set + { + fixed (byte* ptr = data) *(decimal*)ptr = value; + } + } + + public FixedByteArray16(decimal from) + { + AsDecimal = from; + } + + public FixedByteArray16(byte[] from) + { + fixed (byte* p = data) + { + Marshal.Copy(from, 0, (IntPtr)p, Math.Min(Size, from.Length)); + } + } + + public static implicit operator byte[](FixedByteArray16 from) + { + return from.ToByteArrayUnmanaged(); + } + public static implicit operator FixedByteArray16(byte[] from) + { + return from.ToUnmanaged(); + } + } + public unsafe struct FixedByteArray32 + { + public const int Size = 32; + public fixed byte data[Size]; + + public FixedByteArray32(byte[] from) + { + fixed (byte* p = data) + { + Marshal.Copy(from, 0, (IntPtr)p, Math.Min(Size, from.Length)); + } + } + + public static implicit operator byte[](FixedByteArray32 from) + { + return from.ToByteArrayUnmanaged(); + } + public static implicit operator FixedByteArray32(byte[] from) + { + return from.ToUnmanaged(); + } + } + public unsafe struct FixedByteArray64 + { + public const int Size = 64; + public fixed byte data[Size]; + + public FixedByteArray64(byte[] from) + { + fixed (byte* p = data) + { + Marshal.Copy(from, 0, (IntPtr)p, Math.Min(Size, from.Length)); + } + } + + public static implicit operator byte[](FixedByteArray64 from) + { + return from.ToByteArrayUnmanaged(); + } + public static implicit operator FixedByteArray64(byte[] from) + { + return from.ToUnmanaged(); + } + } + + public unsafe struct FixedByteArray128 + { + public const int Size = 128; + public fixed byte data[Size]; + + public FixedByteArray128(byte[] from) + { + fixed (byte* p = data) + { + Marshal.Copy(from, 0, (IntPtr)p, Math.Min(Size, from.Length)); + } + } + + public static implicit operator byte[](FixedByteArray128 from) + { + return from.ToByteArrayUnmanaged(); + } + public static implicit operator FixedByteArray128(byte[] from) + { + return from.ToUnmanaged(); + } + } + public unsafe struct FixedByteArray256 + { + public const int Size = 128; + public fixed byte data[Size]; + + public FixedByteArray256(byte[] from) + { + fixed (byte* p = data) + { + Marshal.Copy(from, 0, (IntPtr)p, Math.Min(Size, from.Length)); + } + } + + public static implicit operator byte[](FixedByteArray256 from) + { + return from.ToByteArrayUnmanaged(); + } + public static implicit operator FixedByteArray256(byte[] from) + { + return from.ToUnmanaged(); + } + } + public unsafe struct FixedByteArray512 + { + public const int Size = 512; + public fixed byte data[Size]; + + public FixedByteArray512(byte[] from) + { + fixed (byte* p = data) + { + Marshal.Copy(from, 0, (IntPtr)p, Math.Min(Size, from.Length)); + } + } + + public static implicit operator byte[](FixedByteArray512 from) + { + return from.ToByteArrayUnmanaged(); + } + public static implicit operator FixedByteArray512(byte[] from) + { + return from.ToUnmanaged(); + } + } + public unsafe struct FixedByteArray1024 + { + public const int Size = 1024; + public fixed byte data[Size]; + + public FixedByteArray1024(byte[] from) + { + fixed (byte* p = data) + { + Marshal.Copy(from, 0, (IntPtr)p, Math.Min(Size, from.Length)); + } + } + + public static implicit operator byte[](FixedByteArray1024 from) + { + return from.ToByteArrayUnmanaged(); + } + public static implicit operator FixedByteArray1024(byte[] from) + { + return from.ToUnmanaged(); + } + } + public unsafe struct FixedByteArray2048 + { + public const int Size = 2048; + public fixed byte data[Size]; + + public FixedByteArray2048(byte[] from) + { + fixed (byte* p = data) + { + Marshal.Copy(from, 0, (IntPtr)p, Math.Min(Size, from.Length)); + } + } + + public static implicit operator byte[](FixedByteArray2048 from) + { + return from.ToByteArrayUnmanaged(); + } + public static implicit operator FixedByteArray2048(byte[] from) + { + return from.ToUnmanaged(); + } + } + public unsafe struct FixedByteArray4096 + { + public const int Size = 4096; + public fixed byte data[Size]; + + public FixedByteArray4096(byte[] from) + { + fixed (byte* p = data) + { + Marshal.Copy(from, 0, (IntPtr)p, Math.Min(Size, from.Length)); + } + } + + public static implicit operator byte[](FixedByteArray4096 from) + { + return from.ToByteArrayUnmanaged(); + } + public static implicit operator FixedByteArray4096(byte[] from) + { + return from.ToUnmanaged(); + } + } + + } + } + public static class ExBinTools + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe byte[] ToByteArrayUnmanaged(this T t) where T : unmanaged + { + byte[] o = new byte[sizeof(T)]; + fixed (byte* ptr = o) + { + *(T*)ptr = t; + } + return o; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe T ToUnmanaged(this byte[] bytes) where T : unmanaged + { + fixed (byte* ptr = bytes) + { + return *(T*)ptr; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe ref T ZeroMemory(this ref T value) where T : unmanaged + { + byte[] buffer = new byte[sizeof(T)]; + + fixed (T* valuePtr = &value) + { + Marshal.Copy(buffer, 0, (IntPtr)valuePtr, sizeof(T)); + } + + return ref value; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe ref T SetMemory(this ref T value, byte def=default) where T : unmanaged + { + byte[] buffer = new byte[sizeof(T)]; + for (int i = 0; i < sizeof(T); i++) buffer[i] = def; + + fixed (T* valuePtr = &value) + { + Marshal.Copy(buffer, 0, (IntPtr)valuePtr, sizeof(T)); + } + + return ref value; + } + } +} diff --git a/exbintools/exbintools.csproj b/exbintools/exbintools.csproj new file mode 100644 index 0000000..1b2f99a --- /dev/null +++ b/exbintools/exbintools.csproj @@ -0,0 +1,15 @@ + + + + netstandard2.0 + + + + true + + + + true + + + diff --git a/excryptotools/Class1.cs b/excryptotools/Class1.cs new file mode 100644 index 0000000..1707a37 --- /dev/null +++ b/excryptotools/Class1.cs @@ -0,0 +1,831 @@ +using System; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Linq; +using Tools; +using System.IO; + +namespace Tools.Crypto +{ + static unsafe class MemoryHelper + { + public static byte[] UMToByteArray(void* ptr, int size) + { + byte[] output = new byte[size]; + Marshal.Copy((IntPtr)ptr, output, 0, size); + return output; + } + + public static void ByteArrayToUM(byte[] input, void* ptr, int size) + { + Marshal.Copy(input, 0, (IntPtr)ptr, size); + } + + public static T[] UMToArray(T* ptr, int size) where T : unmanaged + { + T[] output = new T[size]; + fixed (T* outputPtr = output) + Buffer.MemoryCopy(ptr, outputPtr, size * sizeof(T), size * sizeof(T)); + return output; + } + public static void ArrayToUM(T[] input, T* ptr, int size) where T : unmanaged + { + fixed (T* inputPtr = input) + Buffer.MemoryCopy(inputPtr, ptr, sizeof(T) * size, sizeof(T) * size); + } + } + public unsafe struct RSAHashSignature + { + public const int Length = 32; + + internal fixed byte sig[Length]; + + public byte[] Signature + { + get + { + fixed (byte* ptr = sig) + { + return MemoryHelper.UMToByteArray(ptr, Length); + } + } + set + { + fixed (byte* ptr = sig) + MemoryHelper.ByteArrayToUM(value, ptr, Length); + } + } + + public static RSAHashSignature CreateSignature(RSACryptoServiceProvider rsa, SHA256 algo, byte[] data) + { + return rsa.SignData(data, algo).ToUnmanaged(); + } + public static RSAHashSignature CreateSignature(RSACryptoServiceProvider rsa, byte[] data) + { + using (var algo = SHA256.Create()) + return CreateSignature(rsa, algo, data); + } + + public bool Verify(RSACryptoServiceProvider rsa, SHA256 algo, byte[] data) + { + return rsa.VerifyData(data, algo, Signature); + } + public bool Verify(RSACryptoServiceProvider rsa, byte[] data) + { + using (var algo = SHA256.Create()) + return Verify(rsa, algo, data); + } + } + public unsafe struct RSACiphertext + { + public const int Length = 128; + + internal fixed byte ciphertext[Length]; + + public byte[] Ciphertext + { + get + { + fixed (byte* ptr = ciphertext) + return MemoryHelper.UMToByteArray(ptr, Length); + } + set + { + fixed (byte* ptr = ciphertext) + MemoryHelper.ByteArrayToUM(value, ptr, Length); + } + } + + public void EncryptSingleBlock(RSACryptoServiceProvider rsa, byte[] plain) + { + Ciphertext = rsa.Encrypt(plain, false); + } + public byte[] DecryptSingleBlock(RSACryptoServiceProvider rsa) + { + return rsa.Decrypt(Ciphertext, false); + } + + public unsafe static RSACiphertext[] Encrypt(RSACryptoServiceProvider rsa, byte[] plain) + { + byte[] ct = rsa.Encrypt(plain, false); + + if (ct.Length == Length) return new RSACiphertext[] { new RSACiphertext() { Ciphertext = ct } }; + else if (ct.Length % Length == 0) + { + int ciphers = ct.Length / Length; + RSACiphertext* cipher = stackalloc RSACiphertext[ciphers]; + + Marshal.Copy(ct, 0, (IntPtr)cipher, ciphers * sizeof(RSACiphertext)); + + return MemoryHelper.UMToArray(cipher, ciphers); + } + else + { + //Probably won't happen? + int ciphers = (ct.Length / Length) + 1; + RSACiphertext* cipher = stackalloc RSACiphertext[ciphers]; + + Marshal.Copy(ct, 0, (IntPtr)cipher, ciphers * sizeof(RSACiphertext)); + + return MemoryHelper.UMToArray(cipher, ciphers); + } + } + public static byte[] Decrypt(RSACryptoServiceProvider rsa, RSACiphertext[] cipher) + { + byte[] byts = new byte[sizeof(RSACiphertext) * cipher.Length]; + fixed (RSACiphertext* input = cipher) + { + fixed (byte* output = byts) + { + Buffer.MemoryCopy(input, output, byts.Length, byts.Length); + } + } + return rsa.Decrypt(byts, false); + } + } + + public unsafe struct AESKey + { + public const int KeySize = 32; + public const int IVSize = 16; + + internal fixed byte key[KeySize]; + internal fixed byte iv[IVSize]; + + /// + /// The Key (256 bit) + /// + public byte[] Key + { + get + { + byte[] bytes = new byte[KeySize]; + fixed (byte* k = key) + { + Marshal.Copy((IntPtr)k, bytes, 0, KeySize); + } + return bytes; + } + set + { + if (value.Length != KeySize) throw new ArgumentException(nameof(value) + " must be exaclty " + KeySize + " bytes (not " + value.Length + ")"); + fixed (byte* k = key) + { + Marshal.Copy(value, 0, (IntPtr)k, KeySize); + } + } + } + + /// + /// The IV (128 bits) + /// + public byte[] IV + { + get + { + byte[] bytes = new byte[IVSize]; + fixed (byte* k = iv) + { + Marshal.Copy((IntPtr)k, bytes, 0, IVSize); + } + return bytes; + } + set + { + if (value.Length != IVSize) throw new ArgumentException(nameof(value) + " must be exaclty " + IVSize + " bytes (not " + value.Length + ")"); + fixed (byte* k = iv) + { + Marshal.Copy(value, 0, (IntPtr)k, IVSize); + } + } + } + + + /// + /// Binary serialisation of this key + /// + public byte[] BinaryData + { + get + { + return this.ToByteArrayUnmanaged(); + } + set + { + if (value.Length < sizeof(AESKey)) throw new ArgumentException(nameof(value) + " must be at least " + sizeof(AESKey) + " bytes (not " + value.Length + ")"); + fixed (AESKey* k = &this) + { + Marshal.Copy(value, 0, (IntPtr)k, sizeof(AESKey)); + } + } + } + + /// + /// Create a new key + /// + /// The new AES Key + public static AESKey NewKey() + { + using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider()) + { + byte[] buffer = new byte[sizeof(AESKey)]; + rng.GetBytes(buffer); + return buffer.ToUnmanaged(); + } + } + + /// + /// Set the key and iv to an AesCryptoServiceProvider + /// + /// The CSP + public void ToCSP(AesCryptoServiceProvider r) + { + r.KeySize = 256; + r.BlockSize = 128; + + r.Key = Key; + r.IV = IV; + } + + public void FromAes(Aes aes) + { + Key = aes.Key; + IV = aes.IV; + } + + public void ToAes(Aes aes) + { + aes.KeySize = 256; + aes.BlockSize = 128; + + aes.Key = Key; + aes.IV = IV; + } + + /// + /// Get the key and iv from and AESCryptoServiceProvider + /// + /// The CSP + public void FromCSP(AesCryptoServiceProvider r) + { + Key = r.Key; + IV = r.IV; + } + /// + /// Initialise a new AESKey from an AESCryptoServiceProvider + /// + /// The AES key + public AESKey(AesCryptoServiceProvider aes) + { + FromCSP(aes); + } + + public AESKey(Aes aes) + { + FromAes(aes); + } + } + + public unsafe struct RSAPublicKey + { + public const int ModulusSize = 128; + public const int ExponentSize = 3; + + internal fixed byte mod[ModulusSize]; + internal fixed byte exp[ExponentSize]; + + /// + /// The modulus of this key + /// + public byte[] Modulus + { + get + { + byte[] bytes = new byte[ModulusSize]; + fixed (byte* m = mod) + { + Marshal.Copy((IntPtr)m, bytes, 0, ModulusSize); + } + return bytes; + } + set + { + if (value.Length != ModulusSize) throw new ArgumentException(nameof(value) + " must be exaclty " + ModulusSize + " bytes (not " + value.Length + ")"); + fixed (byte* m = mod) + { + Marshal.Copy(value, 0, (IntPtr)m, ModulusSize); + } + } + } + /// + /// The public exponent of this key + /// + public byte[] Exponent + { + get + { + byte[] bytes = new byte[ExponentSize]; + fixed (byte* m = exp) + { + Marshal.Copy((IntPtr)m, bytes, 0, ExponentSize); + } + return bytes; + } + set + { + if (value.Length != ExponentSize) throw new ArgumentException(nameof(value) + " must be exaclty " + ExponentSize + " bytes (not " + value.Length + ")"); + fixed (byte* m = exp) + { + Marshal.Copy(value, 0, (IntPtr)m, ExponentSize); + } + } + } + + /// + /// Binary serialisation of this key + /// + public byte[] BinaryData + { + get + { + return this.ToByteArrayUnmanaged(); + } + set + { + if (value.Length < sizeof(RSAPublicKey)) throw new ArgumentException(nameof(value) + " must be at least " + sizeof(RSAPublicKey) + " bytes (not " + value.Length + ")"); + fixed (RSAPublicKey* k = &this) + { + Marshal.Copy(value, 0, (IntPtr)k, sizeof(RSAPublicKey)); + } + } + } + + /// + /// Set the public key to a RSACryptoServiceProvider + /// + /// The CSP to set the key to + public void ToCSP(RSACryptoServiceProvider csp) + { + var p = csp.ExportParameters(false); + p.Modulus = Modulus; + p.Exponent = Exponent; + csp.ImportParameters(p); + } + /// + /// Get the public key information from an RSACryptoServiceProvider and return it in an RSAPublicKey struct + /// + /// The CSP + /// A new RSAPublicKey struct + public static RSAPublicKey FromCSP(RSACryptoServiceProvider csp) + { + RSAPublicKey rp = new RSAPublicKey(); + var p = csp.ExportParameters(false); + rp.Modulus = p.Modulus; + rp.Exponent = p.Exponent; + return rp; + } + + public static implicit operator byte[](RSAPublicKey rp) + { + return rp.ToByteArrayUnmanaged(); + } + public static explicit operator RSAPublicKey(byte[] byt) + { + return byt.ToUnmanaged(); + } + } + + public unsafe struct RSAPrivateKey + { + + public override string ToString() + { + return BitConverter.ToString(this.ToByteArrayUnmanaged()).Replace("-", ""); + } + + public override bool Equals(object obj) + { + return obj is RSAPrivateKey priv && priv.ToByteArrayUnmanaged().SequenceEqual(this.ToByteArrayUnmanaged()); + } + + public override int GetHashCode() + { + unchecked + { + return (int)DamienG.Security.Cryptography.Crc32.Compute(this.ToByteArrayUnmanaged()); + } + } + + public RSAPublicKey PublicPart => new RSAPublicKey() { Modulus = Modulus, Exponent = Exponent }; + + public const int ModulusLength = 128; + public const int ExponentLength = 3; + public const int DLength = 128; + public const int PLength = 64; + public const int QLength = 64; + public const int DPLength = 64; + public const int DQLength = 64; + public const int InverseQLength = 64; + + internal fixed byte modulus[ModulusLength]; + internal fixed byte exponent[ExponentLength]; + internal fixed byte d[DLength]; + internal fixed byte p[PLength]; + internal fixed byte q[QLength]; + internal fixed byte dp[DPLength]; + internal fixed byte dq[DQLength]; + internal fixed byte inverseQ[InverseQLength]; + + public byte[] Modulus + { + get + { + byte[] bytes = new byte[ModulusLength]; + fixed (byte* m = modulus) + { + Marshal.Copy((IntPtr)m, bytes, 0, ModulusLength); + } + return bytes; + } + set + { + if (value.Length != ModulusLength) throw new ArgumentException(nameof(value) + " must be exaclty " + ModulusLength + " bytes (not " + value.Length + ")"); + fixed (byte* m = modulus) + { + Marshal.Copy(value, 0, (IntPtr)m, ModulusLength); + } + } + } + + public byte[] Exponent + { + get + { + byte[] bytes = new byte[ExponentLength]; + fixed (byte* m = exponent) + { + Marshal.Copy((IntPtr)m, bytes, 0, ExponentLength); + } + return bytes; + } + set + { + if (value.Length != ExponentLength) throw new ArgumentException(nameof(value) + " must be exaclty " + ExponentLength + " bytes (not " + value.Length + ")"); + fixed (byte* m = exponent) + { + Marshal.Copy(value, 0, (IntPtr)m, ExponentLength); + } + } + } + + public byte[] D + { + get + { + byte[] bytes = new byte[DLength]; + fixed (byte* m = d) + { + Marshal.Copy((IntPtr)m, bytes, 0, DLength); + } + return bytes; + } + set + { + if (value.Length != DLength) throw new ArgumentException(nameof(value) + " must be exaclty " + DLength + " bytes (not " + value.Length + ")"); + fixed (byte* m = d) + { + Marshal.Copy(value, 0, (IntPtr)m, DLength); + } + } + } + + public byte[] P + { + get + { + byte[] bytes = new byte[PLength]; + fixed (byte* m = p) + { + Marshal.Copy((IntPtr)m, bytes, 0, PLength); + } + return bytes; + } + set + { + if (value.Length != PLength) throw new ArgumentException(nameof(value) + " must be exaclty " + PLength + " bytes (not " + value.Length + ")"); + fixed (byte* m = p) + { + Marshal.Copy(value, 0, (IntPtr)m, PLength); + } + } + } + + public byte[] Q + { + get + { + byte[] bytes = new byte[QLength]; + fixed (byte* m = q) + { + Marshal.Copy((IntPtr)m, bytes, 0, QLength); + } + return bytes; + } + set + { + if (value.Length != QLength) throw new ArgumentException(nameof(value) + " must be exaclty " + QLength + " bytes (not " + value.Length + ")"); + fixed (byte* m = q) + { + Marshal.Copy(value, 0, (IntPtr)m, QLength); + } + } + } + + public byte[] DP + { + get + { + byte[] bytes = new byte[DPLength]; + fixed (byte* m = dp) + { + Marshal.Copy((IntPtr)m, bytes, 0, DPLength); + } + return bytes; + } + set + { + if (value.Length != DPLength) throw new ArgumentException(nameof(value) + " must be exaclty " + DPLength + " bytes (not " + value.Length + ")"); + fixed (byte* m = dp) + { + Marshal.Copy(value, 0, (IntPtr)m, DPLength); + } + } + } + + public byte[] DQ + { + get + { + byte[] bytes = new byte[DQLength]; + fixed (byte* m = dq) + { + Marshal.Copy((IntPtr)m, bytes, 0, DQLength); + } + return bytes; + } + set + { + if (value.Length != DQLength) throw new ArgumentException(nameof(value) + " must be exaclty " + DQLength + " bytes (not " + value.Length + ")"); + fixed (byte* m = dq) + { + Marshal.Copy(value, 0, (IntPtr)m, DQLength); + } + } + } + + public byte[] InverseQ + { + get + { + byte[] bytes = new byte[InverseQLength]; + fixed (byte* m = inverseQ) + { + Marshal.Copy((IntPtr)m, bytes, 0, InverseQLength); + } + return bytes; + } + set + { + if (value.Length != InverseQLength) throw new ArgumentException(nameof(value) + " must be exaclty " + InverseQLength + " bytes (not " + value.Length + ")"); + fixed (byte* m = inverseQ) + { + Marshal.Copy(value, 0, (IntPtr)m, InverseQLength); + } + } + } + + + public void FromCSP(RSACryptoServiceProvider rsa) + { + var param = rsa.ExportParameters(true); + + Modulus = param.Modulus; + Exponent = param.Exponent; + D = param.D; + P = param.P; + Q = param.Q; + DP = param.DP; + DQ = param.DQ; + InverseQ = param.InverseQ; + } + + public void ToCSP(RSACryptoServiceProvider rsa) + { + var param = new RSAParameters(); + + param.Modulus = Modulus; + param.Exponent = Exponent; + param.D = D; + param.P = P; + param.Q = Q; + param.DP = DP; + param.DQ = DQ; + param.InverseQ = InverseQ; + + rsa.ImportParameters(param); + } + + public static RSAPrivateKey Generate() + { + using (var rsa = new RSACryptoServiceProvider()) + { + RSAPrivateKey ret = new RSAPrivateKey(); + ret.FromCSP(rsa); + return ret; + } + } + + public static bool operator ==(RSAPrivateKey left, RSAPrivateKey right) + { + return left.Equals(right); + } + + public static bool operator !=(RSAPrivateKey left, RSAPrivateKey right) + { + return !(left == right); + } + } + + public unsafe struct SHA256Hash + { + public const int Size = 32; + internal fixed byte hash[Size]; + + public override bool Equals(object obj) + { + return obj is SHA256Hash hash && hash.ToByteArrayUnmanaged().SequenceEqual(this.ToByteArrayUnmanaged()); + } + + public override int GetHashCode() + { + unchecked + { + return (int)DamienG.Security.Cryptography.Crc32.Compute(this.ToByteArrayUnmanaged()); + } + } + + public byte[] Hash + { + get + { + byte[] bytes = new byte[Size]; + fixed (byte* m = hash) + { + Marshal.Copy((IntPtr)m, bytes, 0, Size); + } + return bytes; + } + set + { + if (value.Length != Size) throw new ArgumentException(nameof(value) + " must be exaclty " + Size + " bytes (not " + value.Length + ")"); + fixed (byte* m = hash) + { + Marshal.Copy(value, 0, (IntPtr)m, Size); + } + } + } + + public SHA256Hash(byte[] hash) + { + Hash = hash; + } + + public static SHA256Hash Generate(byte[] data, SHA256 hasher = null) + { + if (hasher == null) + using (var hash = SHA256.Create()) + return Generate(data, hash); + + return (SHA256Hash)hasher.ComputeHash(data); + } + + public static implicit operator byte[](SHA256Hash hash) => hash.ToByteArrayUnmanaged(); + public static explicit operator SHA256Hash(byte[] hash) => hash.Length == Size ? hash.ToUnmanaged() : throw new InvalidCastException("Hash must be exactly "+Size+" bytes"); + + public static bool operator ==(SHA256Hash left, SHA256Hash right) + { + return left.Equals(right); + } + + public static bool operator !=(SHA256Hash left, SHA256Hash right) + { + return !(left == right); + } + + public override string ToString() + { + return BitConverter.ToString(this.ToByteArrayUnmanaged()).Replace("-", "").ToLower(); + } + } +} + +namespace Tools +{ + using Tools.Crypto; + + public class IncrementalHashStream : Stream + { + private long written = 0; + private IncrementalHash hasher; + public IncrementalHashStream(HashAlgorithmName algo) + { + hasher = IncrementalHash.CreateHash(algo); + } + + private byte[] hash; + public SHA256Hash Hash => new SHA256Hash() { Hash = hash ?? throw new InvalidOperationException("Hash has not been computed. (Call Flush())") }; + public SHA256Hash HashAndReset() + { + Flush(); + return Hash; + } + + public override bool CanRead => false; + + public override bool CanSeek => false; + + public override bool CanWrite => true; + + public override long Length => written; + + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + + /// + /// Compute the hash of all written data, store it in , and reset the algorithm. + /// + public override void Flush() + { + lock (mutex) + { + hash = hasher.GetHashAndReset(); + } + written = 0; + } + + public override int Read(byte[] buffer, int offset, int count) + { + throw new NotSupportedException(); + } + + public override long Seek(long offset, SeekOrigin origin) + { + throw new NotSupportedException(); + } + + public override void SetLength(long value) + { + throw new NotSupportedException(); + } + + private readonly object mutex = new object(); + public override void Write(byte[] buffer, int offset, int count) + { + var dt = new ArraySegment(buffer, offset, count).Array; + lock (mutex) + { + hasher.AppendData(dt); + written += dt.Length; + } + } + + public SHA256Hash GetFinalHash() + { + if (hasher == null) throw new ObjectDisposedException(this.ToString()); + Flush(); + Dispose(); + return Hash; + } + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + if (disposing) hasher?.Dispose(); + hasher = null; + } + + } + public static class ExCryptoTools + { + public static SHA256Hash SHA256Hash(this byte[] data) + { + using (var sha = SHA256.Create()) + return (SHA256Hash)sha.ComputeHash(data); + } + + public static SHA256Hash SHA256Hash(this Stream str) + { + using (var sha = SHA256.Create()) + return (SHA256Hash)sha.ComputeHash(str); + } + } +} diff --git a/excryptotools/crc/crc32.cs b/excryptotools/crc/crc32.cs new file mode 100644 index 0000000..910d487 --- /dev/null +++ b/excryptotools/crc/crc32.cs @@ -0,0 +1,119 @@ +// Copyright (c) Damien Guard. All rights reserved. +// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. +// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 +// Originally published at http://damieng.com/blog/2006/08/08/calculating_crc32_in_c_and_net + +using System; +using System.Collections.Generic; +using System.Security.Cryptography; + +namespace DamienG.Security.Cryptography +{ + /// + /// Implements a 32-bit CRC hash algorithm compatible with Zip etc. + /// + /// + /// Crc32 should only be used for backward compatibility with older file formats + /// and algorithms. It is not secure enough for new applications. + /// If you need to call multiple times for the same data either use the HashAlgorithm + /// interface or remember that the result of one Compute call needs to be ~ (XOR) before + /// being passed in as the seed for the next Compute call. + /// + public sealed class Crc32 : HashAlgorithm + { + public const UInt32 DefaultPolynomial = 0xedb88320u; + public const UInt32 DefaultSeed = 0xffffffffu; + + static UInt32[] defaultTable; + + readonly UInt32 seed; + readonly UInt32[] table; + UInt32 hash; + + public Crc32() + : this(DefaultPolynomial, DefaultSeed) + { + } + + public Crc32(UInt32 polynomial, UInt32 seed) + { + table = InitializeTable(polynomial); + this.seed = hash = seed; + } + + public override void Initialize() + { + hash = seed; + } + + protected override void HashCore(byte[] array, int ibStart, int cbSize) + { + hash = CalculateHash(table, hash, array, ibStart, cbSize); + } + + protected override byte[] HashFinal() + { + var hashBuffer = UInt32ToBigEndianBytes(~hash); + HashValue = hashBuffer; + return hashBuffer; + } + + public override int HashSize { get { return 32; } } + + public static UInt32 Compute(byte[] buffer) + { + return Compute(DefaultSeed, buffer); + } + + public static UInt32 Compute(UInt32 seed, byte[] buffer) + { + return Compute(DefaultPolynomial, seed, buffer); + } + + public static UInt32 Compute(UInt32 polynomial, UInt32 seed, byte[] buffer) + { + return ~CalculateHash(InitializeTable(polynomial), seed, buffer, 0, buffer.Length); + } + + static UInt32[] InitializeTable(UInt32 polynomial) + { + if (polynomial == DefaultPolynomial && defaultTable != null) + return defaultTable; + + var createTable = new UInt32[256]; + for (var i = 0; i < 256; i++) + { + var entry = (UInt32)i; + for (var j = 0; j < 8; j++) + if ((entry & 1) == 1) + entry = (entry >> 1) ^ polynomial; + else + entry = entry >> 1; + createTable[i] = entry; + } + + if (polynomial == DefaultPolynomial) + defaultTable = createTable; + + return createTable; + } + + static UInt32 CalculateHash(UInt32[] table, UInt32 seed, IList buffer, int start, int size) + { + var crc = seed; + for (var i = start; i < size - start; i++) + crc = (crc >> 8) ^ table[buffer[i] ^ crc & 0xff]; + return crc; + } + + static byte[] UInt32ToBigEndianBytes(UInt32 uint32) + { + var result = BitConverter.GetBytes(uint32); + + if (BitConverter.IsLittleEndian) + Array.Reverse(result); + + return result; + } + } +} \ No newline at end of file diff --git a/excryptotools/crc/crc64.cs b/excryptotools/crc/crc64.cs new file mode 100644 index 0000000..2991783 --- /dev/null +++ b/excryptotools/crc/crc64.cs @@ -0,0 +1,139 @@ +// Copyright (c) Damien Guard. All rights reserved. +// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. +// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 +// Originally published at http://damieng.com/blog/2007/11/19/calculating-crc-64-in-c-and-net + +using System; +using System.Collections.Generic; +using System.Security.Cryptography; + +namespace DamienG.Security.Cryptography +{ + /// + /// Implements a 64-bit CRC hash algorithm for a given polynomial. + /// + /// + /// For ISO 3309 compliant 64-bit CRC's use Crc64Iso. + /// + public class Crc64 : HashAlgorithm + { + public const UInt64 DefaultSeed = 0x0; + + readonly UInt64[] table; + + readonly UInt64 seed; + UInt64 hash; + + public Crc64(UInt64 polynomial) + : this(polynomial, DefaultSeed) + { + } + + public Crc64(UInt64 polynomial, UInt64 seed) + { + table = InitializeTable(polynomial); + this.seed = hash = seed; + } + + public override void Initialize() + { + hash = seed; + } + + protected override void HashCore(byte[] array, int ibStart, int cbSize) + { + hash = CalculateHash(hash, table, array, ibStart, cbSize); + } + + protected override byte[] HashFinal() + { + var hashBuffer = UInt64ToBigEndianBytes(hash); + HashValue = hashBuffer; + return hashBuffer; + } + + public override int HashSize { get { return 64; } } + + protected static UInt64 CalculateHash(UInt64 seed, UInt64[] table, IList buffer, int start, int size) + { + var crc = seed; + + for (var i = start; i < size; i++) + unchecked + { + crc = (crc >> 8) ^ table[(buffer[i] ^ crc) & 0xff]; + } + + return crc; + } + + static byte[] UInt64ToBigEndianBytes(UInt64 value) + { + var result = BitConverter.GetBytes(value); + + if (BitConverter.IsLittleEndian) + Array.Reverse(result); + + return result; + } + + static UInt64[] InitializeTable(UInt64 polynomial) + { + if (polynomial == Crc64Iso.Iso3309Polynomial && Crc64Iso.Table != null) + return Crc64Iso.Table; + + var createTable = CreateTable(polynomial); + + if (polynomial == Crc64Iso.Iso3309Polynomial) + Crc64Iso.Table = createTable; + + return createTable; + } + + protected static ulong[] CreateTable(ulong polynomial) + { + var createTable = new UInt64[256]; + for (var i = 0; i < 256; ++i) + { + var entry = (UInt64) i; + for (var j = 0; j < 8; ++j) + if ((entry & 1) == 1) + entry = (entry >> 1) ^ polynomial; + else + entry = entry >> 1; + createTable[i] = entry; + } + return createTable; + } + } + + public class Crc64Iso : Crc64 + { + internal static UInt64[] Table; + + public const UInt64 Iso3309Polynomial = 0xD800000000000000; + + public Crc64Iso() + : base(Iso3309Polynomial) + { + } + + public Crc64Iso(UInt64 seed) + : base(Iso3309Polynomial, seed) + { + } + + public static UInt64 Compute(byte[] buffer) + { + return Compute(DefaultSeed, buffer); + } + + public static UInt64 Compute(UInt64 seed, byte[] buffer) + { + if (Table == null) + Table = CreateTable(Iso3309Polynomial); + + return CalculateHash(seed, Table, buffer, 0, buffer.Length); + } + } +} \ No newline at end of file diff --git a/excryptotools/excryptotools.csproj b/excryptotools/excryptotools.csproj new file mode 100644 index 0000000..e7d260e --- /dev/null +++ b/excryptotools/excryptotools.csproj @@ -0,0 +1,19 @@ + + + + netstandard2.0 + + + + true + + + + true + + + + + + + diff --git a/exstreamtools/Class1.cs b/exstreamtools/Class1.cs new file mode 100644 index 0000000..17ccb98 --- /dev/null +++ b/exstreamtools/Class1.cs @@ -0,0 +1,221 @@ +using System; +using System.IO; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace Tools +{ + public static class ExStreamTools + { + public static void CopyTo(this Stream input, Stream output, int buffersize, long bytes) + { + byte[] buffer = new byte[buffersize]; + int count; + while (bytes > 0L && (count = input.Read(buffer, 0, (int)Math.Min((long)buffer.Length, bytes))) > 0) + { + output.Write(buffer, 0, count); + bytes -= (long)count; + } + } + public static async Task CopyToAsync(this Stream input, Stream output, int buffersize, long bytes, CancellationToken token =default) + { + byte[] buffer = new byte[buffersize]; + int count; + while (bytes > 0L && (count = await input.ReadAsync(buffer, 0, (int)Math.Min((long)buffer.Length, bytes), token)) > 0) + { + await output.WriteAsync(buffer, 0, count, token); + bytes -= (long)count; + } + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe void WriteValueUnmanaged(this Stream s, T t) where T : unmanaged + { + byte[] buffer = new byte[sizeof(T)]; + fixed (byte* ptr = buffer) + { + *(T*)ptr = t; + } + s.Write(buffer, 0, buffer.Length); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe Task WriteValueUnmanagedAsync(this Stream s, T t, CancellationToken token = default) where T : unmanaged + { + byte[] buffer = new byte[sizeof(T)]; + fixed (byte* ptr = buffer) + { + *(T*)ptr = t; + } + return s.WriteAsync(buffer, 0, buffer.Length, token); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WriteAll(this Stream s, byte[] buffer) + { + s.Write(buffer, 0, buffer.Length); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Task WriteAllAsync(this Stream s, byte[] buffer, CancellationToken token=default) + { + return s.WriteAsync(buffer, 0, buffer.Length,token); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int ReadAll(this Stream s, byte[] buffer) + { + return s.Read(buffer, 0, buffer.Length); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Task ReadAllAsync(this Stream s, byte[] buffer, CancellationToken token = default) + { + return s.ReadAsync(buffer, 0, buffer.Length, token); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int ReadAllBlocking(this Stream s, byte[] buffer) + { + return s.BlockingRead(buffer, 0, buffer.Length); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Task ReadAllBlockingAsync(this Stream s, byte[] buffer, CancellationToken token = default) + { + return s.BlockingReadAsync(buffer, 0, buffer.Length, token); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte[] ReadNew(this Stream s, int len) + { + byte[] buffer = new byte[len]; + s.Read(buffer, 0, len); + return buffer; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task ReadNewAsync(this Stream s, int len, CancellationToken token = default) + { + byte[] buffer = new byte[len]; + await s.ReadAsync(buffer, 0, len, token); + return buffer; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte[] ReadNewBlocking(this Stream s, int len) + { + byte[] buffer = new byte[len]; + s.BlockingRead(buffer, 0, len); + return buffer; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task ReadNewBlockingAsync(this Stream s, int len, CancellationToken token = default) + { + byte[] buffer = new byte[len]; + await s.BlockingReadAsync(buffer, 0, len, token); + return buffer; + } + + public static int BlockingRead(this Stream s, byte[] buffer, int offset, int count) + { + int read; + int rlen = 0; + + while ((rlen += (read = s.Read(buffer, offset + rlen, count - rlen))) < count) if (read <= 0) break; + + return rlen; + } + public static async Task BlockingReadAsync(this Stream s, byte[] buffer, int offset, int count, CancellationToken token=default) + { + int read; + int rlen = 0; + + while ((rlen += (read = await s.ReadAsync(buffer, offset + rlen, count - rlen, token))) < count) if (read <= 0) break; + + return rlen; + } + + public static void WriteString(this Stream s, string str, Encoding encoding = null) + { + if (encoding == null) encoding = Encoding.UTF8; + + int code = encoding.CodePage; + byte[] buf = encoding.GetBytes(str); + + s.WriteValueUnmanaged(buf.Length); + s.WriteValueUnmanaged(code); + s.WriteAll(buf); + } + public static Task WriteStringAsync(this Stream s, string str, CancellationToken token = default) + => WriteStringAsync(s, str, Encoding.UTF8, token); + public static async Task WriteStringAsync(this Stream s, string str, Encoding encoding, CancellationToken token=default) + { + int code = encoding.CodePage; + byte[] buf = encoding.GetBytes(str); + + await s.WriteValueUnmanagedAsync(buf.Length, token); + await s.WriteValueUnmanagedAsync(code,token); + await s.WriteAllAsync(buf,token); + } + + public static string ReadString(this Stream s, Encoding encoding = null) + { + int len = s.ReadValueUnmanaged(); + int code = s.ReadValueUnmanaged(); + byte[] buf = s.ReadNew(len); + + if (encoding == null) + encoding = Encoding.GetEncoding(code); + + return encoding.GetString(buf); + } + public static async Task ReadStringAsync(this Stream s, CancellationToken token = default) + { + int len = await s.ReadValueUnmanagedAsync(token); + int code = await s.ReadValueUnmanagedAsync(token); + byte[] buf = await s.ReadNewAsync(len, token); + + var encoding = Encoding.GetEncoding(code); + + return encoding.GetString(buf); + } + public static async Task ReadStringAsync(this Stream s, Encoding encoding, CancellationToken token = default) + { + int len = await s.ReadValueUnmanagedAsync(token); + await s.ReadValueUnmanagedAsync(token); + byte[] buf = await s.ReadNewAsync(len, token); + + return encoding.GetString(buf); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe T ReadValueUnmanaged(this Stream s) where T : unmanaged + { + T output; + byte[] buffer = new byte[sizeof(T)]; + s.Read(buffer, 0, buffer.Length); + + fixed (byte* ptr = buffer) + { + output = *(T*)ptr; + } + + return output; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task ReadValueUnmanagedAsync(this Stream s, CancellationToken token=default) where T : unmanaged + { + T output; + int len; + unsafe + { + len = sizeof(T); + } + byte[] buffer = new byte[len]; + await s.ReadAsync(buffer, 0, buffer.Length, token); + unsafe + { + fixed (byte* ptr = buffer) + { + output = *(T*)ptr; + } + } + return output; + } + } +} diff --git a/exstreamtools/exstreamtools.csproj b/exstreamtools/exstreamtools.csproj new file mode 100644 index 0000000..1b2f99a --- /dev/null +++ b/exstreamtools/exstreamtools.csproj @@ -0,0 +1,15 @@ + + + + netstandard2.0 + + + + true + + + + true + + + diff --git a/extensions.sln b/extensions.sln new file mode 100644 index 0000000..1f755c8 --- /dev/null +++ b/extensions.sln @@ -0,0 +1,49 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29609.76 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "extensions", "extensions\extensions.csproj", "{6A440D6F-7F49-431C-89E1-61EF6C69038C}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "exbintools", "exbintools\exbintools.csproj", "{A76EB40A-3825-4225-9D63-74338BF92CAC}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "exstreamtools", "exstreamtools\exstreamtools.csproj", "{CBDB78A8-7630-4C8C-9964-E083895BD287}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "excryptotools", "excryptotools\excryptotools.csproj", "{F3FF4A85-1949-47E0-9E2B-052CF72BFA44}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "exasynctools", "exasynctools\exasynctools.csproj", "{4C54F119-650D-4939-8713-83FCA0484E3B}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {6A440D6F-7F49-431C-89E1-61EF6C69038C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6A440D6F-7F49-431C-89E1-61EF6C69038C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6A440D6F-7F49-431C-89E1-61EF6C69038C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6A440D6F-7F49-431C-89E1-61EF6C69038C}.Release|Any CPU.Build.0 = Release|Any CPU + {A76EB40A-3825-4225-9D63-74338BF92CAC}.Debug|Any CPU.ActiveCfg = Release|Any CPU + {A76EB40A-3825-4225-9D63-74338BF92CAC}.Debug|Any CPU.Build.0 = Release|Any CPU + {A76EB40A-3825-4225-9D63-74338BF92CAC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A76EB40A-3825-4225-9D63-74338BF92CAC}.Release|Any CPU.Build.0 = Release|Any CPU + {CBDB78A8-7630-4C8C-9964-E083895BD287}.Debug|Any CPU.ActiveCfg = Release|Any CPU + {CBDB78A8-7630-4C8C-9964-E083895BD287}.Debug|Any CPU.Build.0 = Release|Any CPU + {CBDB78A8-7630-4C8C-9964-E083895BD287}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CBDB78A8-7630-4C8C-9964-E083895BD287}.Release|Any CPU.Build.0 = Release|Any CPU + {F3FF4A85-1949-47E0-9E2B-052CF72BFA44}.Debug|Any CPU.ActiveCfg = Release|Any CPU + {F3FF4A85-1949-47E0-9E2B-052CF72BFA44}.Debug|Any CPU.Build.0 = Release|Any CPU + {F3FF4A85-1949-47E0-9E2B-052CF72BFA44}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F3FF4A85-1949-47E0-9E2B-052CF72BFA44}.Release|Any CPU.Build.0 = Release|Any CPU + {4C54F119-650D-4939-8713-83FCA0484E3B}.Debug|Any CPU.ActiveCfg = Release|Any CPU + {4C54F119-650D-4939-8713-83FCA0484E3B}.Debug|Any CPU.Build.0 = Release|Any CPU + {4C54F119-650D-4939-8713-83FCA0484E3B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4C54F119-650D-4939-8713-83FCA0484E3B}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {A44477E2-1912-4925-9DCB-297C07E1CE39} + EndGlobalSection +EndGlobal diff --git a/extensions/extensions.cs b/extensions/extensions.cs new file mode 100644 index 0000000..fba0c1b --- /dev/null +++ b/extensions/extensions.cs @@ -0,0 +1,2693 @@ +//#define FORMS +using Microsoft.Win32; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +#if FORMS +using System.ComponentModel; +using System.Drawing; +using System.Windows.Forms; +#endif + +namespace Tools +{ + namespace ByValStrings + { + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct ByValANSIString1 + { + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1)] + public string cstring; + + public ByValANSIString1(string c) + { + this.cstring = c; + } + + public static implicit operator ByValANSIString1(string s) + { + return new ByValANSIString1(s); + } + + public static explicit operator string(ByValANSIString1 s) + { + return s.cstring; + } + } + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct ByValANSIString2 + { + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 2)] + public string cstring; + + public ByValANSIString2(string c) + { + this.cstring = c; + } + + public static implicit operator ByValANSIString2(string s) + { + return new ByValANSIString2(s); + } + + public static explicit operator string(ByValANSIString2 s) + { + return s.cstring; + } + } + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct ByValANSIString4 + { + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 4)] + public string cstring; + + public ByValANSIString4(string c) + { + this.cstring = c; + } + + public static implicit operator ByValANSIString4(string s) + { + return new ByValANSIString4(s); + } + + public static explicit operator string(ByValANSIString4 s) + { + return s.cstring; + } + } + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct ByValANSIString8 + { + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] + public string cstring; + + public ByValANSIString8(string c) + { + this.cstring = c; + } + + public static implicit operator ByValANSIString8(string s) + { + return new ByValANSIString8(s); + } + + public static explicit operator string(ByValANSIString8 s) + { + return s.cstring; + } + } + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct ByValANSIString16 + { + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)] + public string cstring; + + public ByValANSIString16(string c) + { + this.cstring = c; + } + + public static implicit operator ByValANSIString16(string s) + { + return new ByValANSIString16(s); + } + + public static explicit operator string(ByValANSIString16 s) + { + return s.cstring; + } + } + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct ByValANSIString32 + { + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] + public string cstring; + + public ByValANSIString32(string c) + { + this.cstring = c; + } + + public static implicit operator ByValANSIString32(string s) + { + return new ByValANSIString32(s); + } + + public static explicit operator string(ByValANSIString32 s) + { + return s.cstring; + } + } + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct ByValANSIString64 + { + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)] + public string cstring; + + public ByValANSIString64(string c) + { + this.cstring = c; + } + + public static implicit operator ByValANSIString64(string s) + { + return new ByValANSIString64(s); + } + + public static explicit operator string(ByValANSIString64 s) + { + return s.cstring; + } + } + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct ByValANSIString128 + { + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] + public string cstring; + + public ByValANSIString128(string c) + { + this.cstring = c; + } + + public static implicit operator ByValANSIString128(string s) + { + return new ByValANSIString128(s); + } + + public static explicit operator string(ByValANSIString128 s) + { + return s.cstring; + } + } + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct ByValANSIString256 + { + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] + public string cstring; + + public ByValANSIString256(string c) + { + this.cstring = c; + } + + public static implicit operator ByValANSIString256(string s) + { + return new ByValANSIString256(s); + } + + public static explicit operator string(ByValANSIString256 s) + { + return s.cstring; + } + } + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct ByValANSIString512 + { + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 512)] + public string cstring; + + public ByValANSIString512(string c) + { + this.cstring = c; + } + + public static implicit operator ByValANSIString512(string s) + { + return new ByValANSIString512(s); + } + + public static explicit operator string(ByValANSIString512 s) + { + return s.cstring; + } + } + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct ByValANSIString1024 + { + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1024)] + public string cstring; + + public ByValANSIString1024(string c) + { + this.cstring = c; + } + + public static implicit operator ByValANSIString1024(string s) + { + return new ByValANSIString1024(s); + } + + public static explicit operator string(ByValANSIString1024 s) + { + return s.cstring; + } + } + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct ByValANSIString2048 + { + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 2048)] + public string cstring; + + public ByValANSIString2048(string c) + { + this.cstring = c; + } + + public static implicit operator ByValANSIString2048(string s) + { + return new ByValANSIString2048(s); + } + + public static explicit operator string(ByValANSIString2048 s) + { + return s.cstring; + } + } + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct ByValANSIString4096 + { + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 4096)] + public string cstring; + + public ByValANSIString4096(string c) + { + this.cstring = c; + } + + public static implicit operator ByValANSIString4096(string s) + { + return new ByValANSIString4096(s); + } + + public static explicit operator string(ByValANSIString4096 s) + { + return s.cstring; + } + } + } + namespace ByValData + { + namespace Special + { + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct ByValSHA1Hash + { + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 20, ArraySubType = UnmanagedType.U1)] + public byte[] data; + + public ByValSHA1Hash(byte[] c) + { + this.data = c.Pad(20); + } + + public static implicit operator ByValSHA1Hash(byte[] s) + { + return new ByValSHA1Hash(s); + } + + public static explicit operator byte[] (ByValSHA1Hash s) + { + return s.data; + } + } + } + namespace Fixed + { + namespace Special + { + public unsafe struct FixedSHA1Hash + { + public const int Size = 20; + public fixed byte data[Size]; + + public FixedSHA1Hash(byte[] from) + { + fixed (byte* p = data) + { + Marshal.Copy(from, 0, (IntPtr)p, Math.Min(Size, from.Length)); + } + } + + public static implicit operator byte[] (FixedSHA1Hash from) + { + return from.ToByteArrayUnmanaged(); + } + public static implicit operator FixedSHA1Hash(byte[] from) + { + return from.ToStructureUnmanaged(); + } + } + } + public unsafe struct FixedByteArray1 + { + public const int Size = 1; + public fixed byte data[Size]; + + public byte AsByte + { + get + { + fixed (byte* ptr = data) return *ptr; + } + set + { + fixed (byte* ptr = data) *ptr = value; + } + } + public sbyte AsSByte + { + get + { + fixed (byte* ptr = data) return *(sbyte*)ptr; + } + set + { + fixed (byte* ptr = data) *(sbyte*)ptr = value; + } + } + + public FixedByteArray1(byte asByte) + { + AsByte = asByte; + } + public FixedByteArray1(sbyte asSbyte) + { + AsSByte = asSbyte; + } + + public FixedByteArray1(byte[] from) + { + fixed (byte* p = data) + { + Marshal.Copy(from, 0,(IntPtr)p, Math.Min(Size,from.Length)); + } + } + + public static implicit operator byte[] (FixedByteArray1 from) + { + return from.ToByteArrayUnmanaged(); + } + public static implicit operator FixedByteArray1(byte[] from) + { + return from.ToStructureUnmanaged(); + } + } + public unsafe struct FixedByteArray2 + { + public const int Size = 2; + public fixed byte data[Size]; + + public short AsShort + { + get + { + fixed (byte* ptr = data) return *(short*)ptr; + } + set + { + fixed (byte* ptr = data) *(short*)ptr = value; + } + } + public ushort AsUShort + { + get + { + fixed (byte* ptr = data) return *(ushort*)ptr; + } + set + { + fixed (byte* ptr = data) *(ushort*)ptr = value; + } + } + + public char AsChar + { + get + { + fixed (byte* ptr = data) return *(char*)ptr; + } + set + { + fixed (byte* ptr = data) *(char*)ptr = value; + } + } + + public FixedByteArray2(char fromChar) + { + AsChar = fromChar; + } + public FixedByteArray2(short fromShort) + { + AsShort = fromShort; + } + public FixedByteArray2(ushort fromUshort) + { + AsUShort = fromUshort; + } + + public FixedByteArray2(byte[] from) + { + fixed (byte* p = data) + { + Marshal.Copy(from, 0, (IntPtr)p, Math.Min(Size,from.Length)); + } + } + + public static implicit operator byte[] (FixedByteArray2 from) + { + return from.ToByteArrayUnmanaged(); + } + public static implicit operator FixedByteArray2(byte[] from) + { + return from.ToStructureUnmanaged(); + } + } + public unsafe struct FixedByteArray4 + { + public const int Size = 4; + public fixed byte data[Size]; + + public int AsInt + { + get + { + fixed (byte* ptr = data) return *(int*)ptr; + } + set + { + fixed (byte* ptr = data) *(int*)ptr = value; + } + } + public uint AsUInt + { + get + { + fixed (byte* ptr = data) return *(uint*)ptr; + } + set + { + fixed (byte* ptr = data) *(uint*)ptr = value; + } + } + + public bool AsBool + { + get + { + fixed (byte* ptr = data) return *(bool*)ptr; + } + set + { + fixed (byte* ptr = data) *(bool*)ptr = value; + } + } + public float AsFloat + { + get + { + fixed (byte* ptr = data) return *(float*)ptr; + } + set + { + fixed (byte* ptr = data) *(float*)ptr = value; + } + } + + public FixedByteArray4(float fromFloat) + { + AsFloat = fromFloat; + } + public FixedByteArray4(bool fromBool) + { + AsBool = fromBool; + } + public FixedByteArray4(int fromInt) + { + AsInt = fromInt; + } + public FixedByteArray4(uint fromUint) + { + AsUInt = fromUint; + } + + public FixedByteArray4(byte[] from) + { + fixed (byte* p = data) + { + Marshal.Copy(from, 0, (IntPtr)p, Math.Min(Size,from.Length)); + } + } + + public static implicit operator byte[] (FixedByteArray4 from) + { + return from.ToByteArrayUnmanaged(); + } + public static implicit operator FixedByteArray4(byte[] from) + { + return from.ToStructureUnmanaged(); + } + } + public unsafe struct FixedByteArray8 + { + public const int Size = 8; + public fixed byte data[Size]; + + public long AsLong + { + get + { + fixed (byte* ptr = data) return *(long*)ptr; + } + set + { + fixed (byte* ptr = data) *(long*)ptr = value; + } + } + public ulong AsULong + { + get + { + fixed (byte* ptr = data) return *(ulong*)ptr; + } + set + { + fixed (byte* ptr = data) *(ulong*)ptr = value; + } + } + + public double AsDouble + { + get + { + fixed (byte* ptr = data) return *(double*)ptr; + } + set + { + fixed (byte* ptr = data) *(double*)ptr = value; + } + } + + public FixedByteArray8(double asDouble) + { + AsDouble = asDouble; + } + public FixedByteArray8(ulong asUlong) + { + AsULong = asUlong; + } + public FixedByteArray8(long asLong) + { + AsLong = asLong; + } + + public FixedByteArray8(byte[] from) + { + fixed (byte* p = data) + { + Marshal.Copy(from, 0, (IntPtr)p, Math.Min(Size,from.Length)); + } + } + + public static implicit operator byte[] (FixedByteArray8 from) + { + return from.ToByteArrayUnmanaged(); + } + public static implicit operator FixedByteArray8(byte[] from) + { + return from.ToStructureUnmanaged(); + } + } + public unsafe struct FixedByteArray16 + { + public const int Size = 16; + public fixed byte data[Size]; + + public decimal AsDecimal + { + get + { + fixed (byte* ptr = data) return *(decimal*)ptr; + } + set + { + fixed (byte* ptr = data) *(decimal*)ptr = value; + } + } + + public FixedByteArray16(decimal from) + { + AsDecimal = from; + } + + public FixedByteArray16(byte[] from) + { + fixed (byte* p = data) + { + Marshal.Copy(from, 0, (IntPtr)p, Math.Min(Size,from.Length)); + } + } + + public static implicit operator byte[] (FixedByteArray16 from) + { + return from.ToByteArrayUnmanaged(); + } + public static implicit operator FixedByteArray16(byte[] from) + { + return from.ToStructureUnmanaged(); + } + } + public unsafe struct FixedByteArray32 + { + public const int Size = 32; + public fixed byte data[Size]; + + public FixedByteArray32(byte[] from) + { + fixed (byte* p = data) + { + Marshal.Copy(from, 0, (IntPtr)p, Math.Min(Size,from.Length)); + } + } + + public static implicit operator byte[] (FixedByteArray32 from) + { + return from.ToByteArrayUnmanaged(); + } + public static implicit operator FixedByteArray32(byte[] from) + { + return from.ToStructureUnmanaged(); + } + } + public unsafe struct FixedByteArray64 + { + public const int Size = 64; + public fixed byte data[Size]; + + public FixedByteArray64(byte[] from) + { + fixed (byte* p = data) + { + Marshal.Copy(from, 0, (IntPtr)p, Math.Min(Size,from.Length)); + } + } + + public static implicit operator byte[] (FixedByteArray64 from) + { + return from.ToByteArrayUnmanaged(); + } + public static implicit operator FixedByteArray64(byte[] from) + { + return from.ToStructureUnmanaged(); + } + } + + public unsafe struct FixedByteArray128 + { + public const int Size = 128; + public fixed byte data[Size]; + + public FixedByteArray128(byte[] from) + { + fixed (byte* p = data) + { + Marshal.Copy(from, 0, (IntPtr)p, Math.Min(Size,from.Length)); + } + } + + public static implicit operator byte[] (FixedByteArray128 from) + { + return from.ToByteArrayUnmanaged(); + } + public static implicit operator FixedByteArray128(byte[] from) + { + return from.ToStructureUnmanaged(); + } + } + public unsafe struct FixedByteArray256 + { + public const int Size = 128; + public fixed byte data[Size]; + + public FixedByteArray256(byte[] from) + { + fixed (byte* p = data) + { + Marshal.Copy(from, 0, (IntPtr)p, Math.Min(Size,from.Length)); + } + } + + public static implicit operator byte[] (FixedByteArray256 from) + { + return from.ToByteArrayUnmanaged(); + } + public static implicit operator FixedByteArray256(byte[] from) + { + return from.ToStructureUnmanaged(); + } + } + public unsafe struct FixedByteArray512 + { + public const int Size = 512; + public fixed byte data[Size]; + + public FixedByteArray512(byte[] from) + { + fixed (byte* p = data) + { + Marshal.Copy(from, 0, (IntPtr)p, Math.Min(Size,from.Length)); + } + } + + public static implicit operator byte[] (FixedByteArray512 from) + { + return from.ToByteArrayUnmanaged(); + } + public static implicit operator FixedByteArray512(byte[] from) + { + return from.ToStructureUnmanaged(); + } + } + public unsafe struct FixedByteArray1024 + { + public const int Size = 1024; + public fixed byte data[Size]; + + public FixedByteArray1024(byte[] from) + { + fixed (byte* p = data) + { + Marshal.Copy(from, 0, (IntPtr)p, Math.Min(Size,from.Length)); + } + } + + public static implicit operator byte[] (FixedByteArray1024 from) + { + return from.ToByteArrayUnmanaged(); + } + public static implicit operator FixedByteArray1024(byte[] from) + { + return from.ToStructureUnmanaged(); + } + } + public unsafe struct FixedByteArray2048 + { + public const int Size = 2048; + public fixed byte data[Size]; + + public FixedByteArray2048(byte[] from) + { + fixed (byte* p = data) + { + Marshal.Copy(from, 0, (IntPtr)p, Math.Min(Size,from.Length)); + } + } + + public static implicit operator byte[] (FixedByteArray2048 from) + { + return from.ToByteArrayUnmanaged(); + } + public static implicit operator FixedByteArray2048(byte[] from) + { + return from.ToStructureUnmanaged(); + } + } + public unsafe struct FixedByteArray4096 + { + public const int Size = 4096; + public fixed byte data[Size]; + + public FixedByteArray4096(byte[] from) + { + fixed (byte* p = data) + { + Marshal.Copy(from, 0, (IntPtr)p, Math.Min(Size,from.Length)); + } + } + + public static implicit operator byte[] (FixedByteArray4096 from) + { + return from.ToByteArrayUnmanaged(); + } + public static implicit operator FixedByteArray4096(byte[] from) + { + return from.ToStructureUnmanaged(); + } + } + + } + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct ByValFixedByteArray1 + { + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1, ArraySubType = UnmanagedType.U1)] + public byte[] data; + + public ByValFixedByteArray1(byte[] c) + { + this.data = c.Pad(1); + } + + public static implicit operator ByValFixedByteArray1(byte[] s) + { + return new ByValFixedByteArray1(s); + } + + public static explicit operator byte[] (ByValFixedByteArray1 s) + { + return s.data; + } + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct ByValFixedByteArray2 + { + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2, ArraySubType = UnmanagedType.U1)] + public byte[] data; + + public ByValFixedByteArray2(byte[] c) + { + this.data = c.Pad(2); + } + + public static implicit operator ByValFixedByteArray2(byte[] s) + { + return new ByValFixedByteArray2(s); + } + + public static explicit operator byte[] (ByValFixedByteArray2 s) + { + return s.data; + } + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct ByValFixedByteArray4 + { + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4, ArraySubType = UnmanagedType.U1)] + public byte[] data; + + public ByValFixedByteArray4(byte[] c) + { + this.data = c.Pad(4); + } + + public static implicit operator ByValFixedByteArray4(byte[] s) + { + return new ByValFixedByteArray4(s); + } + + public static explicit operator byte[] (ByValFixedByteArray4 s) + { + return s.data; + } + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct ByValFixedByteArray8 + { + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8, ArraySubType = UnmanagedType.U1)] + public byte[] data; + + public ByValFixedByteArray8(byte[] c) + { + this.data = c.Pad(8); + } + + public static implicit operator ByValFixedByteArray8(byte[] s) + { + return new ByValFixedByteArray8(s); + } + + public static explicit operator byte[] (ByValFixedByteArray8 s) + { + return s.data; + } + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct ByValFixedByteArray16 + { + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16, ArraySubType = UnmanagedType.U1)] + public byte[] data; + + public ByValFixedByteArray16(byte[] c) + { + this.data = c.Pad(16); + } + + public static implicit operator ByValFixedByteArray16(byte[] s) + { + return new ByValFixedByteArray16(s); + } + + public static explicit operator byte[] (ByValFixedByteArray16 s) + { + return s.data; + } + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct ByValFixedByteArray32 + { + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32, ArraySubType = UnmanagedType.U1)] + public byte[] data; + + public ByValFixedByteArray32(byte[] c) + { + this.data = c.Pad(32); + } + + public static implicit operator ByValFixedByteArray32(byte[] s) + { + return new ByValFixedByteArray32(s); + } + + public static explicit operator byte[] (ByValFixedByteArray32 s) + { + return s.data; + } + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct ByValFixedByteArray64 + { + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 64, ArraySubType = UnmanagedType.U1)] + public byte[] data; + + public ByValFixedByteArray64(byte[] c) + { + this.data = c.Pad(64); + } + + public static implicit operator ByValFixedByteArray64(byte[] s) + { + return new ByValFixedByteArray64(s); + } + + public static explicit operator byte[] (ByValFixedByteArray64 s) + { + return s.data; + } + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct ByValFixedByteArray128 + { + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 128, ArraySubType = UnmanagedType.U1)] + public byte[] data; + + public ByValFixedByteArray128(byte[] c) + { + this.data = c.Pad(128); + } + + public static implicit operator ByValFixedByteArray128(byte[] s) + { + return new ByValFixedByteArray128(s); + } + + public static explicit operator byte[] (ByValFixedByteArray128 s) + { + return s.data; + } + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct ByValFixedByteArray256 + { + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256, ArraySubType = UnmanagedType.U1)] + public byte[] data; + + public ByValFixedByteArray256(byte[] c) + { + this.data = c.Pad(256); + } + + public static implicit operator ByValFixedByteArray256(byte[] s) + { + return new ByValFixedByteArray256(s); + } + + public static explicit operator byte[] (ByValFixedByteArray256 s) + { + return s.data; + } + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct ByValFixedByteArray512 + { + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 512, ArraySubType = UnmanagedType.U1)] + public byte[] data; + + public ByValFixedByteArray512(byte[] c) + { + this.data = c.Pad(512); + } + + public static implicit operator ByValFixedByteArray512(byte[] s) + { + return new ByValFixedByteArray512(s); + } + + public static explicit operator byte[] (ByValFixedByteArray512 s) + { + return s.data; + } + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct ByValFixedByteArray1024 + { + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1024, ArraySubType = UnmanagedType.U1)] + public byte[] data; + + public ByValFixedByteArray1024(byte[] c) + { + this.data = c.Pad(1024); + } + + public static implicit operator ByValFixedByteArray1024(byte[] s) + { + return new ByValFixedByteArray1024(s); + } + + public static explicit operator byte[] (ByValFixedByteArray1024 s) + { + return s.data; + } + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct ByValFixedByteArray2048 + { + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2048, ArraySubType = UnmanagedType.U1)] + public byte[] data; + + public ByValFixedByteArray2048(byte[] c) + { + this.data = c.Pad(2048); + } + + public static implicit operator ByValFixedByteArray2048(byte[] s) + { + return new ByValFixedByteArray2048(s); + } + + public static explicit operator byte[] (ByValFixedByteArray2048 s) + { + return s.data; + } + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct ByValFixedByteArray4096 + { + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4096, ArraySubType = UnmanagedType.U1)] + public byte[] data; + + public ByValFixedByteArray4096(byte[] c) + { + this.data = c.Pad(4096); + } + + public static implicit operator ByValFixedByteArray4096(byte[] s) + { + return new ByValFixedByteArray4096(s); + } + + public static explicit operator byte[] (ByValFixedByteArray4096 s) + { + return s.data; + } + } + + + + } + + public static class Extensions + { + public static void Shuffle(this T[] t, Random r) + { + int num = ((IEnumerable)t).Count(); + for (int i = num - 1; i > 0; --i) + t.Swap(i, r.Next(0, num - 1)); + } + + public static void Forget(this Task task, Action exceptionHandler = null) + { + if (exceptionHandler != null) + task.ContinueWith(t => exceptionHandler(t.Exception), TaskContinuationOptions.OnlyOnFaulted); + } + + public static void Swap(this T[] t, int i, int j) + { + T obj = t[i]; + t[i] = t[j]; + t[j] = obj; + } + + public static IEnumerable RemoveDuplicates(this IEnumerable t) + { + List objList = new List(); + foreach (T obj in t) + { + if (!objList.Contains(obj)) + objList.Add(obj); + } + return (IEnumerable)objList.ToArray(); + } + + public static bool ContainsAny(this string t, string[] o) + { + foreach (string str in o) + { + if (t.Contains(str)) + return true; + } + return false; + } + + public static bool AllValidTypes(this object[] objs, params Type[] t) + { + if (objs.Length != t.Length) + return false; + for (int index = 0; index < objs.Length; ++index) + { + if (!objs[index].GetType().Equals(t[index])) + return false; + } + return true; + } + + public static void Shred(this FileInfo fi) + { + fi.Shred(true); + } + + public static void Shred(this FileInfo fi, bool delete) + { + fi.Shred(delete, 3); + } + + public static void Shred(this FileInfo fi, bool delete, int passes) + { + fi.Shred(delete, passes, 4096L); + } + + public static double ToUnixTime(this DateTime d) + { + return (d.ToUniversalTime() - new DateTime(1970, 1, 1).ToUniversalTime()).TotalSeconds; + } + + public static void Shred(this FileInfo fi, bool delete, int passes, long bufsize) + { + FileStream fileStream = fi.Open(FileMode.Open); + RNGCryptoServiceProvider cryptoServiceProvider = new RNGCryptoServiceProvider(); + for (int index = 0; index < passes; ++index) + { + byte[] numArray = new byte[bufsize]; + fileStream.Position = 0L; + long num = 0; + while (num < fileStream.Length) + { + cryptoServiceProvider.GetBytes(numArray); + fileStream.Write(numArray, 0, (int)bufsize); + num += bufsize; + } + } + cryptoServiceProvider.Dispose(); + fileStream.Close(); + if (!delete) + return; + fi.Delete(); + } + + public static void CopyTo(this Stream input, Stream output, int buffersize, long bytes) + { + byte[] buffer = new byte[buffersize]; + int count; + while (bytes > 0L && (count = input.Read(buffer, 0, (int)Math.Min((long)buffer.Length, bytes))) > 0) + { + output.Write(buffer, 0, count); + bytes -= (long)count; + } + } + + public static byte[] CreateZeroMemory(this Type t) + { + if (t.IsValueType) + return new byte[Marshal.SizeOf(t)]; + throw new ArgumentException("Object is not value type"); + } + public static object ZeroMemory(this Type t) + { + byte[] zeroMemory = t.CreateZeroMemory(); + Marshal.SizeOf(t); + GCHandle gcHandle = GCHandle.Alloc((object)zeroMemory, GCHandleType.Pinned); + object structure = Marshal.PtrToStructure(gcHandle.AddrOfPinnedObject(), t); + gcHandle.Free(); + return Convert.ChangeType(structure, t); + + } + + public static byte[] SHA1Hash(this byte[] by) + { + SHA1 shA1 = SHA1.Create(); + byte[] hash = shA1.ComputeHash(by); + shA1.Dispose(); + return hash; + } + + public static T[] SingleArray(this T t) + { + return new T[1] { t }; + } + + public static T[] Pad(this T[] t, int l) + { + T[] objArray = new T[l]; + for (int index = 0; index < t.Length && index < l; ++index) + objArray[index] = t[index]; + return objArray; + } + + public static unsafe byte[] ToByteArrayUnmanaged(this T t) where T : unmanaged + { + byte[] o = new byte[sizeof(T)]; + fixed (byte* ptr = o) + { + *(T*)ptr = t; + } + return o; + } + private static Dictionary cachedTypes = + new Dictionary(); + public static bool IsUnmanaged(this Type t) + { + var result = false; + if (cachedTypes.ContainsKey(t)) + return cachedTypes[t]; + else if (t.IsPrimitive || t.IsPointer || t.IsEnum) + result = true; + else if (t.IsGenericType || !t.IsValueType) + result = false; + else + result = t.GetFields(BindingFlags.Public | + BindingFlags.NonPublic | BindingFlags.Instance) + .All(x => x.FieldType.IsUnmanaged()); + cachedTypes.Add(t, result); + return result; + } + public static unsafe int SizeOfUnsafe(this T t) where T : struct + { + Type type = typeof(T); + + TypeCode typeCode = Type.GetTypeCode(type); + switch (typeCode) + { + case TypeCode.Boolean: + return sizeof(bool); + case TypeCode.Char: + return sizeof(char); + case TypeCode.SByte: + return sizeof(sbyte); + case TypeCode.Byte: + return sizeof(byte); + case TypeCode.Int16: + return sizeof(short); + case TypeCode.UInt16: + return sizeof(ushort); + case TypeCode.Int32: + return sizeof(int); + case TypeCode.UInt32: + return sizeof(uint); + case TypeCode.Int64: + return sizeof(long); + case TypeCode.UInt64: + return sizeof(ulong); + case TypeCode.Single: + return sizeof(float); + case TypeCode.Double: + return sizeof(double); + case TypeCode.Decimal: + return sizeof(decimal); + case TypeCode.DateTime: + return sizeof(DateTime); + default: + T[] tArray = new T[2]; + GCHandle tArrayPinned = GCHandle.Alloc(tArray, GCHandleType.Pinned); + try + { + TypedReference tRef0 = __makeref(tArray[0]); + TypedReference tRef1 = __makeref(tArray[1]); + IntPtr ptrToT0 = *((IntPtr*)&tRef0); + IntPtr ptrToT1 = *((IntPtr*)&tRef1); + + return (int)(((byte*)ptrToT1) - ((byte*)ptrToT0)); + } + finally + { + tArrayPinned.Free(); + } + } + } + public static int SizeOf(this T t, bool managed=false) where T : struct + { + if (managed && typeof(T).IsUnmanaged()) unsafe { return t.SizeOfUnsafe(); } + else + { + return Marshal.SizeOf(typeof(T)); + } + } + public static unsafe T ToStructureUnmanaged(this byte[] bytes) where T : unmanaged + { +#if DEBUG + if (sizeof(T) > bytes.Length) throw new IndexOutOfRangeException(nameof(bytes) + " does not have enough space for type " + typeof(T) + " (" + sizeof(T) + " bytes required, only given " + bytes.Length + ")"); +#endif + fixed (byte* ptr = bytes) + { + return *(T*)ptr; + } + } + [DllImport("kernel32.dll", EntryPoint = "CopyMemory", SetLastError = false)] + public static extern void CopyMemory(IntPtr dest, IntPtr src, uint count); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte[] ToByteArray(this T t) where T : struct + { + var type = typeof(T); + if (type.IsPrimitive || type.IsUnmanaged()) + { + unsafe + { + TypedReference valueref = __makeref(t); + byte* valuePtr = (byte*)*((IntPtr*)&valueref); + var sz = Marshal.SizeOf(type); + + byte[] output = new byte[sz]; + fixed (byte* outPtr = output) + { + CopyMemory(new IntPtr(outPtr), new IntPtr(valuePtr), (uint)sz); + } + return output; + } + } + else + { + byte[] numArray = new byte[Marshal.SizeOf(typeof(T))]; + GCHandle gcHandle = GCHandle.Alloc((object)numArray, GCHandleType.Pinned); + Marshal.StructureToPtr((object)t, gcHandle.AddrOfPinnedObject(), true); + gcHandle.Free(); + return numArray; + } + } + + public static T ToStructure(this byte[] bytes) where T : struct + { + return bytes.ToStructure(0); + } + + public static unsafe void* Pointer(ref this T value) where T:struct + { + return __makeref(value).Pointer(); + } + public static IntPtr IntPtr(ref this T value) where T : struct + { + unsafe { return (IntPtr)value.Pointer(); } + } + + public static unsafe void* Pointer(this TypedReference _ref) + { + return (void*)*((IntPtr*)&_ref); + } + + public static IntPtr IntPtr(this TypedReference _ref) + { + unsafe + { + return (IntPtr)_ref.Pointer(); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T ToStructure(this byte[] bytes, int offset) where T : struct + { + if (offset >= bytes.Length) throw new IndexOutOfRangeException("ToStructure<" + typeof(T) + ">: "+nameof(offset) + "(" + offset + ") is larger than " + nameof(bytes) + "'s size (" + bytes.Length + ")"); + var type = typeof(T); + if (type == typeof(byte)) + { + return (T)(object)bytes[0]; + } + else if (type.IsPrimitive || type.IsUnmanaged()) + { + T output = default; + unsafe + { + TypedReference valueref = __makeref(output); + byte* outPtr = (byte*)*((IntPtr*)&valueref); + var sz = Marshal.SizeOf(type); + fixed (byte* inputPtr = bytes) + { + byte* rptr = inputPtr + offset; + CopyMemory(new IntPtr(outPtr), new IntPtr(rptr), Math.Min((uint)sz, (uint)bytes.Length)); + } + return output; + } + } + else + { + GCHandle gcHandle = GCHandle.Alloc((object)bytes, GCHandleType.Pinned); + T structure = (T)Marshal.PtrToStructure(gcHandle.AddrOfPinnedObject() + offset, type); + gcHandle.Free(); + return structure; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WriteValue(this Stream s, T t) where T : struct + { + byte[] byteArray = t.ToByteArray(); + s.Write(byteArray, 0, byteArray.Length); + } + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe void WriteValueUnmanaged(this Stream s, T t) where T : unmanaged + { + byte[] buffer = new byte[sizeof(T)]; + fixed (byte* ptr = buffer) + { + *(T*)ptr = t; + } + s.Write(buffer, 0, buffer.Length); + } + + public static byte[] ReadNew(this Stream s, int len) + { + byte[] buffer = new byte[len]; + s.Read(buffer, 0, len); + return buffer; + } + + public static T[] PadWith(this T[] t, int len, Func selector) + { + return Enumerable.Range(0, len).Select((Func)(x => + { + if (x < t.Length) + return t[x]; + return selector(x); + })).ToArray(); + } + + public static byte[] EncodeToByteArray(this string s, Encoding e) + { + return e.GetBytes(s); + } + + public static byte[] EncodeToByteArray(this string s) + { + return s.EncodeToByteArray(Encoding.ASCII); + } + + public static string DecodeToString(this byte[] byt, Encoding e) + { + return e.GetString(byt); + } + + public static string DecodeToString(this byte[] byt) + { + return byt.DecodeToString(Encoding.ASCII); + } + + public static bool ElementsEqual(this T[] ar, T[] o, int len) + { + return ar.ElementsEqual(o, 0, len); + } + + public static bool ElementsEqual(this T[] ar, T[] o, int offset, int len) + { + return ar.ElementsEqual(o, offset, offset, len); + } + + public static void FillMemory(this T[] input, T with = default) where T : unmanaged + { + unsafe + { + if (typeof(T) == typeof(byte)) + { + fixed (T* ip = input) + { + byte c = *(byte*)&with; + MemSet((IntPtr)ip, c, input.Length); + } + } + else + { + fixed (T* ip = input) + { + T* ptr = ip; + while (ptr < (ip + input.Length)) + { + *ptr++ = with; + } + } + + } + } + } + [DllImport("msvcrt.dll", EntryPoint = "memset", CallingConvention = CallingConvention.Cdecl, SetLastError = false)] + public static extern IntPtr MemSet(IntPtr dest, int c, int count); + public static void ZeroMemory(this T obj) where T : unmanaged + { + unsafe + { + MemSet((IntPtr)(&obj), 0, sizeof(T)); + } + } + public static void Fill(this T[] input, T with = default) + { + for (int i = 0; i < input.Length; i++) input[i] = with; + } + + public static IEnumerable ConcatAll(this IEnumerable t) + { + foreach (T[] objArray in t) + { + foreach (T obj in objArray) + yield return obj; + } + } + + public static T[] SubArray(this T[] ar, long index) + { + return ar.SubArray(index, ar.Length - index); + } + + public static T[] SubArray(this T[] ar, long index, long length) + { + T[] objArray = new T[length]; + for (int index1 = 0; index1 < length; ++index1) + objArray[index1] = ar[index + index1]; + return objArray; + } + + public static bool ElementsEqual(this T[] ar, T[] o, int of1, int of2, int len) + { + for (int index = 0; index < len; ++index) + { + if (!ar[of1 + index].Equals((object)o[of2 + index])) + return false; + } + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T ReadValue(this Stream s) where T : struct + { + int len = Marshal.SizeOf(typeof(T)); + return s.ReadNew(len).ToStructure(); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe T ReadValueUnmanaged(this Stream s) where T : unmanaged + { + T output; + byte[] buffer = new byte[sizeof(T)]; + s.Read(buffer, 0, buffer.Length); + + fixed (byte* ptr = buffer) + { + output = *(T*)ptr; + } + + return output; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WriteAll(this Stream s, byte[] by) + { + s.Write(by, 0, by.Length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int ReadAll(this Stream s, byte[] by) + { + return s.Read(by, 0, by.Length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static string Hex(this byte[] byt) + { + return BitConverter.ToString(byt).Replace("-", ""); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte[] UnHex(this string s) + { + return Enumerable.Range(0, s.Length).Where((Func)(x => x % 2 == 0)).Select((Func)(x => Convert.ToByte(s.Substring(x, 2)))).ToArray(); + } + } + //TODO: Fix this + public class UniqueRandom + { + private int _shufflePasses = 1; + private Random rand; + private byte[] ar; + private int i; + private int ent; + + public bool AutoReset { get; set; } + + public int ShufflePasses + { + get + { + return this._shufflePasses; + } + set + { + if (value < 1) + throw new ArgumentOutOfRangeException("Cannot shuffle less than once"); + this._shufflePasses = value; + } + } + + public UniqueRandom(int entropy, int seed) + { + this.ent = entropy; + this.rand = new Random(seed); + this.setup(true); + this.intsu(); + } + + public UniqueRandom(int entropy) + { + this.ent = entropy; + this.rand = new Random(); + this.setup(true); + this.intsu(); + } + + public UniqueRandom() + : this(256) + { + } + + public UniqueRandom(byte[] entropy, int seed) + { + this.ent = entropy.Length; + this.rand = new Random(seed); + this.ar = new byte[this.ent]; + entropy.CopyTo((Array)this.ar, 0); + this.i = 0; + this.ar.Shuffle(this.rand); + this.intsu(); + } + + public UniqueRandom(byte[] entropy) + { + this.ent = entropy.Length; + this.rand = new Random(); + this.ar = new byte[this.ent]; + entropy.CopyTo((Array)this.ar, 0); + this.i = 0; + this.ar.Shuffle(this.rand); + this.intsu(); + } + + protected virtual void intsu() + { + this.AutoReset = false; + } + + public static int TimeSeed + { + get + { + long binary = DateTime.Now.ToBinary(); + int[] numArray = new int[2] + { + binary.ToByteArray().SubArray(0, 4).ToStructure(), + binary.ToByteArray().SubArray(4, 4).ToStructure() + }; + return numArray[0] ^ numArray[1]; + } + } + + private void setup(bool fresh) + { + if (fresh) + this.ar = Enumerable.Range(0, this.ent).Select((Func)(x => (byte)x)).ToArray(); + if (this.ShufflePasses > 1) + Help.DoX((Action)(() => this.ar.Shuffle(this.rand)), this.ShufflePasses); + else + this.ar.Shuffle(this.rand); + this.i = 0; + } + + public void Reset() + { + this.setup(false); + } + + public int Left + { + get + { + return this.ent - this.i; + } + } + + public byte NextByte() + { + if (this.i < this.ar.Length) + return this.ar[this.i++]; + if (!this.AutoReset) + throw new NotEnoughEntropyException(this.ent, this.i); + this.setup(false); + return this.NextByte(); + } + + public void NextBytes(byte[] fil) + { + for (int index = 0; index < fil.Length; ++index) + fil[index] = this.NextByte(); + } + + public byte[] NextNewBytes(int i) + { + byte[] fil = new byte[i]; + this.NextBytes(fil); + return fil; + } + + public T NextStructure() where T : struct + { + byte[] zeroMemory = typeof(T).CreateZeroMemory(); + this.NextBytes(zeroMemory); + return zeroMemory.ToStructure(); + } + } + public class NotEnoughEntropyException : Exception + { + public NotEnoughEntropyException(int ent, int req) + : base("Out of entropy (had " + (object)ent + ", requested " + (object)req) + { + } + } + + public static class Help + { + public static void Crash() + { + System.Runtime.Serialization.FormatterServices.GetUninitializedObject(typeof(Type).GetType()).ToString(); + } + public static int PROGRESS_SIZE = 50; + + public static void DoX(Action a, int t) + { + for (int index = 0; index < t; ++index) + a(); + } + + public static void Progress(double s, double l) + { + double num1 = s / l; + double num2 = num1 * 100.0; + Console.Write("\r["); + for (int index = 0; index < Help.PROGRESS_SIZE; ++index) + { + if ((double)index < (double)Help.PROGRESS_SIZE * num1) + Console.Write("="); + else + Console.Write(" "); + } + Console.Write("]: " + num2.ToString("##0.00") + "% "); + } + + /// + /// Start a task for action. + /// + public static System.Threading.Tasks.Task Go(Action a) + { + var ts = new System.Threading.Tasks.Task(a); + ts.Start(); + return ts; + } + + /// + /// Start a thread for action. + /// + public static Thread Spawn(Action a) + { + Thread t = new Thread(() => a()); + t.Start(); + return t; + } + + public static void ClearProgress() + { + Console.Write("\r" + new string(' ', Console.WindowWidth - 1) + "\r"); + } +#if FORMS + public static void ErrMsg(string text, string title) + { + int num = (int)MessageBox.Show(text, title, MessageBoxButtons.OK, MessageBoxIcon.Hand); + } +#endif + } + + public class GCHPinned : IDisposable + { + private GCHandle handle; + + public IntPtr Pointer + { + get + { + return this.handle.AddrOfPinnedObject(); + } + } + + public GCHPinned(GCHandle h) + { + this.handle = h; + } + + public GCHPinned(object o) + : this(GCHandle.Alloc(o, GCHandleType.Pinned)) + { + } + + public void Dispose() + { + this.handle.Free(); + } + + public static implicit operator IntPtr(GCHPinned p) + { + return p.Pointer; + } + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct BitField + { + private byte b; + + public bool fieldn(int n, bool? val) + { + if (!val.HasValue) + return ((int)this.b & 1 << n) != 0; + if (val.Value != this.fieldn(n, new bool?())) + this.b ^= (byte)(1 << n); + return val.Value; + } + + public bool Field0 + { + get + { + return this.fieldn(0, new bool?()); + } + set + { + this.fieldn(0, new bool?(value)); + } + } + + public bool Field1 + { + get + { + return this.fieldn(1, new bool?()); + } + set + { + this.fieldn(1, new bool?(value)); + } + } + + public bool Field2 + { + get + { + return this.fieldn(2, new bool?()); + } + set + { + this.fieldn(2, new bool?(value)); + } + } + + public bool Field3 + { + get + { + return this.fieldn(3, new bool?()); + } + set + { + this.fieldn(3, new bool?(value)); + } + } + + public bool Field4 + { + get + { + return this.fieldn(4, new bool?()); + } + set + { + this.fieldn(4, new bool?(value)); + } + } + + public bool Field5 + { + get + { + return this.fieldn(5, new bool?()); + } + set + { + this.fieldn(5, new bool?(value)); + } + } + + public bool Field6 + { + get + { + return this.fieldn(6, new bool?()); + } + set + { + this.fieldn(6, new bool?(value)); + } + } + + public bool Field7 + { + get + { + return this.fieldn(7, new bool?()); + } + set + { + this.fieldn(7, new bool?(value)); + } + } + + public bool this[int n] + { + get + { + return this.fieldn(n, new bool?()); + } + set + { + this.fieldn(n, new bool?(value)); + } + } + } + + public class AsyncSchedulerTaskHandleUnhandledExceptionEventArgs : EventArgs + { + public AsyncSchedulerTaskException Exception { get; private set; } + + public AsyncSchedulerTaskHandleUnhandledExceptionEventArgs(AsyncSchedulerTaskException ex) + { + this.Exception = ex; + } + } + public class AsyncSchedulerTaskException : Exception + { + public Thread CallingThread { get; set; } + + public AsyncSchedulerTaskException(Exception e, Thread t, string message) + : base(message, e) + { + this.CallingThread = t; + } + } + public class AsyncScheduler : IDisposable + { + public static int AllowedJoinTimeOnDispose = 100; + public const int NO_MAX = -1; + private bool disposed; + private List threads; + private Thread collector; + + public int MaxTasks { get; set; } + + public AsyncScheduler(int max) + { + this.MaxTasks = max; + this.threads = new List(); + this.collector = new Thread(new ThreadStart(this.collect)); + this.collector.Start(); + } + + public AsyncScheduler() + : this(-1) + { + } + + private void no_param(object o) + { + ((ThreadStart)o)(); + } + + private void param(object o) + { + ParameterizedThreadStart parameterizedThreadStart = (ParameterizedThreadStart)((object[])o)[0]; + object obj = ((object[])o)[1]; + try + { + parameterizedThreadStart(obj); + } + catch (Exception ex) + { + this.raiseUEEvent(new AsyncSchedulerTaskException(ex, Thread.CurrentThread, "Exception (" + ex.GetBaseException().GetType().Name + ") on thread (" + (Thread.CurrentThread.Name ?? "(unbound)") + "): " + ex.Message)); + } + } + + protected virtual void raiseUEEvent(AsyncSchedulerTaskException e) + { + if (this.OnUnhandledException == null) + throw e; + this.OnUnhandledException((object)this, new AsyncSchedulerTaskHandleUnhandledExceptionEventArgs(e)); + } + + public event AsyncScheduler.UnhandledExceptionOnThreadHandler OnUnhandledException; + + private void collect() + { + while (!this.disposed) + { + lock (this.threads) + { + for (int index = 0; index < this.threads.Count; ++index) + { + if (this.threads[index] != null && !this.threads[index].IsAlive) + this.threads[index] = (Thread)null; + } + this.threads.RemoveAll((Predicate)(x => x == null)); + } + Thread.Sleep(500); + } + } + + public Thread RunTask(AsyncScheduler.GenericParameterisedAsyncStart pts, T o) + { + return this.RunTask((ThreadStart)(() => pts(o))); + } + + public Thread RunTask(ParameterizedThreadStart pts, object o) + { + lock (this.threads) + { + if (this.MaxTasks != -1 && this.threads.Count >= this.MaxTasks) + return (Thread)null; + Thread thread = new Thread(new ParameterizedThreadStart(this.param)); + this.threads.Add(thread); + thread.Start((object)new object[2] + { + (object) pts, + o + }); + return thread; + } + } + + public Thread RunTask(ThreadStart ts) + { + return this.RunTask(new AsyncScheduler.GenericParameterisedAsyncStart(this.no_param), ts); + } + + public void Dispose() + { + this.disposed = true; + if (!this.collector.Join(550)) + this.collector.Abort(); + foreach (Thread thread in this.threads) + { + if (thread != null && thread.IsAlive && !thread.Join(AsyncScheduler.AllowedJoinTimeOnDispose)) + thread.Abort(); + } + this.threads.Clear(); + } + + public void Purge(bool instant) + { + lock (this.threads) + { + foreach (Thread thread in this.threads) + { + if (thread != null && thread.IsAlive && (instant || !thread.Join(AsyncScheduler.AllowedJoinTimeOnDispose))) + thread.Abort(); + } + this.threads.Clear(); + } + } + + public void Purge() + { + this.Purge(false); + } + + public void JoinAll(int timeout) + { + lock (this.threads) + { + foreach (Thread thread in this.threads) + { + if (thread != null && thread.IsAlive && !thread.Join(timeout)) + thread.Abort(); + } + this.threads.Clear(); + } + } + + public void JoinAll() + { + lock (this.threads) + { + foreach (Thread thread in this.threads) + { + if (thread != null && thread.IsAlive) + thread.Join(); + } + this.threads.Clear(); + } + } + + public delegate void GenericParameterisedAsyncStart(T param); + + public delegate void UnhandledExceptionOnThreadHandler(object sender, AsyncSchedulerTaskHandleUnhandledExceptionEventArgs eventArgs); + } + + public class ArrayBuilder + { + private List list; + + public ArrayBuilder() + { + this.list = new List(); + } + + public ArrayBuilder Append(T[] ar) + { + this.list.Add(ar); + return this; + } + + public ArrayBuilder Append(T[][] arar) + { + this.list.Add(((IEnumerable)arar).ConcatAll().ToArray()); + return this; + } + + public ArrayBuilder Append(T single) + { + this.list.Add(new T[1] { single }); + return this; + } + + public T[] ToArray() + { + return ((IEnumerable)this.list.ToArray()).ConcatAll().ToArray(); + } + + public override bool Equals(object obj) + { + if (obj is ArrayBuilder) + { + if (this.Length == (obj as ArrayBuilder).Length) + return this.ToArray().ElementsEqual((obj as ArrayBuilder).ToArray(), this.Length); + } + else if (obj is T[] && this.Length == (obj as T[]).Length) + return this.ToArray().ElementsEqual(obj as T[], this.Length); + return obj.Equals((object)this); + } + + public override int GetHashCode() + { + return this.ToArray().GetHashCode(); + } + + public int Length + { + get + { + return this.list.Select((Func)(x => x.Length)).Sum(); + } + } + } + + public class ArgHelper + { + private static bool _d_groupString = false; + private static bool _d_anyCase = true; + private List handles = new List(); + + public static bool SetDefaultGroupString(bool? value) + { + if (!value.HasValue) + return ArgHelper._d_groupString; + return ArgHelper._d_groupString = value.Value; + } + + public static bool SetDefaultAnyCase(bool? value) + { + if (!value.HasValue) + return ArgHelper._d_anyCase; + return ArgHelper._d_anyCase = value.Value; + } + + public ArgHelper(params ArgHelper.ArgHandle[] ags) + { + this.Add(ags); + } + + public ArgHelper Add(params ArgHelper.ArgHandle[] ars) + { + this.handles.AddRange((IEnumerable)ars); + return this; + } + + public ArgHelper Reset() + { + foreach (ArgHelper.ArgHandle handle in this.handles) + handle.Reset(); + return this; + } + + public ArgHelper Parse(string[] args) + { + for (int i = 0; i < args.Length; ++i) + { + List stringList = new List(); + for (int index = 0; index < this.handles.Count && (!this.handles[index].GroupString || !stringList.Contains(this.handles[index].Argument)); ++index) + { + if (this.handles[index].AttemptHandle(args, i)) + { + stringList.Add(this.handles[index].Argument); + i += this.handles[index].Requires; + break; + } + } + } + return this; + } + + public static ArgHelper CreateObj(params object[][] o) + { + List argHandleList = new List(); + foreach (object[] objs in o) + { + if (!objs.AllValidTypes(typeof(string), typeof(int), typeof(ArgHelper.ArgHandler))) + throw new ArgumentException("Invalid Format"); + argHandleList.Add(new ArgHelper.ArgHandle(objs[0] as string, (int)objs[1], objs[2] as ArgHelper.ArgHandler)); + } + return new ArgHelper(argHandleList.ToArray()); + } + + public static ArgHelper Create(params object[] o) + { + if (o.Length % 3 != 0) + throw new ArgumentException("Invalid Format"); + List objArrayList = new List(); + int index = 0; + while (index < o.Length) + { + objArrayList.Add(o.SubArray(index, 3)); + index += 3; + } + return ArgHelper.CreateObj(objArrayList.ToArray()); + } + + public delegate bool ArgHandler(string[] args, int index); + + public class ArgHandle + { + public string Argument { get; set; } + + public int Requires { get; set; } + + public ArgHelper.ArgHandler Handle { get; set; } + + public bool Handled { get; private set; } + + public ArgHandle(string str, int left, ArgHelper.ArgHandler handle) + { + this.GroupString = ArgHelper._d_groupString; + this.AnyCase = ArgHelper._d_anyCase; + this.Argument = str; + this.Requires = left; + this.Handle = handle; + this.Handled = false; + } + + public bool AttemptHandle(string[] ar, int i) + { + int length = ar.Length; + if (i < 0 || i >= length || (this.Handled || length - (i + 1) < this.Requires) || (this.AnyCase ? (this.Argument.ToLower().Equals(ar[i].ToLower()) ? 1 : 0) : (this.Argument.Equals(ar[i]) ? 1 : 0)) == 0) + return false; + this.Handled = true; + return this.Handle(ar, i); + } + + public void Reset() + { + this.Handled = false; + } + + public bool GroupString { get; set; } + + public bool AnyCase { get; set; } + + public override string ToString() + { + return this.Argument + "(" + (object)this.Requires + ")"; + } + } + } + + + +#if FORMS + namespace Forms + { + public static class FormBackgroundWorker + { + public static void DoWork(FormBackgroundWorker.ParameterisedWorkerAction a, object arg, string m, bool mq) + { + BackgroundWorker backgroundWorker = new BackgroundWorker(); + backgroundWorker.DoWork += new DoWorkEventHandler(FormBackgroundWorker.bg_DoWork); + backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(FormBackgroundWorker.bg_RunWorkerCompleted); + WorkingForm workingForm = new WorkingForm(m, mq ? -1 : 0); + backgroundWorker.RunWorkerAsync((object)new object[3] + { + (object) workingForm, + (object) a, + arg + }); + int num = (int)workingForm.ShowDialog(); + backgroundWorker.Dispose(); + } + + public static void DoWork(FormBackgroundWorker.ParameterisedWorkerAction a, object arg, string m, bool mq, bool allowCancel) + { + BackgroundWorker backgroundWorker = new BackgroundWorker(); + backgroundWorker.DoWork += new DoWorkEventHandler(FormBackgroundWorker.bg_DoWork); + backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(FormBackgroundWorker.bg_RunWorkerCompleted); + WorkingForm workingForm = new WorkingForm(m, mq ? -1 : 0); + workingForm.AllowCancel = allowCancel; + backgroundWorker.RunWorkerAsync((object)new object[3] + { + (object) workingForm, + (object) a, + arg + }); + int num = (int)workingForm.ShowDialog(); + backgroundWorker.Dispose(); + } + + public static void DoWork(FormBackgroundWorker.ParameterisedWorkerAction a, object arg, string m, bool mq, bool allowCancel, IWin32Window parent) + { + BackgroundWorker backgroundWorker = new BackgroundWorker(); + backgroundWorker.DoWork += new DoWorkEventHandler(FormBackgroundWorker.bg_DoWork); + backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(FormBackgroundWorker.bg_RunWorkerCompleted); + WorkingForm workingForm = new WorkingForm(m, mq ? -1 : 0); + workingForm.AllowCancel = allowCancel; + backgroundWorker.RunWorkerAsync((object)new object[3] + { + (object) workingForm, + (object) a, + arg + }); + int num = (int)workingForm.ShowDialog(parent); + backgroundWorker.Dispose(); + } + + public static void DoWork(FormBackgroundWorker.ParameterisedWorkerAction a, object arg, string m, bool mq, IWin32Window parent) + { + BackgroundWorker backgroundWorker = new BackgroundWorker(); + backgroundWorker.DoWork += new DoWorkEventHandler(FormBackgroundWorker.bg_DoWork); + backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(FormBackgroundWorker.bg_RunWorkerCompleted); + WorkingForm workingForm = new WorkingForm(m, mq ? -1 : 0); + backgroundWorker.RunWorkerAsync((object)new object[3] + { + (object) workingForm, + (object) a, + arg + }); + int num = (int)workingForm.ShowDialog(parent); + backgroundWorker.Dispose(); + } + + private static void bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) + { + WorkingForm result = (WorkingForm)e.Result; + result.Stop(); + result.Close(); + result.Dispose(); + } + + private static void bg_DoWork(object sender, DoWorkEventArgs e) + { + object[] objArray = (object[])e.Argument; + WorkingForm wf = (WorkingForm)objArray[0]; + ((FormBackgroundWorker.ParameterisedWorkerAction)objArray[1])(wf, objArray[2]); + e.Result = (object)wf; + } + + public delegate void ParameterisedWorkerAction(WorkingForm wf, object param); + } + + public class WorkingForm : Form + { + private string sm; + private string smc; + private volatile int progress; + private bool cancelCalled; + private IContainer components; + private Label label1; + private Label label2; + private ProgressBar progressBar1; + private Label label3; + private System.Windows.Forms.Timer timer1; + private Button button1; + + public string Message + { + get + { + return this.label2.Text; + } + set + { + this.label2.Text = value; + } + } + + public WorkingForm(string msg, int startP) + { + this.sm = msg; + this.progress = startP; + this.InitializeComponent(); + } + + public int Progress + { + get + { + return this.progress; + } + set + { + this.progress = value; + } + } + + public bool AllowCancel + { + get + { + return this.button1.Visible; + } + set + { + this.button1.Visible = value; + } + } + + private void WorkingForm_Load(object sender, EventArgs e) + { + this.Message = this.sm; + this.setProgress(this.progress); + this.Start(); + } + + private void Start() + { + this.timer1.Start(); + } + + public void Stop() + { + this.timer1.Stop(); + } + + public void SetMessage(string s) + { + this.smc = s; + } + + public void SetProgress(double small, double large) + { + this.Progress = (int)Math.Floor(small / large * 100.0); + } + + private void setProgress(int p) + { + if (p >= 0) + { + if (this.progressBar1.Style != ProgressBarStyle.Blocks) + this.progressBar1.Style = ProgressBarStyle.Blocks; + if (this.progressBar1.MarqueeAnimationSpeed != 0) + this.progressBar1.MarqueeAnimationSpeed = 0; + this.progressBar1.Value = p; + this.label3.Text = p.ToString() + "%"; + } + else + { + if (this.progressBar1.Value != 10) + this.progressBar1.Value = 10; + if (this.progressBar1.Style != ProgressBarStyle.Marquee) + this.progressBar1.Style = ProgressBarStyle.Marquee; + if (this.progressBar1.MarqueeAnimationSpeed != 100) + this.progressBar1.MarqueeAnimationSpeed = 100; + switch (this.label3.Text) + { + case "|": + this.label3.Text = "/"; + break; + case "/": + this.label3.Text = "-"; + break; + case "-": + this.label3.Text = "\\"; + break; + default: + this.label3.Text = "|"; + break; + } + } + } + + private void timer1_Tick(object sender, EventArgs e) + { + this.setProgress(this.progress); + if (this.smc == null) + return; + this.Message = this.smc; + this.smc = (string)null; + } + + public bool CancelCalled() + { + return this.cancelCalled; + } + + private void button1_Click(object sender, EventArgs e) + { + this.cancelCalled = true; + } + + protected override void Dispose(bool disposing) + { + if (disposing && this.components != null) + this.components.Dispose(); + base.Dispose(disposing); + } + + private void InitializeComponent() + { + this.components = (IContainer)new Container(); + this.label1 = new Label(); + this.label2 = new Label(); + this.progressBar1 = new ProgressBar(); + this.label3 = new Label(); + this.timer1 = new System.Windows.Forms.Timer(this.components); + this.button1 = new Button(); + this.SuspendLayout(); + this.label1.AutoSize = true; + this.label1.Location = new Point(12, 34); + this.label1.Name = "label1"; + this.label1.Size = new Size(36, 13); + this.label1.TabIndex = 0; + this.label1.Text = "Done:"; + this.label2.AutoSize = true; + this.label2.Location = new Point(12, 9); + this.label2.Name = "label2"; + this.label2.Size = new Size(55, 13); + this.label2.TabIndex = 1; + this.label2.Text = "(unbound)"; + this.progressBar1.Location = new Point(54, 34); + this.progressBar1.Name = "progressBar1"; + this.progressBar1.Size = new Size(182, 13); + this.progressBar1.TabIndex = 2; + this.label3.AutoSize = true; + this.label3.Location = new Point(242, 34); + this.label3.Name = "label3"; + this.label3.Size = new Size(63, 13); + this.label3.TabIndex = 3; + this.label3.Text = "(unbound)%"; + this.timer1.Tick += new EventHandler(this.timer1_Tick); + this.button1.Location = new Point(199, 4); + this.button1.Name = "button1"; + this.button1.Size = new Size(75, 23); + this.button1.TabIndex = 4; + this.button1.Text = "Cancel"; + this.button1.UseVisualStyleBackColor = true; + this.button1.Visible = false; + this.button1.Click += new EventHandler(this.button1_Click); + this.AutoScaleDimensions = new SizeF(6f, 13f); + this.AutoScaleMode = AutoScaleMode.Font; + this.ClientSize = new Size(286, 51); + this.ControlBox = false; + this.Controls.Add((Control)this.button1); + this.Controls.Add((Control)this.label3); + this.Controls.Add((Control)this.progressBar1); + this.Controls.Add((Control)this.label2); + this.Controls.Add((Control)this.label1); + this.FormBorderStyle = FormBorderStyle.FixedSingle; + this.MaximizeBox = false; + this.MinimizeBox = false; + this.Name = nameof(WorkingForm); + this.ShowIcon = false; + this.StartPosition = FormStartPosition.CenterParent; + this.Text = "Working"; + this.Load += new EventHandler(this.WorkingForm_Load); + this.ResumeLayout(false); + this.PerformLayout(); + } + } + } +#endif + } \ No newline at end of file diff --git a/extensions/extensions.csproj b/extensions/extensions.csproj new file mode 100644 index 0000000..797c21e --- /dev/null +++ b/extensions/extensions.csproj @@ -0,0 +1,15 @@ + + + + netcoreapp3.1 + + + + true + + + + true + + +