├── .editorconfig ├── .gitattributes ├── .gitignore ├── LICENSE.md ├── NStandard.Analyzer ├── MeasureGenerator.cs └── NStandard.Analyzer.csproj ├── NStandard.Caching └── NStandard.Caching.csproj ├── NStandard.Compress ├── NStandard.Compress.csproj ├── ZipStream.StaticDataSource.cs ├── ZipStream.UpdateScope.cs └── ZipStream.cs ├── NStandard.Debug ├── NStandard.Debug.csproj └── ObjectExtensions.cs ├── NStandard.Dev ├── AnyDev.Func.cs ├── BitStream.cs ├── ConvertEx.Base32Converter.cs ├── Data │ └── Mathematics │ │ ├── IMathFunction.cs │ │ ├── MathBinary.cs │ │ ├── MathConstant.cs │ │ ├── MathLambda.cs │ │ ├── MathNodeType.cs │ │ └── MathSqrt.cs ├── Obsolete │ ├── Evaluator.cs │ ├── NowOffsetScope.cs │ ├── NowOffsetScopeAccessor.cs │ ├── NowScope.cs │ ├── NowScopeAccessor.cs │ ├── NumericalEvaluator.cs │ ├── NumericalRTEvaluator.cs │ └── Reference │ │ ├── GAC.cs │ │ └── GACFolders.cs ├── Threading │ ├── Cron.cs │ ├── CronFieldType.cs │ └── Scheduler.cs └── [NoRelease] NStandard.Dev.csproj ├── NStandard.Diagnostics ├── Concurrency.cs ├── NStandard.Diagnostics.csproj ├── TestId.cs ├── TestReport.cs └── TestResult.cs ├── NStandard.Encoding ├── EncodingEx.cs └── NStandard.Encoding.csproj ├── NStandard.Json.Net ├── Converters │ ├── DateOnlyConverter.cs │ ├── IPAddressConverter.cs │ ├── LazyConverter.cs │ ├── PhysicalAddressConverter.cs │ └── VariantConverter.cs ├── NStandard.Json.Net.csproj └── README.md ├── NStandard.Json ├── Converters │ ├── DateOnlyConverter.cs │ ├── IPAddressConverter.cs │ ├── LazyConverter.cs │ ├── NetDoubleConverter.cs │ ├── NetSingleConverter.cs │ ├── PhysicalAddressConverter.cs │ └── VariantConverter.cs ├── NStandard.Json.csproj └── README.md ├── NStandard.Runtime ├── AssemblyContext.cs ├── DotNetFramework.cs ├── NStandard.Runtime.csproj └── SdkType.cs ├── NStandard.Trees ├── AvlTree.cs ├── BinaryNodeType.cs ├── NStandard.Trees.csproj └── OldTree.cs ├── NStandard.Windows ├── Doc2Code.tt ├── Doc2Code.txt ├── NStandard - Backup.Windows.csproj ├── NStandard.Windows.csproj ├── Native │ ├── Service │ │ ├── NativeMethods.cs │ │ ├── SERVICE_DESCRIPTIONW.cs │ │ ├── ScmRights.cs │ │ ├── ServiceConfigInfoLevel.cs │ │ ├── ServiceControls.cs │ │ ├── ServiceErrorControl.cs │ │ ├── ServiceRights.cs │ │ ├── ServiceStartType.cs │ │ ├── ServiceState.cs │ │ ├── ServiceStatus.cs │ │ └── ServiceType.cs │ └── Types │ │ └── GenericRights.cs ├── ShellProcess.cs └── WindowsService.cs ├── NStandard.lutconfig ├── NStandard.sln ├── NStandard ├── !Any │ ├── Any.Chain.cs │ ├── Any.Compose.cs │ ├── Any.Flat.cs │ ├── Any.Forward.cs │ ├── Any.ReDim.cs │ ├── Any.Struct.cs │ ├── Any.Text.cs │ ├── Any.Zip.cs │ ├── Any.Zip.tt │ └── Any.cs ├── !Design │ ├── ISliceCount.cs │ └── ISliceLength.cs ├── !DotNet │ └── System │ │ ├── Collections │ │ ├── IStructuralComparable.cs │ │ └── IStructuralEquatable.cs │ │ ├── FormattableString.cs │ │ ├── HashCode.cs │ │ ├── Reflection │ │ └── CustomAttributeExtensions.cs │ │ ├── Runtime │ │ └── CompilerServices │ │ │ ├── FormattableStringFactory.cs │ │ │ └── ITuple.cs │ │ ├── SR - partial.cs │ │ ├── Security │ │ └── Cryptography │ │ │ ├── HashAlgorithmName.cs │ │ │ ├── Oids.cs │ │ │ ├── RSAEncryptionPadding.cs │ │ │ ├── RSAEncryptionPaddingMode.cs │ │ │ ├── RSASignaturePadding.cs │ │ │ └── RSASignaturePaddingMode.cs │ │ └── Tuple.cs ├── !Extensions │ ├── AppDomainExtensions.cs │ ├── ArrayExtensions - Jagged - ToMultiple.cs │ ├── ArrayExtensions - Jagged.cs │ ├── ArrayExtensions - Multiple - ToJagged.cs │ ├── ArrayExtensions.Deconstruct.cs │ ├── ArrayExtensions.Deconstruct.tt │ ├── ArrayExtensions.Each.cs │ ├── ArrayExtensions.IndexOf.cs │ ├── ArrayExtensions.Let.cs │ ├── ArrayExtensions.Locate.cs │ ├── ArrayExtensions.Select.cs │ ├── ArrayExtensions.String.cs │ ├── ArrayExtensions.cs │ ├── CharExtensions.cs │ ├── DateOnlyExtensions.cs │ ├── DateTimeExtensions.cs │ ├── DateTimeOffsetExtensions.cs │ ├── DelegateExtensions.cs │ ├── EnumExtensions.cs │ ├── FuncExtensions.cs │ ├── IDisposeableExtension.cs │ ├── Int32Extensions.cs │ ├── Int64Extensions.cs │ ├── ObjectExtensions.cs │ ├── SpanExtensions.cs │ ├── SpanExtensions.tt │ ├── StringExtensions.cs │ ├── System.Collections │ │ ├── Generic │ │ │ └── LinkedListExtensions.cs │ │ └── IEnumerableExtensions.cs │ ├── System.Drawing │ │ └── ColorExtensions.cs │ ├── System.IO │ │ ├── Compression │ │ │ └── ZipFileExtensions.cs │ │ └── StreamExtensions.cs │ ├── System.Net │ │ └── IPAddressExtensions.cs │ ├── System.Text │ │ ├── Json │ │ │ └── JsonElementExtensions.cs │ │ └── StringBuilderExtensions.cs │ ├── System.Threading.Tasks │ │ └── TaskExtensions.cs │ ├── SystemReflection │ │ ├── AssemblyExtensions.cs │ │ ├── EventInfoExtensions.cs │ │ ├── ICustomAttributeProviderExtensions.cs │ │ └── PropertyInfoExtensions.cs │ ├── TimeOnlyExtensions.cs │ ├── TypeExtensions.cs │ ├── UInt32Extensions.cs │ └── UInt64Extensions.cs ├── !Static │ ├── ArrayEx.cs │ ├── BitConverterEx.cs │ ├── Collections │ │ └── Generic │ │ │ └── EnumerableEx.cs │ ├── ConvertEx.Base58Converter.cs │ ├── ConvertEx.cs │ ├── DateOnlyEx.cs │ ├── DateTimeEx.cs │ ├── DateTimeOffsetEx.cs │ ├── Drawing │ │ └── ColorEx.cs │ ├── EnumEx.cs │ ├── GuidEx.cs │ ├── Linq │ │ └── Expressions │ │ │ └── ExpressionExtensions.cs │ ├── MathEx.Ceiling.cs │ ├── MathEx.Ceiling.tt │ ├── MathEx.Combin.cs │ ├── MathEx.Combin.tt │ ├── MathEx.Floor.cs │ ├── MathEx.Floor.tt │ ├── MathEx.Permut.cs │ ├── MathEx.Permut.tt │ ├── MathEx.cs │ ├── Net │ │ └── IPAddressEx.cs │ ├── ObjectEx.cs │ ├── RangeEx.cs │ ├── Reflection │ │ └── MethodInfoEx.cs │ ├── StringEx.cs │ └── TypeEx.cs ├── !internal │ ├── ArrayMapper.cs │ ├── BitOperations.cs │ ├── ExceptionResource.cs │ ├── Flater.cs │ └── IndicesStepper.cs ├── Algorithm │ ├── PatternSearcher.cs │ ├── SnowflakeWorker.cs │ └── SnowflakeWorker128.cs ├── Caching │ ├── !Delegates.cs │ ├── Cache.cs │ └── CacheSet.cs ├── ChainOrigin.cs ├── Collections │ ├── ArrayVisitor.cs │ ├── Counter.cs │ ├── FixedSizeQueue.cs │ ├── HashMap.cs │ ├── Interval.cs │ ├── Sequence.cs │ ├── Sliding.cs │ └── SlidingMode.cs ├── ConsoleContext.cs ├── Converts │ ├── BytesConvert.cs │ └── StringConvert.cs ├── Data │ ├── DataFrame.cs │ ├── Fraction.cs │ ├── Moment.cs │ └── MomentType.cs ├── DataBinding │ ├── IDiff.cs │ └── ValueDiff.cs ├── DateMode.cs ├── DateOnlyType.cs ├── DateTimeType.cs ├── Design │ └── ObsoleteMessage.cs ├── Discards.cs ├── DpContainer.cs ├── Drawing │ └── RgbaColor.cs ├── Dynamic.cs ├── EnumOption.cs ├── Evaluators │ ├── Bracket.cs │ ├── Evaluator.cs │ ├── Node.cs │ ├── NodeType.cs │ └── NumericalEvaluator.cs ├── Flows │ ├── BytesFlow.cs │ ├── GuidFlow.cs │ ├── HashFlow.cs │ ├── IPAddressFlow.cs │ ├── NumberFlow.cs │ └── StringFlow.cs ├── FuncDelegates.cs ├── IO │ └── SequenceInputStream.cs ├── ISingleton.cs ├── Infrastructure │ └── ChainIterator.cs ├── Linq │ └── DependencyCollector.cs ├── Lock.cs ├── Locks │ ├── InstanceLockParser.cs │ └── TypeLockParser.cs ├── Measures │ ├── IMeasurable.cs │ ├── IMeasureConvertible.cs │ ├── IMeasureExtensions.cs │ └── MeasureAttribute.cs ├── MinMaxPair.cs ├── NStandard.csproj ├── Native.cs ├── Ref.cs ├── Reflection │ ├── FieldReflector.cs │ ├── MethodReflector.cs │ ├── PropertyReflector.cs │ ├── Reflector.cs │ ├── TypeFieldReflector.cs │ ├── TypeMethodReflector.cs │ ├── TypePropertyReflector.cs │ └── TypeReflector.cs ├── ResourceAccessor.cs ├── Schema │ ├── Loop.cs │ └── LoopFor.cs ├── Scope.cs ├── Security │ ├── !Asymmetric │ │ ├── !internal │ │ │ ├── PemNode.cs │ │ │ └── RsaConverter.cs │ │ └── RsaProvider.cs │ ├── !Hash │ │ ├── Md5Hasher.cs │ │ └── Sha1Hasher.cs │ └── !Symmetric │ │ ├── AesCipher.cs │ │ ├── AesProvider.cs │ │ ├── DesCipher.cs │ │ ├── DesProvider.cs │ │ ├── SymmetricCipher.cs │ │ ├── SymmetricProvider.cs │ │ ├── TripleDesCipher.cs │ │ └── TripleDesProvider.cs ├── Snowflake.cs ├── State.cs ├── StructTuple.cs ├── StructTuple.tt ├── Text │ └── Json │ │ ├── Converters │ │ ├── JsonAsConverter.cs │ │ ├── JsonImplConverter.cs │ │ └── JsonValueConverter.cs │ │ ├── IJsonValue.cs │ │ ├── JsonAsAttribute.cs │ │ ├── JsonImplAttribute.cs │ │ ├── JsonValueAttribute.cs │ │ └── JsonXmlSerializer.cs ├── TimePointValue.cs ├── Trees │ ├── BinaryTree.cs │ ├── IBinaryTree.cs │ ├── ITreeVisitable.cs │ ├── Tree.cs │ └── TreeNode.cs ├── UnitValues │ ├── ISummable.cs │ ├── IUnitValue.cs │ └── IUnitValueExtensions.cs ├── Usable.cs ├── Usings.cs ├── Val.cs ├── ValueTuples │ └── IndexAndValue.cs ├── Variant.cs └── YearWeekPair.cs ├── README.md ├── README.zh.md ├── Tests ├── NStandard.NET45.Test │ ├── FormattableStringTests.cs │ ├── HashCodeTests.cs │ ├── IntervalTests.cs │ ├── NStandard.NET45.Test.csproj │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── TupleTests.cs │ └── packages.config └── NStandard.Test │ ├── !Extensions │ ├── !System.Collections │ │ └── !Generic │ │ │ └── LinkedListExtensionsTests.cs │ ├── !System.Net │ │ └── IPAddressExtensionsTests.cs │ ├── !System.Reflection │ │ └── EventInfoExtensionsTests.cs │ ├── !System.Threading │ │ └── !Tasks │ │ │ └── TaskExtensionsTests.cs │ ├── AppDomainExtensionsTests.cs │ ├── ArrayExtensionsTests.cs │ ├── AssemblyExtensionsTests.cs │ ├── DateTimeExtensionsTests.cs │ ├── ObjectExtensionsTests.cs │ ├── StringExtensionsTests.cs │ └── TypeExtensionsTests.cs │ ├── !FeatureTests.cs │ ├── !Static │ ├── ArrayExTests.cs │ ├── Collections │ │ └── Generic │ │ │ └── EnumerableExTests.cs │ ├── ConvertExTests.cs │ ├── Drawing │ │ └── ColorExTests.cs │ ├── EnumExTests.cs │ ├── GuidEx.cs │ ├── Linq │ │ └── Expressions │ │ │ └── ExpressionExTests.cs │ ├── MathExTests.cs │ ├── ObjectExTests.cs │ ├── RangeExTests.cs │ ├── Reflection │ │ └── MethodInfoExTests.cs │ └── StringExTests.cs │ ├── !data-structures │ ├── IntClass.cs │ └── IntStrcut.cs │ ├── !extern │ ├── IEnumerableExtensions.MaxOrDefault.cs │ ├── IEnumerableExtensions.WhereMax.cs │ └── IEnumerableExtensions.WhereMin.cs │ ├── AnyTests.cs │ ├── ArrayVisitorTests.cs │ ├── CacheContainerTests.cs │ ├── CacheTests.cs │ ├── ChainPropertyTests.cs │ ├── Collections │ ├── CounterTests.cs │ ├── FixedSizeQueueTests.cs │ ├── HashMapTests.cs │ ├── IntervalTests.cs │ └── SequnceTests.cs │ ├── ConsoleContextTests.cs │ ├── Data │ ├── FractionTests.cs │ ├── MathFunctionTests.cs │ └── MomentTests.cs │ ├── DateTimeExTests.cs │ ├── DpContainerTests - DpCoin.cs │ ├── DpContainerTests - DpFib.cs │ ├── DpContainerTests - DpKnapsacks.cs │ ├── DpContainerTests - DpLIS.cs │ ├── Drawing │ └── RgbaColorTests.cs │ ├── DynamicTests.cs │ ├── EnumOptionTests.cs │ ├── Evaluators │ └── NumberEvaluatorTests.cs │ ├── Flows │ ├── GuidFlowTests.cs │ ├── IPAddressFlowTests.cs │ └── StringFlowTests.cs │ ├── IO │ └── SequenceInputStreamTests.cs │ ├── ISliceTests.cs │ ├── Json │ ├── DateOnlyTests.cs │ ├── JsonTests.cs │ ├── NetAddressTests.cs │ ├── UnderlyingTests.cs │ └── VariantTests.cs │ ├── Locks │ ├── InstanceLockTest.cs │ └── TypeLockTest.cs │ ├── Measures │ ├── LengthTests.cs │ ├── StorageCapacityTests.cs │ └── WeightTests.cs │ ├── NStandard.Test.csproj │ ├── RefTests.cs │ ├── Reference │ └── DotNetFrameworkTests.cs │ ├── ReflectorTests.cs │ ├── RuntimeTests.cs │ ├── Schema │ ├── LoopForTests.cs │ └── LoopTests.cs │ ├── ScopeTests.cs │ ├── Security │ └── ProviderTests.cs │ ├── SingletonTests.cs │ ├── SlidingTests.cs │ ├── SnowflakeTests.cs │ ├── SpanExtensionsTests.cs │ ├── StateTests.cs │ ├── StructTupleTests.cs │ ├── Text │ └── Json │ │ ├── JsonImplConverterTests.cs │ │ └── JsonXmlSerializerTests.cs │ ├── Threading │ └── CronTests.cs │ ├── TimePointValueTests.cs │ ├── Trees │ ├── AvlTreeTests.cs │ ├── BinaryTreeConstructor.cs │ ├── BinaryTreeTests.cs │ └── TreeTests.cs │ ├── UsableTests.cs │ ├── ValTests.cs │ └── VariantTests.cs ├── docs ├── cn │ ├── Any.Chain.md │ ├── Any.Flat.md │ ├── Any.Forward.md │ ├── Any.ReDim.md │ ├── Any.Zip.md │ ├── ArrayExtensions.md │ ├── Compatibility.md │ ├── DateTimeExtensions.md │ ├── DpContainer.md │ ├── Evaluator.md │ ├── SequenceInputStream.md │ ├── State.md │ └── UnitValue.md ├── en │ ├── Any.Chain.md │ ├── Any.Flat.md │ ├── Any.Forward.md │ ├── Any.ReDim.md │ ├── Any.Zip.md │ ├── ArrayExtensions.md │ ├── Compatibility.md │ ├── DateTimeExtensions.md │ ├── DpContainer.md │ ├── Evaluator.md │ ├── SequenceInputStream.md │ ├── State.md │ └── UnitValue.md └── images │ ├── State-001.png │ ├── State-002.png │ ├── State-003.png │ ├── State-004.png │ ├── State-005.png │ ├── State-006.png │ ├── image-20221227131745251.png │ ├── image-20221227134222183.png │ └── image-20221227134321883.png ├── nstandard.png ├── push.cmd └── testEnvironments.json /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 zmjack 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /NStandard.Caching/NStandard.Caching.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | NStandard 6 | DotNet Core extensions for system library. 7 | zmjack 8 | LICENSE.md 9 | https://github.com/zmjack/NStandard 10 | https://github.com/zmjack/NStandard 11 | git 12 | System Standard Extension 13 | 0.5.0 14 | false 15 | nstandard.png 16 | Copyright © nstandard.net 2020 17 | NStandard.Caching 18 | 19 | 20 | 21 | 22 | True 23 | 24 | 25 | 26 | True 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /NStandard.Compress/NStandard.Compress.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | net5.0;net6.0;net7.0; 6 | netstandard2.0;netstandard2.1; 7 | net451;net452;net46;net461;net462;net47;net471;net472;net48; 8 | 9 | preview 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /NStandard.Compress/ZipStream.StaticDataSource.cs: -------------------------------------------------------------------------------- 1 | using ICSharpCode.SharpZipLib.Zip; 2 | using System.IO; 3 | 4 | namespace Dawnx.Compress; 5 | 6 | public partial class ZipStream 7 | { 8 | private class StaticDataSource : IStaticDataSource 9 | { 10 | private readonly Stream StoredStream; 11 | 12 | public StaticDataSource(Stream stream) 13 | { 14 | StoredStream = stream; 15 | } 16 | 17 | public Stream GetSource() => StoredStream; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /NStandard.Compress/ZipStream.UpdateScope.cs: -------------------------------------------------------------------------------- 1 | using NStandard; 2 | 3 | namespace Dawnx.Compress; 4 | 5 | public partial class ZipStream 6 | { 7 | public class UpdateScope : Scope 8 | { 9 | public readonly ZipStream Model; 10 | 11 | public UpdateScope(ZipStream model) 12 | { 13 | Model = model; 14 | Model.ZipFile.BeginUpdate(); 15 | } 16 | 17 | public override void Disposing() 18 | { 19 | Model.ZipFile.CommitUpdate(); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /NStandard.Debug/NStandard.Debug.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard2.0 5 | preview 6 | 7 | 8 | 9 | none 10 | false 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /NStandard.Dev/Data/Mathematics/IMathFunction.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Data.Mathematics; 2 | 3 | public interface IMathFunction 4 | { 5 | public MathNodeType NodeType { get; } 6 | public string GetText(); 7 | } 8 | -------------------------------------------------------------------------------- /NStandard.Dev/Data/Mathematics/MathBinary.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | 3 | namespace NStandard.Data.Mathematics; 4 | 5 | [DebuggerDisplay("{GetText()}")] 6 | public class MathBinary : IMathFunction 7 | { 8 | public MathNodeType NodeType { get; } 9 | public IMathFunction Left { get; } 10 | public IMathFunction Right { get; } 11 | 12 | public static readonly MathNodeType[] ValidNodes = [MathNodeType.Add, MathNodeType.Subtract, MathNodeType.Multiply, MathNodeType.Divide]; 13 | 14 | public MathBinary(MathNodeType type, IMathFunction left, IMathFunction right) 15 | { 16 | if (type == MathNodeType.Add) NodeType = MathNodeType.Add; 17 | else if (type == MathNodeType.Subtract) NodeType = MathNodeType.Subtract; 18 | else if (type == MathNodeType.Multiply) NodeType = MathNodeType.Multiply; 19 | else if (type == MathNodeType.Divide) NodeType = MathNodeType.Divide; 20 | else throw new NotImplementedException(); 21 | 22 | Left = left; 23 | Right = right; 24 | } 25 | 26 | public string GetText() 27 | { 28 | return NodeType switch 29 | { 30 | MathNodeType.Add => $"{Left.GetText()} + {Right.GetText()}", 31 | MathNodeType.Subtract => $"{Left.GetText()} - {Right.GetText()}", 32 | MathNodeType.Multiply => $"{Left.GetText()} · {Right.GetText()}", 33 | MathNodeType.Divide => $"{Left.GetText()} / {Right.GetText()}", 34 | _ => throw new NotImplementedException(), 35 | }; 36 | } 37 | 38 | public override string ToString() 39 | { 40 | return GetText(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /NStandard.Dev/Data/Mathematics/MathNodeType.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Data.Mathematics; 2 | 3 | public enum MathNodeType 4 | { 5 | None, 6 | Constant, 7 | Lambda, 8 | 9 | Add, 10 | Subtract, 11 | Multiply, 12 | Divide, 13 | 14 | Sqrt, 15 | } 16 | -------------------------------------------------------------------------------- /NStandard.Dev/Data/Mathematics/MathSqrt.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | 3 | namespace NStandard.Data.Mathematics; 4 | 5 | [DebuggerDisplay("{GetText()}")] 6 | public class MathSqrt : IMathFunction 7 | { 8 | public MathNodeType NodeType => MathNodeType.Sqrt; 9 | 10 | public IMathFunction Constant { get; } 11 | public int Value { get; } 12 | 13 | public MathSqrt(IMathFunction constant, int value) 14 | { 15 | Constant = constant; 16 | Value = value; 17 | } 18 | 19 | public static MathBinary operator -(MathSqrt left, IMathFunction right) 20 | { 21 | return new MathBinary(MathNodeType.Subtract, left, right); 22 | } 23 | 24 | public string GetText() 25 | { 26 | if (Value == 2) 27 | { 28 | return $"\\sqrt{{{Constant.GetText()}}}"; 29 | } 30 | else 31 | { 32 | return $"\\sqrt[{-Value}]{{{Constant.GetText()}}}"; 33 | } 34 | } 35 | public override string ToString() 36 | { 37 | return GetText(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /NStandard.Dev/Obsolete/NowOffsetScope.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard 2 | { 3 | public class NowOffsetScope : Scope 4 | { 5 | public DateTimeOffset Now; 6 | internal NowOffsetScope() { Now = DateTimeOffset.Now; } 7 | internal NowOffsetScope(Func store) { Now = store(DateTimeOffset.Now); } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /NStandard.Dev/Obsolete/NowOffsetScopeAccessor.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard 2 | { 3 | public class NowOffsetScopeAccessor 4 | { 5 | public static readonly NowOffsetScopeAccessor Instance = new(); 6 | 7 | internal NowOffsetScopeAccessor() { } 8 | 9 | public bool HasAnyScope => NowOffsetScope.Scopes.Count > 0; 10 | 11 | public DateTimeOffset Current 12 | { 13 | get 14 | { 15 | var scope = NowOffsetScope.Current; 16 | if (scope is null) throw new InvalidOperationException($"No {nameof(NowOffsetScope)} found."); 17 | return scope.Now; 18 | } 19 | } 20 | public DateTimeOffset? CurrentOrDefault => NowOffsetScope.Current?.Now; 21 | 22 | public DateTimeOffset Outermost 23 | { 24 | get 25 | { 26 | var scope = NowOffsetScope.Scopes.LastOrDefault(); 27 | if (scope is null) throw new InvalidOperationException($"No {nameof(NowOffsetScope)} found."); 28 | return scope.Now; 29 | } 30 | } 31 | public DateTimeOffset? OutermostOrDefault => NowOffsetScope.Scopes.LastOrDefault()?.Now; 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /NStandard.Dev/Obsolete/NowScope.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard 2 | { 3 | public class NowScope : Scope 4 | { 5 | public DateTime Now; 6 | internal NowScope() { Now = DateTime.Now; } 7 | internal NowScope(Func store) { Now = store(DateTime.Now); } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /NStandard.Dev/Obsolete/NowScopeAccessor.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard 2 | { 3 | public class NowScopeAccessor 4 | { 5 | public static readonly NowScopeAccessor Instance = new(); 6 | 7 | internal NowScopeAccessor() { } 8 | 9 | public bool HasAnyScope => NowScope.Scopes.Count > 0; 10 | 11 | public DateTime Current 12 | { 13 | get 14 | { 15 | var scope = NowScope.Current; 16 | if (scope is null) throw new InvalidOperationException($"No {nameof(NowScope)} found."); 17 | return scope.Now; 18 | } 19 | } 20 | public DateTime? CurrentOrDefault => NowScope.Current?.Now; 21 | 22 | public DateTime Outermost 23 | { 24 | get 25 | { 26 | var scope = NowScope.Scopes.LastOrDefault(); 27 | if (scope is null) throw new InvalidOperationException($"No {nameof(NowScope)} found."); 28 | return scope.Now; 29 | } 30 | } 31 | public DateTime? OutermostOrDefault => NowScope.Scopes.LastOrDefault()?.Now; 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /NStandard.Dev/Obsolete/Reference/GACFolders.cs: -------------------------------------------------------------------------------- 1 | #if false 2 | using System; 3 | 4 | namespace NStandard.Reference 5 | { 6 | [Flags] 7 | public enum GACFolders 8 | { 9 | All = Shared | SDK | NuGet | Reserved | Packs, 10 | Shared = 1, 11 | SDK = 2, 12 | NuGet = 4, 13 | Reserved = 8, 14 | Packs = 16, 15 | } 16 | } 17 | #endif 18 | -------------------------------------------------------------------------------- /NStandard.Dev/Threading/CronFieldType.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Threading 2 | { 3 | public enum CronFieldType 4 | { 5 | Ingore = -1, 6 | Any = 0, 7 | Specified = 1, 8 | Last = 2, 9 | Workday = 3, 10 | LastWorkday = 4, 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /NStandard.Dev/Threading/Scheduler.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | 3 | namespace NStandard.Threading 4 | { 5 | public abstract class Scheduler 6 | { 7 | public static Thread Thread; 8 | public static bool SigAbort { get; private set; } 9 | public static DateTime LastExecutionTime { get; private set; } 10 | 11 | [MethodImpl(MethodImplOptions.Synchronized)] 12 | public static void Start(TimeSpan interval) 13 | { 14 | SigAbort = false; 15 | if (Thread == null) 16 | { 17 | Thread = new Thread(() => 18 | { 19 | while (true) 20 | { 21 | if (SigAbort) break; 22 | var now = DateTime.Now; 23 | 24 | LastExecutionTime = now; 25 | Thread.Sleep(interval); 26 | } 27 | Thread = null; 28 | SigAbort = false; 29 | }); 30 | Thread.Start(); 31 | } 32 | else throw new InvalidOperationException(); 33 | } 34 | 35 | public static void Stop() => SigAbort = true; 36 | 37 | public abstract void Task(DateTime now); 38 | 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /NStandard.Dev/[NoRelease] NStandard.Dev.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | NStandard 6 | NStandard.Dev 7 | preview 8 | true 9 | enable 10 | enable 11 | 12 | 13 | 14 | none 15 | false 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /NStandard.Diagnostics/NStandard.Diagnostics.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | net5.0;net6.0;net7.0; 6 | netstandard2.0;netstandard2.1; 7 | net35;net451;net452;net46;net461;net462;net47;net471;net472;net48; 8 | 9 | preview 10 | 11 | 12 | 13 | none 14 | false 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /NStandard.Diagnostics/TestId.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Diagnostics; 2 | 3 | public struct TestId 4 | { 5 | public int ThreadId { get; set; } 6 | public int InvokeNumber { get; set; } 7 | 8 | public TestId(int threadId, int invokeNumber) 9 | { 10 | ThreadId = threadId; 11 | InvokeNumber = invokeNumber; 12 | } 13 | 14 | public override string ToString() 15 | { 16 | return $"Thread:{ThreadId}({InvokeNumber})"; 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /NStandard.Diagnostics/TestReport.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | 4 | namespace NStandard.Diagnostics; 5 | 6 | public class TestReport 7 | { 8 | public TestReport(TestResult[] results) 9 | { 10 | Results = results; 11 | } 12 | 13 | public TimeSpan? AverageElapsed { get; private set; } 14 | public TimeSpan? TotalElapsed { get; private set; } 15 | public TimeSpan? MinElapsed { get; private set; } 16 | public TimeSpan? MaxElapsed { get; private set; } 17 | 18 | private TestResult[] _results; 19 | public TestResult[] Results 20 | { 21 | get => _results; 22 | set 23 | { 24 | _results = value; 25 | var allTicks = value.Where(x => x.Success).Select(x => x.Elapsed.Ticks); 26 | if (allTicks.Any()) 27 | { 28 | AverageElapsed = new TimeSpan((long)allTicks.Average()); 29 | TotalElapsed = new TimeSpan(allTicks.Sum()); 30 | MinElapsed = new TimeSpan(allTicks.Min()); 31 | MaxElapsed = new TimeSpan(allTicks.Max()); 32 | } 33 | else 34 | { 35 | AverageElapsed = default; 36 | TotalElapsed = default; 37 | MinElapsed = default; 38 | MaxElapsed = default; 39 | } 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /NStandard.Diagnostics/TestResult.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace NStandard.Diagnostics; 4 | 5 | public struct TestResult 6 | { 7 | public int ThreadId { get; set; } 8 | public int InvokeNumber { get; set; } 9 | public bool Success { get; set; } 10 | 11 | public TRet Return { get; set; } 12 | public TimeSpan Elapsed { get; set; } 13 | public Exception Exception { get; set; } 14 | 15 | public override string ToString() 16 | { 17 | return $"{{ Id: {ThreadId}:{InvokeNumber}, Success = {Success}, Elapsed = {Elapsed} }}"; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /NStandard.Encoding/NStandard.Encoding.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | net5.0;net6.0;net7.0;net8.0; 6 | netstandard2.0;netstandard2.1; 7 | net46;net461;net462;net47;net471;net472;net48; 8 | 9 | 0.8.5 10 | preview 11 | NStandard 12 | DotNet Core extensions for system library. 13 | zmjack 14 | LICENSE.md 15 | https://github.com/zmjack/NStandard 16 | https://github.com/zmjack/NStandard 17 | git 18 | System Standard Extension 19 | true 20 | nstandard.png 21 | Copyright © nstandard.net 2020 22 | NStandard.Encoding 23 | 24 | 25 | 26 | none 27 | false 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | True 37 | 38 | 39 | 40 | True 41 | 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /NStandard.Json.Net/Converters/DateOnlyConverter.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | 4 | namespace NStandard.Json.Net.Converters; 5 | 6 | #if NET6_0_OR_GREATER 7 | public class DateOnlyConverter : JsonConverter 8 | { 9 | public override bool CanConvert(Type objectType) => objectType == typeof(DateOnly) || objectType == typeof(DateOnly?); 10 | 11 | public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) 12 | { 13 | return reader.TokenType switch 14 | { 15 | JsonToken.Null => null, 16 | JsonToken.String => DateOnly.FromDateTime(DateTime.Parse(reader.Value as string).ToLocalTime()), 17 | JsonToken.Date => DateOnly.FromDateTime((DateTime)reader.Value), 18 | _ => throw new NotSupportedException($"{reader.TokenType} is not supported."), 19 | }; 20 | } 21 | 22 | public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) 23 | { 24 | var valueType = value.GetType(); 25 | if (!CanConvert(valueType)) throw new InvalidOperationException($"The converter specified on '{writer.Path}' is not compatible with the type '{typeof(DateOnly)}'."); 26 | serializer.Serialize(writer, ((DateOnly)value).ToString("O")); 27 | } 28 | } 29 | #endif 30 | -------------------------------------------------------------------------------- /NStandard.Json.Net/Converters/IPAddressConverter.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | using System.Net; 4 | 5 | namespace NStandard.Json.Net.Converters; 6 | 7 | public class IPAddressConverter : JsonConverter 8 | { 9 | public override bool CanConvert(Type objectType) => objectType == typeof(IPAddress); 10 | 11 | public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) 12 | { 13 | return reader.TokenType switch 14 | { 15 | JsonToken.Null => null, 16 | JsonToken.String => IPAddress.Parse(reader.Value as string), 17 | _ => throw new NotSupportedException($"{reader.TokenType} is not supported."), 18 | }; 19 | } 20 | 21 | public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) 22 | { 23 | var valueType = value.GetType(); 24 | if (!CanConvert(valueType)) throw new InvalidOperationException($"The converter specified on '{writer.Path}' is not compatible with the type '{typeof(IPAddress)}'."); 25 | serializer.Serialize(writer, ((IPAddress)value).ToString()); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /NStandard.Json.Net/Converters/PhysicalAddressConverter.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | using System.Net.NetworkInformation; 4 | using System.Text; 5 | 6 | namespace NStandard.Json.Net.Converters; 7 | 8 | public class PhysicalAddressConverter : JsonConverter 9 | { 10 | public override bool CanConvert(Type objectType) => objectType == typeof(PhysicalAddress); 11 | 12 | public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) 13 | { 14 | return reader.TokenType switch 15 | { 16 | JsonToken.Null => null, 17 | JsonToken.String => PhysicalAddress.Parse(reader.Value as string), 18 | _ => throw new NotSupportedException($"{reader.TokenType} is not supported."), 19 | }; 20 | } 21 | 22 | public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) 23 | { 24 | var valueType = value.GetType(); 25 | if (!CanConvert(valueType)) throw new InvalidOperationException($"The converter specified on '{writer.Path}' is not compatible with the type '{typeof(PhysicalAddress)}'."); 26 | 27 | var bytes = ((PhysicalAddress)value).GetAddressBytes(); 28 | var enumerator = bytes.GetEnumerator(); 29 | var sb = new StringBuilder(30); 30 | if (enumerator.MoveNext()) 31 | { 32 | sb.Append(((byte)enumerator.Current).ToString("X2")); 33 | while (enumerator.MoveNext()) 34 | { 35 | sb.Append('-'); 36 | sb.Append(((byte)enumerator.Current).ToString("X2")); 37 | } 38 | } 39 | 40 | serializer.Serialize(writer, sb.ToString()); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /NStandard.Json.Net/Converters/VariantConverter.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | 4 | namespace NStandard.Json.Net.Converters; 5 | 6 | public class VariantConverter : JsonConverter 7 | { 8 | public override bool CanConvert(Type objectType) => objectType.IsType(typeof(Variant)); 9 | 10 | public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) 11 | { 12 | return reader.TokenType switch 13 | { 14 | JsonToken.Null => new Variant((string)null), 15 | JsonToken.None => new Variant((string)null), 16 | JsonToken.Undefined => new Variant((string)null), 17 | JsonToken.Integer => new Variant((int)reader.Value), 18 | JsonToken.Float => new Variant((double)reader.Value), 19 | JsonToken.String => new Variant(reader.Value as string), 20 | JsonToken.Boolean => new Variant((bool)reader.Value), 21 | JsonToken.Date => new Variant((DateTime)reader.Value), 22 | _ => throw new NotSupportedException($"{reader.TokenType} is not supported."), 23 | }; 24 | } 25 | 26 | public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) 27 | { 28 | var valueType = value.GetType(); 29 | if (!CanConvert(valueType)) throw new InvalidOperationException($"The converter specified on '{writer.Path}' is not compatible with the type '{typeof(Variant)}'."); 30 | serializer.Serialize(writer, (value as Variant).ToString()); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /NStandard.Json.Net/NStandard.Json.Net.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | net5.0;net6.0;net7.0; 6 | netstandard2.0;netstandard2.1; 7 | net35;net451;net452;net46;net461;net462;net47;net471;net472;net48; 8 | 9 | preview 10 | zmjack 11 | 0.7.0 12 | nstandard.net 13 | 14 | Json extensions for Newtonsoft.Json. 15 | - Includes built-in type compatibility, such as Lazy, DateOnly, etc. 16 | 17 | Copyright © nstandard.net 2021 18 | LICENSE.md 19 | nstandard.net 20 | nstandard.png 21 | https://github.com/zmjack/NStandard 22 | git 23 | Json Extension 24 | true 25 | 26 | 27 | 28 | none 29 | false 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | True 39 | 40 | 41 | 42 | True 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /NStandard.Json.Net/README.md: -------------------------------------------------------------------------------- 1 | # NStandard.Json.Net 2 | 3 | **Json** extensions for **Newtonsoft.Json**. 4 | 5 | - Includes built-in type compatibility , such as **Lazy\**. 6 | 7 | 8 |
9 | 10 | ## Built-in compatibility 11 | 12 | **Lazy\** is a commonly used type, but his serialization is not very easy to use. 13 | 14 | For example, 15 | 16 | ```csharp 17 | var lazy = new Lazy(123); 18 | var output = System.Text.Json.JsonSerializer.Serialize(lazy); 19 | ``` 20 | 21 | The output is 22 | 23 | ```json 24 | {"IsValueCreated":true,"Value":123} 25 | ``` 26 | 27 | We can find that the **IsValueCreated** field is meaningless in **Json**. 28 | 29 |
30 | 31 | So, we hope it can be simplified. Use these code: 32 | 33 | ```csharp 34 | using System.Text.Json; 35 | using NStandard.Json; 36 | ``` 37 | 38 | ```csharp 39 | var options = new JsonSerializerOptions(); 40 | options.Converters.Add(new LazyConverter()); 41 | 42 | // Serialize 43 | var lazy = new Lazy(123); 44 | var output = JsonSerializer.Serialize(lazy, options); 45 | // The output is: 123 46 | 47 | // Deserialize 48 | var backLazy = JsonSerializer.Deserialize>(output, options); 49 | var value = backLazy.Value; 50 | // The value is: 123 51 | ``` 52 | 53 |
54 | 55 | ## Use in AspNet Core 56 | 57 | You need to install the **Microsoft.AspNetCore.Mvc.NewtonsoftJson** package first. 58 | 59 | Use the following code to enable the extension in the **AspNet Core** application. 60 | 61 | ```csharp 62 | services 63 | .AddControllersWithViews() 64 | .AddNewtonsoftJson(options => 65 | { 66 | options.SerializerSettings.Converters.Add(new LazyConverter()); 67 | }); 68 | ``` 69 | 70 |
71 | 72 | -------------------------------------------------------------------------------- /NStandard.Json/Converters/DateOnlyConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text.Json; 3 | using System.Text.Json.Serialization; 4 | 5 | namespace NStandard.Json.Converters; 6 | 7 | #if NET6_0_OR_GREATER 8 | public class DateOnlyConverter : JsonConverter 9 | { 10 | public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) 11 | { 12 | var str = reader.GetString(); 13 | var dt = DateTime.Parse(str).ToLocalTime(); 14 | return DateOnly.FromDateTime(dt); 15 | } 16 | 17 | public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options) 18 | { 19 | var isoDate = value.ToString("O"); 20 | writer.WriteStringValue(isoDate); 21 | } 22 | } 23 | #endif 24 | -------------------------------------------------------------------------------- /NStandard.Json/Converters/IPAddressConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using System.Text.Json; 4 | using System.Text.Json.Serialization; 5 | 6 | namespace NStandard.Json.Converters; 7 | 8 | public class IPAddressConverter : JsonConverter 9 | { 10 | public override bool CanConvert(Type objectType) => objectType == typeof(IPAddress); 11 | 12 | public override IPAddress Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) 13 | { 14 | var str = reader.GetString(); 15 | return IPAddress.Parse(str); 16 | } 17 | 18 | public override void Write(Utf8JsonWriter writer, IPAddress value, JsonSerializerOptions options) 19 | { 20 | writer.WriteStringValue(value.ToString()); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /NStandard.Json/Converters/LazyConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text.Json; 3 | using System.Text.Json.Serialization; 4 | 5 | namespace NStandard.Json.Converters; 6 | 7 | public class LazyConverter : JsonConverterFactory 8 | { 9 | public override bool CanConvert(Type typeToConvert) 10 | { 11 | if (!typeToConvert.IsGenericType) return false; 12 | return typeToConvert.GetGenericTypeDefinition() == typeof(Lazy<>); 13 | } 14 | 15 | public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) 16 | { 17 | var wrappedType = typeToConvert.GetGenericArguments()[0]; 18 | var converter = (JsonConverter)Activator.CreateInstance(typeof(LazyConverter<>).MakeGenericType(wrappedType)); 19 | return converter; 20 | } 21 | } 22 | 23 | public class LazyConverter : JsonConverter> 24 | { 25 | private Lazy CreateLazy(TValue value) 26 | { 27 | var lazy = new Lazy(() => value); 28 | var ret = lazy.Value; 29 | return lazy; 30 | } 31 | 32 | public override bool CanConvert(Type objectType) => objectType == typeof(Lazy); 33 | 34 | public override Lazy Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) 35 | { 36 | if (reader.TokenType == JsonTokenType.Null) return null; 37 | var value = JsonSerializer.Deserialize(ref reader, options); 38 | return CreateLazy(value); 39 | } 40 | 41 | public override void Write(Utf8JsonWriter writer, Lazy value, JsonSerializerOptions options) 42 | { 43 | JsonSerializer.Serialize(writer, value.Value, typeof(TValue), options); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /NStandard.Json/Converters/NetDoubleConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text.Json; 3 | using System.Text.Json.Serialization; 4 | 5 | namespace NStandard.Json.Converters; 6 | 7 | public class NetDoubleConverter : JsonConverter 8 | { 9 | public override double Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) 10 | { 11 | if (reader.TokenType == JsonTokenType.String) 12 | { 13 | var str = reader.GetString(); 14 | return str switch 15 | { 16 | "Infinity" => double.PositiveInfinity, 17 | "-Infinity" => double.NegativeInfinity, 18 | _ => double.NaN, 19 | }; 20 | } 21 | return reader.GetDouble(); 22 | } 23 | 24 | public override void Write(Utf8JsonWriter writer, double value, JsonSerializerOptions options) 25 | { 26 | if (double.IsNaN(value)) writer.WriteStringValue("NaN"); 27 | else if (double.IsPositiveInfinity(value)) writer.WriteStringValue("Infinity"); 28 | else if (double.IsNegativeInfinity(value)) writer.WriteStringValue("-Infinity"); 29 | else writer.WriteNumberValue(value); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /NStandard.Json/Converters/NetSingleConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text.Json; 3 | using System.Text.Json.Serialization; 4 | 5 | namespace NStandard.Json.Converters; 6 | 7 | public class NetSingleConverter : JsonConverter 8 | { 9 | public override float Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) 10 | { 11 | if (reader.TokenType == JsonTokenType.String) 12 | { 13 | var str = reader.GetString(); 14 | return str switch 15 | { 16 | "Infinity" => float.PositiveInfinity, 17 | "-Infinity" => float.NegativeInfinity, 18 | _ => float.NaN, 19 | }; 20 | } 21 | return reader.GetSingle(); 22 | } 23 | 24 | public override void Write(Utf8JsonWriter writer, float value, JsonSerializerOptions options) 25 | { 26 | if (float.IsNaN(value)) writer.WriteStringValue("NaN"); 27 | else if (float.IsPositiveInfinity(value)) writer.WriteStringValue("Infinity"); 28 | else if (float.IsNegativeInfinity(value)) writer.WriteStringValue("-Infinity"); 29 | else writer.WriteNumberValue(value); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /NStandard.Json/Converters/PhysicalAddressConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net.NetworkInformation; 3 | using System.Text; 4 | using System.Text.Json; 5 | using System.Text.Json.Serialization; 6 | 7 | namespace NStandard.Json.Converters; 8 | 9 | public class PhysicalAddressConverter : JsonConverter 10 | { 11 | public override bool CanConvert(Type objectType) => objectType == typeof(PhysicalAddress); 12 | 13 | public override PhysicalAddress Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) 14 | { 15 | var str = reader.GetString(); 16 | return PhysicalAddress.Parse(str); 17 | } 18 | 19 | public override void Write(Utf8JsonWriter writer, PhysicalAddress value, JsonSerializerOptions options) 20 | { 21 | var bytes = ((PhysicalAddress)value).GetAddressBytes(); 22 | var enumerator = bytes.GetEnumerator(); 23 | var sb = new StringBuilder(30); 24 | if (enumerator.MoveNext()) 25 | { 26 | sb.Append(((byte)enumerator.Current).ToString("X2")); 27 | while (enumerator.MoveNext()) 28 | { 29 | sb.Append('-'); 30 | sb.Append(((byte)enumerator.Current).ToString("X2")); 31 | } 32 | } 33 | 34 | writer.WriteStringValue(sb.ToString()); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /NStandard.Json/Converters/VariantConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text.Json; 3 | using System.Text.Json.Serialization; 4 | 5 | namespace NStandard.Json.Converters; 6 | 7 | public class VariantConverter : JsonConverter 8 | { 9 | public override bool CanConvert(Type objectType) => objectType.IsType(typeof(Variant)); 10 | 11 | public override Variant Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) 12 | { 13 | return reader.TokenType switch 14 | { 15 | JsonTokenType.None => new Variant(null as string), 16 | JsonTokenType.Null => new Variant(null as string), 17 | JsonTokenType.String => reader.GetString(), 18 | JsonTokenType.Number => reader.GetDouble(), 19 | JsonTokenType.False => false, 20 | JsonTokenType.True => true, 21 | _ => throw new NotSupportedException($"{reader.TokenType} is not supported."), 22 | }; 23 | } 24 | 25 | public override void Write(Utf8JsonWriter writer, Variant value, JsonSerializerOptions options) 26 | { 27 | writer.WriteStringValue(value.ToString()); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /NStandard.Runtime/NStandard.Runtime.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | net5.0;net6.0;net7.0;net8.0; 6 | netstandard2.0;netstandard2.1; 7 | 8 | 1.9.0 9 | preview 10 | true 11 | zmjack 12 | Copyright © nstandard.net 2020 13 | nstandard.net 14 | DotNet extensions for system library. 15 | LICENSE.md 16 | nstandard.net 17 | nstandard.png 18 | https://github.com/zmjack/NStandard 19 | git 20 | System Standard Extension 21 | NStandard.Runtime 22 | 23 | 24 | 25 | none 26 | false 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | True 40 | 41 | 42 | 43 | True 44 | 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /NStandard.Runtime/SdkType.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Runtime; 2 | 3 | public static class SdkType 4 | { 5 | public const string Legacy = ""; 6 | public const string Core = "Microsoft.NET.Sdk"; 7 | public const string Web = "Microsoft.NET.Sdk.Web"; 8 | } 9 | -------------------------------------------------------------------------------- /NStandard.Trees/BinaryNodeType.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Trees; 2 | 3 | public enum BinaryNodeType 4 | { 5 | LeftNode = -1, 6 | RootNode = 0, 7 | RightNode = 1, 8 | } 9 | -------------------------------------------------------------------------------- /NStandard.Trees/NStandard.Trees.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | preview 6 | enable 7 | 8 | 9 | 10 | none 11 | false 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /NStandard.Windows/NStandard - Backup.Windows.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | True 6 | 7 | 8 | 9 | none 10 | false 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /NStandard.Windows/NStandard.Windows.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | preview 6 | True 7 | 0.0.1 8 | 9 | 10 | 11 | none 12 | false 13 | 14 | 15 | 16 | 17 | TextTemplatingFileGenerator 18 | Doc2Code.txt 19 | 20 | 21 | True 22 | True 23 | Doc2Code.tt 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /NStandard.Windows/Native/Service/SERVICE_DESCRIPTIONW.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.InteropServices; 2 | 3 | namespace NStandard.Windows.Native.Service; 4 | 5 | internal struct SERVICE_DESCRIPTIONW 6 | { 7 | [MarshalAs(UnmanagedType.LPWStr)] public string Description; 8 | } 9 | -------------------------------------------------------------------------------- /NStandard.Windows/Native/Service/ScmRights.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace NStandard.Windows.Native.Service; 4 | 5 | [Flags] 6 | internal enum ScmRights 7 | { 8 | None = 0, 9 | SC_MANAGER_ALL_ACCESS = 0xF003F, 10 | SC_MANAGER_CREATE_SERVICE = 0x0002, 11 | SC_MANAGER_CONNECT = 0x0001, 12 | SC_MANAGER_ENUMERATE_SERVICE = 0x0004, 13 | SC_MANAGER_LOCK = 0x0008, 14 | SC_MANAGER_MODIFY_BOOT_CONFIG = 0x0020, 15 | SC_MANAGER_QUERY_LOCK_STATUS = 0x0010, 16 | } 17 | -------------------------------------------------------------------------------- /NStandard.Windows/Native/Service/ServiceControls.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace NStandard.Windows.Native.Service; 4 | 5 | [Flags] 6 | internal enum ServiceControls : uint 7 | { 8 | SERVICE_CONTROL_CONTINUE = 0x00000003, 9 | SERVICE_CONTROL_INTERROGATE = 0x00000004, 10 | SERVICE_CONTROL_NETBINDADD = 0x00000007, 11 | SERVICE_CONTROL_NETBINDDISABLE = 0x0000000A, 12 | SERVICE_CONTROL_NETBINDENABLE = 0x00000009, 13 | SERVICE_CONTROL_NETBINDREMOVE = 0x00000008, 14 | SERVICE_CONTROL_PARAMCHANGE = 0x00000006, 15 | SERVICE_CONTROL_PAUSE = 0x00000002, 16 | SERVICE_CONTROL_STOP = 0x00000001, 17 | } 18 | -------------------------------------------------------------------------------- /NStandard.Windows/Native/Service/ServiceErrorControl.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Windows.Native.Service; 2 | 3 | public enum ServiceErrorControl 4 | { 5 | /// 6 | /// The startup program logs the error in the event log, if possible. If the last-known-good configuration is being started, the startup operation fails. Otherwise, the system is restarted with the last-known good configuration. 7 | /// 8 | SERVICE_ERROR_CRITICAL = 0x00000003, 9 | 10 | /// 11 | /// The startup program ignores the error and continues the startup operation. 12 | /// 13 | SERVICE_ERROR_IGNORE = 0x00000000, 14 | 15 | /// 16 | /// The startup program logs the error in the event log but continues the startup operation. 17 | /// 18 | SERVICE_ERROR_NORMAL = 0x00000001, 19 | 20 | /// 21 | /// The startup program logs the error in the event log. If the last-known-good configuration is being started, the startup operation continues. Otherwise, the system is restarted with the last-known-good configuration. 22 | /// 23 | SERVICE_ERROR_SEVERE = 0x00000002, 24 | 25 | } 26 | -------------------------------------------------------------------------------- /NStandard.Windows/Native/Service/ServiceStartType.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Windows.Native.Service; 2 | 3 | public enum ServiceStartType 4 | { 5 | /// 6 | /// A service started automatically by the service control manager during system startup. For more information, see Automatically Starting Services. 7 | /// 8 | SERVICE_AUTO_START = 0x00000002, 9 | 10 | /// 11 | /// A device driver started by the system loader. This value is valid only for driver services. 12 | /// 13 | SERVICE_BOOT_START = 0x00000000, 14 | 15 | /// 16 | /// A service started by the service control manager when a process calls the StartService function. For more information, see Starting Services on Demand. 17 | /// 18 | SERVICE_DEMAND_START = 0x00000003, 19 | 20 | /// 21 | /// A service that cannot be started. Attempts to start the service result in the error code ERROR_SERVICE_DISABLED. 22 | /// 23 | SERVICE_DISABLED = 0x00000004, 24 | 25 | /// 26 | /// A device driver started by the IoInitSystem function. This value is valid only for driver services. 27 | /// 28 | SERVICE_SYSTEM_START = 0x00000001, 29 | 30 | } 31 | -------------------------------------------------------------------------------- /NStandard.Windows/Native/Service/ServiceState.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Windows.Native.Service; 2 | 3 | internal enum ServiceState : int 4 | { 5 | SERVICE_STOPPED = 0x00000001, 6 | SERVICE_START_PENDING = 0x00000002, 7 | SERVICE_STOP_PENDING = 0x00000003, 8 | SERVICE_RUNNING = 0x00000004, 9 | SERVICE_CONTINUE_PENDING = 0x00000005, 10 | SERVICE_PAUSE_PENDING = 0x00000006, 11 | SERVICE_PAUSED = 0x00000007, 12 | } 13 | -------------------------------------------------------------------------------- /NStandard.Windows/Native/Service/ServiceStatus.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.InteropServices; 2 | 3 | namespace NStandard.Windows.Native.Service; 4 | 5 | [StructLayout(LayoutKind.Sequential)] 6 | internal struct ServiceStatus 7 | { 8 | public uint dwServiceType; 9 | public ServiceState dwCurrentState; 10 | public uint dwControlsAccepted; 11 | public uint dwWin32ExitCode; 12 | public uint dwServiceSpecificExitCode; 13 | public uint dwCheckPoint; 14 | public uint dwWaitHint; 15 | } 16 | -------------------------------------------------------------------------------- /NStandard.Windows/Native/Service/ServiceType.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Windows.Native.Service; 2 | 3 | internal enum ServiceType 4 | { 5 | /// 6 | /// Reserved. 7 | /// 8 | SERVICE_ADAPTER = 0x00000004, 9 | 10 | /// 11 | /// File system driver service. 12 | /// 13 | SERVICE_FILE_SYSTEM_DRIVER = 0x00000002, 14 | 15 | /// 16 | /// Driver service. 17 | /// 18 | SERVICE_KERNEL_DRIVER = 0x00000001, 19 | 20 | /// 21 | /// Reserved. 22 | /// 23 | SERVICE_RECOGNIZER_DRIVER = 0x00000008, 24 | 25 | /// 26 | /// Service that runs in its own process. 27 | /// 28 | SERVICE_WIN32_OWN_PROCESS = 0x00000010, 29 | 30 | /// 31 | /// Service that shares a process with one or more other services. For more information, see Service Programs. 32 | /// 33 | SERVICE_WIN32_SHARE_PROCESS = 0x00000020, 34 | } 35 | -------------------------------------------------------------------------------- /NStandard.Windows/Native/Types/GenericRights.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace NStandard.Windows.Native.Types; 4 | 5 | [Flags] 6 | internal enum GenericRights : uint 7 | { 8 | GENERIC_READ = 0x80000000, 9 | GENERIC_WRITE = 0x40000000, 10 | GENERIC_EXECUTE = 0x20000000, 11 | GENERIC_ALL = 0x10000000, 12 | } 13 | -------------------------------------------------------------------------------- /NStandard.lutconfig: -------------------------------------------------------------------------------- 1 | 2 | 3 | true 4 | true 5 | 180000 6 | -------------------------------------------------------------------------------- /NStandard/!Any/Any.Compose.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard; 2 | 3 | public static partial class Any 4 | { 5 | /// 6 | /// Takes two functions and returns a function. 7 | /// 8 | /// 9 | public static Func Compose(Func pipe) 10 | { 11 | return x => pipe(x); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /NStandard/!Any/Any.Forward.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard; 2 | 3 | public static partial class Any 4 | { 5 | /// 6 | /// Computes the element by path and returns the element. 7 | /// 8 | /// 9 | /// 10 | /// 11 | /// 12 | public static IEnumerable Forward(T seed, Func forward) where T : class 13 | { 14 | T current = seed; 15 | while (true) 16 | { 17 | if (current is null) break; 18 | yield return current; 19 | current = forward(current); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /NStandard/!Any/Any.ReDim.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | 3 | namespace NStandard; 4 | 5 | public static partial class Any 6 | { 7 | private static ArgumentException Exception_IncompatibleRank(string paramName) => new("The lengths can not be incompatible with the array.", paramName); 8 | private static ArgumentException Exception_VariableMustBeArray(string paramName) => new($"The {paramName} must be an array.", paramName); 9 | 10 | /// 11 | /// Reallocates storage space for an array variable. 12 | /// 13 | /// 14 | /// 15 | /// 16 | /// 17 | public static void ReDim(ref TArray variable, params int[] lengths) where TArray : class, ICollection, IEnumerable, IList, ICloneable 18 | { 19 | var type = variable.GetType(); 20 | if (!type.IsArray) throw Exception_VariableMustBeArray(nameof(variable)); 21 | 22 | var origin = (variable as Array)!; 23 | if (lengths.Length != origin.Rank) throw Exception_IncompatibleRank(nameof(lengths)); 24 | 25 | var elementType = type.GetElementType()!; 26 | var newArray = Array.CreateInstance(elementType, lengths); 27 | var originLengths = origin.GetLengths(); 28 | 29 | var stepper = new IndicesStepper(0, Zip(originLengths, lengths).Select(pair => Math.Min(pair.Item1, pair.Item2)).ToArray()); 30 | foreach (var indices in stepper) 31 | { 32 | newArray.SetValue(origin.GetValue(indices), indices); 33 | } 34 | variable = (newArray as TArray)!; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /NStandard/!Any/Any.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard; 2 | 3 | public static partial class Any 4 | { 5 | /// 6 | /// Creates a instance by the specified function. 7 | /// 8 | /// 9 | /// 10 | /// 11 | public static T Create(Func func) => func(); 12 | 13 | /// 14 | /// Swaps the values of two instances. 15 | /// 16 | /// 17 | /// 18 | /// 19 | public static void Swap(ref T a, ref T b) 20 | { 21 | var tmp = a; 22 | a = b; 23 | b = tmp; 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /NStandard/!Design/ISliceCount.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard; 2 | 3 | public interface ISliceCount 4 | { 5 | int Count { get; } 6 | TRet Slice(int start, int length); 7 | } 8 | -------------------------------------------------------------------------------- /NStandard/!Design/ISliceLength.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard; 2 | 3 | public interface ISliceLength 4 | { 5 | int Length { get; } 6 | TRet Slice(int start, int length); 7 | } 8 | -------------------------------------------------------------------------------- /NStandard/!DotNet/System/Collections/IStructuralComparable.cs: -------------------------------------------------------------------------------- 1 | #if NETCOREAPP1_0_OR_GREATER || NETSTANDARD1_0_OR_GREATER || NET451_OR_GREATER 2 | #else 3 | // Licensed to the .NET Foundation under one or more agreements. 4 | // The .NET Foundation licenses this file to you under the MIT license. 5 | // See the LICENSE file in the project root for more information. 6 | 7 | namespace System.Collections; 8 | 9 | public interface IStructuralComparable 10 | { 11 | int CompareTo(object other, IComparer comparer); 12 | } 13 | #endif 14 | -------------------------------------------------------------------------------- /NStandard/!DotNet/System/Collections/IStructuralEquatable.cs: -------------------------------------------------------------------------------- 1 | #if NETCOREAPP1_0_OR_GREATER || NETSTANDARD1_0_OR_GREATER || NET451_OR_GREATER 2 | #else 3 | // Licensed to the .NET Foundation under one or more agreements. 4 | // The .NET Foundation licenses this file to you under the MIT license. 5 | // See the LICENSE file in the project root for more information. 6 | 7 | namespace System.Collections; 8 | 9 | public interface IStructuralEquatable 10 | { 11 | bool Equals(object other, IEqualityComparer comparer); 12 | int GetHashCode(IEqualityComparer comparer); 13 | } 14 | #endif 15 | -------------------------------------------------------------------------------- /NStandard/!DotNet/System/Runtime/CompilerServices/ITuple.cs: -------------------------------------------------------------------------------- 1 | #if NETCOREAPP2_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER || NET471_OR_GREATER 2 | #else 3 | // Licensed to the .NET Foundation under one or more agreements. 4 | // The .NET Foundation licenses this file to you under the MIT license. 5 | // See the LICENSE file in the project root for more information. 6 | 7 | namespace System.Runtime.CompilerServices; 8 | 9 | /// 10 | /// This interface is required for types that want to be indexed into by dynamic patterns. 11 | /// 12 | public interface ITuple 13 | { 14 | /// 15 | /// The number of positions in this data structure. 16 | /// 17 | int Length { get; } 18 | 19 | /// 20 | /// Get the element at position . 21 | /// 22 | object? this[int index] { get; } 23 | } 24 | #endif 25 | -------------------------------------------------------------------------------- /NStandard/!DotNet/System/SR - partial.cs: -------------------------------------------------------------------------------- 1 | namespace System; 2 | 3 | internal static class SR 4 | { 5 | #if NETCOREAPP3_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER 6 | #else 7 | internal static string Format(string resourceFormat, object p1) => string.Format(resourceFormat, p1); 8 | internal static string Format(string resourceFormat, object p1, object p2) => string.Format(resourceFormat, p1, p2); 9 | #endif 10 | 11 | #if NETCOREAPP3_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER 12 | #else 13 | internal static string @HashCode_HashCodeNotSupported => "HashCode is a mutable struct and should not be compared with other HashCodes. Use ToHashCode to retrieve the computed hash code."; 14 | internal static string @HashCode_EqualityNotSupported => "HashCode is a mutable struct and should not be compared with other HashCodes."; 15 | #endif 16 | 17 | #if NET5_0_OR_GREATER || NETSTANDARD2_0_OR_GREATER || NET40_OR_GREATER 18 | #else 19 | internal static string @ArgumentException_TupleIncorrectType => "Argument must be of type {0}."; 20 | internal static string @ArgumentException_TupleLastArgumentNotATuple => "The last element of an eight element tuple must be a Tuple."; 21 | internal static string @Argument_EnumTypeDoesNotMatch => "The argument type, '{0}', is not the same as the enum type '{1}'."; 22 | #endif 23 | 24 | #if NET5_0_OR_GREATER || NETSTANDARD2_0_OR_GREATER || NET46_OR_GREATER 25 | #else 26 | internal static string @Cryptography_HashAlgorithmNameNullOrEmpty => "The hash algorithm name cannot be null or empty."; 27 | internal static string @Cryptography_InvalidHashAlgorithmOid => "The specified OID ({0}) does not represent a known hash algorithm."; 28 | 29 | internal static string @ArgumentOutOfRange_Range => @"Valid values are between {0} and {1}, inclusive."; 30 | #endif 31 | } 32 | -------------------------------------------------------------------------------- /NStandard/!DotNet/System/Security/Cryptography/RSAEncryptionPaddingMode.cs: -------------------------------------------------------------------------------- 1 | #if NETCOREAPP1_0_OR_GREATER || NETSTANDARD1_3_OR_GREATER || NET46_OR_GREATER 2 | #else 3 | // Licensed to the .NET Foundation under one or more agreements. 4 | // The .NET Foundation licenses this file to you under the MIT license. 5 | 6 | namespace System.Security.Cryptography; 7 | 8 | /// 9 | /// Specifies the padding mode to use with RSA encryption or decryption operations. 10 | /// 11 | public enum RSAEncryptionPaddingMode 12 | { 13 | /// 14 | /// PKCS #1 v1.5. 15 | /// 16 | /// 17 | /// This mode corresponds to the RSAES-PKCS1-v1_5 encryption scheme described in the PKCS #1 RSA Encryption Standard. 18 | /// It is supported for compatibility with existing applications. 19 | /// 20 | Pkcs1, 21 | 22 | /// 23 | /// Optimal Asymmetric Encryption Padding. 24 | /// 25 | /// 26 | /// This mode corresponds to the RSAES-OEAP encryption scheme described in the PKCS #1 RSA Encryption Standard. 27 | /// It is recommended for new applications. 28 | /// 29 | Oaep, 30 | } 31 | #endif 32 | -------------------------------------------------------------------------------- /NStandard/!DotNet/System/Security/Cryptography/RSASignaturePaddingMode.cs: -------------------------------------------------------------------------------- 1 | #if NETCOREAPP1_0_OR_GREATER || NETSTANDARD1_3_OR_GREATER || NET46_OR_GREATER 2 | #else 3 | // Licensed to the .NET Foundation under one or more agreements. 4 | // The .NET Foundation licenses this file to you under the MIT license. 5 | 6 | namespace System.Security.Cryptography; 7 | 8 | /// 9 | /// Specifies the padding mode to use with RSA signature creation or verification operations. 10 | /// 11 | public enum RSASignaturePaddingMode 12 | { 13 | /// 14 | /// PKCS #1 v1.5. 15 | /// 16 | /// 17 | /// This corresponds to the RSASSA-PKCS1-v1.5 signature scheme of the PKCS #1 RSA Encryption Standard. 18 | /// It is supported for compatibility with existing applications. 19 | /// 20 | Pkcs1, 21 | 22 | /// 23 | /// Probabilistic Signature Scheme. 24 | /// 25 | /// 26 | /// This corresponds to the RSASSA-PKCS1-v1.5 signature scheme of the PKCS #1 RSA Encryption Standard. 27 | /// It is recommended for new applications. 28 | /// 29 | Pss, 30 | } 31 | #endif 32 | -------------------------------------------------------------------------------- /NStandard/!Extensions/AppDomainExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using System.Reflection; 3 | 4 | namespace NStandard; 5 | 6 | [EditorBrowsable(EditorBrowsableState.Never)] 7 | public static class AppDomainExtensions 8 | { 9 | //TODO: Long-term Maintenance 10 | public static Assembly? GetCoreLibAssembly(this AppDomain @this) 11 | { 12 | var assemblies = @this.GetAssemblies(); 13 | foreach (var assembly in assemblies) 14 | { 15 | switch (assembly.GetName().Name) 16 | { 17 | // "System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e" 18 | // "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" 19 | case "System.Private.CoreLib": 20 | case "mscorlib": return assembly; 21 | } 22 | } 23 | return null; 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /NStandard/!Extensions/ArrayExtensions.String.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard; 2 | 3 | public static partial class ArrayExtensions 4 | { 5 | } 6 | -------------------------------------------------------------------------------- /NStandard/!Extensions/CharExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | 3 | namespace NStandard; 4 | 5 | [EditorBrowsable(EditorBrowsableState.Never)] 6 | public static class CharExtensions 7 | { 8 | /// 9 | /// Gets the length of the specified char as Ascii. 10 | /// 11 | /// 12 | /// 13 | public static int GetLengthA(this char @this) => @this < 0x100 ? 1 : 2; 14 | 15 | /// 16 | /// Converts the value of a Unicode character to its lowercase equivalent. 17 | /// 18 | /// 19 | /// 20 | public static char ToLower(this char @this) => char.ToLower(@this); 21 | 22 | /// 23 | /// Converts the value of a Unicode character to its uppercase equivalent. 24 | /// 25 | /// 26 | /// 27 | public static char ToUpper(this char @this) => char.ToUpper(@this); 28 | 29 | } 30 | -------------------------------------------------------------------------------- /NStandard/!Extensions/DelegateExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using System.Linq.Expressions; 3 | 4 | namespace NStandard; 5 | 6 | [EditorBrowsable(EditorBrowsableState.Never)] 7 | public static class DelegateExtensions 8 | { 9 | /// 10 | /// Convert a function to its higher-order form. 11 | /// 12 | /// 13 | /// 14 | /// 15 | /// 16 | public static Func Higher(this Func @this, int degree) 17 | { 18 | var parameter = Expression.Parameter(typeof(TSelf), "Param_0"); 19 | var func = Expression.Constant(@this); 20 | Expression higher = parameter; 21 | for (int i = 0; i < degree; i++) 22 | higher = Expression.Invoke(func, higher); 23 | var lambda = Expression.Lambda>(higher, parameter); 24 | return lambda.Compile(); 25 | } 26 | 27 | /// 28 | /// Convert a function to its higher-order form. 29 | /// 30 | /// 31 | /// 32 | /// 33 | /// 34 | public static UnaryFunc Higher(this UnaryFunc @this, int degree) 35 | { 36 | var parameter = Expression.Parameter(typeof(TSelf), "Param_0"); 37 | var func = Expression.Constant(@this); 38 | Expression higher = parameter; 39 | for (int i = 0; i < degree; i++) 40 | higher = Expression.Invoke(func, higher); 41 | var lambda = Expression.Lambda>(higher, parameter); 42 | return lambda.Compile(); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /NStandard/!Extensions/EnumExtensions.cs: -------------------------------------------------------------------------------- 1 | using NStandard.Static; 2 | using System.ComponentModel; 3 | using System.Reflection; 4 | 5 | namespace NStandard; 6 | 7 | [EditorBrowsable(EditorBrowsableState.Never)] 8 | public static class EnumExtensions 9 | { 10 | public static long ToInt64(this Enum @this) => (long)Convert.ChangeType(@this, typeof(long)); 11 | 12 | public static T[] GetFlags(this T @this) where T : Enum 13 | { 14 | return EnumEx.GetFlags().Where(x => @this.HasFlag(x)).ToArray(); 15 | } 16 | 17 | #if NETCOREAPP1_0_OR_GREATER || NETSTANDARD1_0_OR_GREATER || NET451_OR_GREATER 18 | #else 19 | public static bool HasFlag(this Enum @this, Enum flag) 20 | { 21 | if (flag == null) throw new ArgumentNullException(nameof(flag)); 22 | 23 | if (@this.GetType() != flag.GetType()) 24 | { 25 | throw new ArgumentException(SR.Format(SR.Argument_EnumTypeDoesNotMatch, flag.GetType(), @this.GetType())); 26 | } 27 | 28 | return (ToInt64(@this) & ToInt64(flag)) > 0; 29 | } 30 | #endif 31 | 32 | /// 33 | /// Get the attribute of enum. 34 | /// 35 | public static TAttribute? GetAttribute(this Enum enumValue) where TAttribute : Attribute 36 | { 37 | return enumValue 38 | .GetType() 39 | .GetMember(enumValue.ToString()) 40 | .FirstOrDefault()? 41 | .GetCustomAttribute(); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /NStandard/!Extensions/FuncExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | 3 | namespace NStandard; 4 | 5 | [EditorBrowsable(EditorBrowsableState.Never)] 6 | public static class FuncExtensions 7 | { 8 | /// 9 | /// Takes two functions and returns a function. 10 | /// 11 | /// 12 | /// 13 | /// 14 | public static Func Compose(this Func @this, Func pipe) 15 | { 16 | return x => pipe(@this(x)); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /NStandard/!Extensions/IDisposeableExtension.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | 3 | namespace NStandard; 4 | 5 | [EditorBrowsable(EditorBrowsableState.Never)] 6 | public static class IDisposableExtension 7 | { 8 | public static void DisposeAll(this T[] @this) where T : IDisposable 9 | { 10 | foreach (var item in @this) 11 | { 12 | item.Dispose(); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /NStandard/!Extensions/Int32Extensions.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | 3 | namespace NStandard; 4 | 5 | [EditorBrowsable(EditorBrowsableState.Never)] 6 | public static class Int32Extensions 7 | { 8 | /// 9 | /// Returns whether the specified number is odd. 10 | /// 11 | /// 12 | /// 13 | public static bool IsOdd(this int @this) => (@this & 1) == 1; 14 | 15 | /// 16 | /// Returns whether the specified number is even. 17 | /// 18 | /// 19 | /// 20 | public static bool IsEven(this int @this) => (@this & 1) == 0; 21 | 22 | /// 23 | /// Gets the positive integer modulus. (Unlike the operator %, this method always returns a positive number) 24 | /// 25 | /// 26 | /// 27 | /// 28 | public static int Mod(this int @this, int mod) 29 | { 30 | if (@this < 0) 31 | return @this % mod + mod; 32 | else return @this % mod; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /NStandard/!Extensions/Int64Extensions.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | 3 | namespace NStandard; 4 | 5 | [EditorBrowsable(EditorBrowsableState.Never)] 6 | public static class Int64Extensions 7 | { 8 | /// 9 | /// Returns whether the specified number is odd. 10 | /// 11 | /// 12 | /// 13 | public static bool IsOdd(this long @this) => (@this & 1) == 1; 14 | 15 | /// 16 | /// Returns whether the specified number is even. 17 | /// 18 | /// 19 | /// 20 | public static bool IsEven(this long @this) => (@this & 1) == 0; 21 | 22 | /// 23 | /// Gets the positive integer modulus. (Unlike the operator %, this method always returns a positive number) 24 | /// 25 | /// 26 | /// 27 | /// 28 | public static long Mod(this long @this, long mod) 29 | { 30 | if (@this < 0) 31 | return @this % mod + mod; 32 | else return @this % mod; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /NStandard/!Extensions/System.Collections/Generic/LinkedListExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | 3 | namespace NStandard; 4 | 5 | [EditorBrowsable(EditorBrowsableState.Never)] 6 | public static class LinkedListExtensions 7 | { 8 | public static IEnumerable> GetNodes(this LinkedList @this) 9 | { 10 | for (var node = @this.First; node != null; node = node.Next) 11 | { 12 | yield return node; 13 | } 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /NStandard/!Extensions/System.Drawing/ColorExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using System.Drawing; 3 | 4 | namespace NStandard; 5 | 6 | [EditorBrowsable(EditorBrowsableState.Never)] 7 | public static class ColorExtensions 8 | { 9 | public static float GetHueOfHsv(this Color @this) => @this.GetHue(); 10 | 11 | public static float GetSaturationOfHsv(this Color @this) 12 | { 13 | var rgb = new[] { @this.R, @this.G, @this.B }; 14 | double min = rgb.Min(); 15 | double max = rgb.Max(); 16 | 17 | if (max == 0) return 0; 18 | else return (float)((max - min) / max); 19 | } 20 | 21 | public static float GetValueOfHsv(this Color @this) 22 | { 23 | var rgb = new[] { @this.R, @this.G, @this.B }; 24 | double max = rgb.Max(); 25 | return (float)(max / 255); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /NStandard/!Extensions/System.IO/StreamExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | 3 | namespace NStandard; 4 | 5 | [EditorBrowsable(EditorBrowsableState.Never)] 6 | public static class StreamExtensions 7 | { 8 | public delegate void ReadingHandler(byte[] buffer, int readLength); 9 | public delegate void WritingHandler(Stream toStream, byte[] buffer, int totalWrittenLength); 10 | 11 | public static void Scan(this Stream @this, int bufferSize, ReadingHandler handler) 12 | { 13 | var buffer = new byte[bufferSize]; 14 | int readLength; 15 | while ((readLength = @this.Read(buffer, 0, bufferSize)) > 0) 16 | { 17 | handler(buffer, readLength); 18 | } 19 | } 20 | 21 | public static void ScanAndWriteTo(this Stream @this, Stream writeTarget, int bufferSize) 22 | { 23 | int totalWritten = 0; 24 | Scan(@this, bufferSize, (buffer, readLength) => 25 | { 26 | writeTarget.Write(buffer, 0, readLength); 27 | totalWritten += readLength; 28 | }); 29 | } 30 | 31 | public static void ScanAndWriteTo(this Stream @this, Stream writeTarget, int bufferSize, WritingHandler handler) 32 | { 33 | int totalWritten = 0; 34 | Scan(@this, bufferSize, (buffer, readLength) => 35 | { 36 | writeTarget.Write(buffer, 0, readLength); 37 | totalWritten += readLength; 38 | handler(writeTarget, buffer, totalWritten); 39 | }); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /NStandard/!Extensions/System.Net/IPAddressExtensions.cs: -------------------------------------------------------------------------------- 1 | using NStandard.Static; 2 | using System.ComponentModel; 3 | using System.Net; 4 | 5 | namespace NStandard; 6 | 7 | [EditorBrowsable(EditorBrowsableState.Never)] 8 | public static class IPAddressExtensions 9 | { 10 | public static uint ToUInt32(this IPAddress @this) 11 | { 12 | var bytes = @this.GetAddressBytes(); 13 | if (bytes.Length != 4) throw new InvalidCastException("The length of IPAddress must be 32 bits."); 14 | 15 | Array.Reverse(bytes); 16 | return BitConverter.ToUInt32(bytes, 0); 17 | } 18 | 19 | #if NET7_0_OR_GREATER 20 | public static UInt128 ToUInt128(this IPAddress @this) 21 | { 22 | var bytes = @this.GetAddressBytes(); 23 | if (bytes.Length != 16) throw new InvalidCastException("The length of IPAddress must be 128 bits."); 24 | 25 | Array.Reverse(bytes); 26 | return BitConverterEx.ToUInt128(bytes, 0); 27 | } 28 | #endif 29 | 30 | } 31 | -------------------------------------------------------------------------------- /NStandard/!Extensions/System.Text/Json/JsonElementExtensions.cs: -------------------------------------------------------------------------------- 1 | #if NET5_0 2 | using System; 3 | using System.Buffers; 4 | using System.Text.Json; 5 | 6 | namespace NStandard; 7 | 8 | public static class JsonElementExtensions 9 | { 10 | public static T? Deserialize(this JsonElement @this, JsonSerializerOptions? options = null) 11 | { 12 | var bufferWriter = new ArrayBufferWriter(); 13 | using (var writer = new Utf8JsonWriter(bufferWriter)) 14 | { 15 | @this.WriteTo(writer); 16 | } 17 | return JsonSerializer.Deserialize(bufferWriter.WrittenSpan, options)!; 18 | } 19 | 20 | public static object? Deserialize(this JsonElement @this, Type returnType, JsonSerializerOptions? options = null) 21 | { 22 | var bufferWriter = new ArrayBufferWriter(); 23 | using (var writer = new Utf8JsonWriter(bufferWriter)) 24 | { 25 | @this.WriteTo(writer); 26 | } 27 | return JsonSerializer.Deserialize(bufferWriter.WrittenSpan, returnType, options)!; 28 | } 29 | } 30 | #endif 31 | -------------------------------------------------------------------------------- /NStandard/!Extensions/System.Text/StringBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | #if NETCOREAPP1_0_OR_GREATER || NETSTANDARD1_0_OR_GREATER || NET451_OR_GREATER 2 | #else 3 | using System.ComponentModel; 4 | using System.Text; 5 | 6 | namespace NStandard; 7 | 8 | [EditorBrowsable(EditorBrowsableState.Never)] 9 | public static class StringBuilderExtensions 10 | { 11 | public static void Clear(this StringBuilder @this) 12 | { 13 | @this.Length = 0; 14 | } 15 | } 16 | #endif 17 | -------------------------------------------------------------------------------- /NStandard/!Extensions/System.Threading.Tasks/TaskExtensions.cs: -------------------------------------------------------------------------------- 1 | #if NET5_0_OR_GREATER || NETSTANDARD2_0_OR_GREATER || NET40_OR_GREATER 2 | using System; 3 | using System.ComponentModel; 4 | using System.Threading.Tasks; 5 | 6 | namespace NStandard; 7 | 8 | [EditorBrowsable(EditorBrowsableState.Never)] 9 | public static class TaskExtensions 10 | { 11 | public static void Catch(this Task @this, Action onException) 12 | { 13 | try { @this.Wait(); } 14 | catch (Exception ex) { onException(ex); } 15 | } 16 | 17 | #if NETCOREAPP1_0_OR_GREATER || NETSTANDARD1_0_OR_GREATER || NET451_OR_GREATER 18 | public static async Task CatchAsync(this Task @this, Action onException) 19 | { 20 | await Task.Run(() => 21 | { 22 | try { @this.Wait(); } 23 | catch (Exception ex) { onException(ex); } 24 | }); 25 | } 26 | #else 27 | public static Task CatchAsync(this Task @this, Action onException) 28 | { 29 | return Task.Factory.StartNew(() => 30 | { 31 | try { @this.Wait(); } 32 | catch (Exception ex) { onException(ex); } 33 | }); 34 | } 35 | #endif 36 | 37 | } 38 | #endif 39 | -------------------------------------------------------------------------------- /NStandard/!Extensions/SystemReflection/EventInfoExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using System.Reflection; 3 | 4 | namespace NStandard; 5 | 6 | [EditorBrowsable(EditorBrowsableState.Never)] 7 | public static class EventInfoExtensions 8 | { 9 | public static void AddEventHandler(this EventInfo @this, object declaringObject, MethodInfo method) 10 | { 11 | @this.AddEventHandler(declaringObject, Delegate.CreateDelegate(@this.EventHandlerType!, method)); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /NStandard/!Extensions/SystemReflection/ICustomAttributeProviderExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using System.Reflection; 3 | 4 | namespace NStandard; 5 | 6 | [EditorBrowsable(EditorBrowsableState.Never)] 7 | public static class ICustomAttributeProviderExtensions 8 | { 9 | public static bool HasAttribute(this ICustomAttributeProvider @this, bool inherit = true) where TAttribute : Attribute 10 | { 11 | return @this.GetCustomAttributes(typeof(TAttribute), inherit).Any(); 12 | } 13 | 14 | public static bool HasAttribute(this ICustomAttributeProvider @this, Type attribute, bool inherit = true) 15 | { 16 | return @this.GetCustomAttributes(attribute, inherit).Any(); 17 | } 18 | 19 | public static Attribute[] GetAttributesViaName(this ICustomAttributeProvider @this, string fullName, bool inherit = true) 20 | { 21 | return @this.GetCustomAttributes(inherit).Where(x => x.GetType().FullName == fullName).OfType().ToArray(); 22 | } 23 | 24 | public static Attribute? GetAttributeViaName(this ICustomAttributeProvider @this, string fullName, bool inherit = true) 25 | { 26 | return @this.GetCustomAttributes(inherit).Where(x => x.GetType().FullName == fullName).FirstOrDefault() as Attribute; 27 | } 28 | 29 | public static bool HasAttributeViaName(this ICustomAttributeProvider @this, string fullName, bool inherit = true) 30 | { 31 | return @this.GetCustomAttributes(inherit).Where(x => x.GetType().FullName == fullName).Any(); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /NStandard/!Extensions/SystemReflection/PropertyInfoExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using System.Reflection; 3 | 4 | namespace NStandard; 5 | 6 | [EditorBrowsable(EditorBrowsableState.Never)] 7 | public static class PropertyInfoExtensions 8 | { 9 | #if NETCOREAPP1_0_OR_GREATER || NETSTANDARD1_0_OR_GREATER || NET451_OR_GREATER 10 | #else 11 | public static object GetValue(this PropertyInfo @this, object obj) => @this.GetValue(obj, null); 12 | public static void SetValue(this PropertyInfo @this, object obj, object value) => @this.SetValue(obj, value, null); 13 | #endif 14 | } 15 | -------------------------------------------------------------------------------- /NStandard/!Extensions/UInt32Extensions.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | 3 | namespace NStandard; 4 | 5 | [EditorBrowsable(EditorBrowsableState.Never)] 6 | public static class UInt32Extensions 7 | { 8 | /// 9 | /// Gets the positive integer modulus. (Unlike the operator %, this method always returns a positive number) 10 | /// 11 | /// 12 | /// 13 | /// 14 | public static uint Mod(this uint @this, uint mod) 15 | { 16 | if (@this < 0) 17 | return @this % mod + mod; 18 | else return @this % mod; 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /NStandard/!Extensions/UInt64Extensions.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | 3 | namespace NStandard; 4 | 5 | [EditorBrowsable(EditorBrowsableState.Never)] 6 | public static class UInt64Extensions 7 | { 8 | /// 9 | /// Gets the positive integer modulus. (Unlike the operator %, this method always returns a positive number) 10 | /// 11 | /// 12 | /// 13 | /// 14 | public static ulong Mod(this ulong @this, ulong mod) 15 | { 16 | if (@this < 0) 17 | return @this % mod + mod; 18 | else return @this % mod; 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /NStandard/!Static/Collections/Generic/EnumerableEx.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Static.Collections.Generic; 2 | 3 | public static class EnumerableEx 4 | { 5 | public static IEnumerable Concat(IEnumerable> enumerables) 6 | { 7 | foreach (var enumerable in enumerables) 8 | foreach (var item in enumerable) 9 | yield return item; 10 | } 11 | 12 | public static IEnumerable Concat(params IEnumerable[] enumerables) 13 | { 14 | foreach (var enumerable in enumerables) 15 | foreach (var item in enumerable) 16 | yield return item; 17 | } 18 | 19 | public static IEnumerable Create(int count, Func generate) 20 | { 21 | for (int i = 0; i < count; i++) 22 | yield return generate(i); 23 | } 24 | 25 | public static IEnumerable Create(T start, Func generate, Func condition) 26 | { 27 | int i = 0; 28 | for (T item = start; condition(item, i); item = generate(item)) 29 | { 30 | yield return item; 31 | i++; 32 | } 33 | } 34 | 35 | public static IEnumerable CreateFromLinked(TSelf @this, Func selector) 36 | { 37 | var select = @this; 38 | while (select is not null) 39 | { 40 | yield return select; 41 | select = selector(select); 42 | } 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /NStandard/!Static/ConvertEx.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Static; 2 | 3 | public static partial class ConvertEx 4 | { 5 | /// 6 | /// Returns an object of the specified type and whose value is equivalent to the specified object. 7 | /// (Enhance: Support Nullable types.) 8 | /// 9 | /// An object that implements the System.IConvertible interface. 10 | /// The type of object to return. 11 | public static object? ChangeType(object value, Type conversionType) 12 | { 13 | if (conversionType.IsNullableValue()) 14 | { 15 | if (value is null) return null; 16 | else return Convert.ChangeType(value, conversionType.GetGenericArguments()[0]); 17 | } 18 | else 19 | { 20 | if (value is null) return conversionType.CreateDefault(); 21 | else return Convert.ChangeType(value, conversionType); 22 | } 23 | } 24 | 25 | public static string ToBase58String(byte[] bytes) => Base58Converter.ToBase58String(bytes); 26 | public static byte[] FromBase58String(string str) => Base58Converter.FromBase58String(str); 27 | 28 | //TODO: Functions are being designed. 29 | //public static string ToBase32String(byte[] bytes) => Base32Converter.ToBase32String(bytes); 30 | //public static byte[] FromBase32String(string str) => Base32Converter.FromBase32String(str); 31 | } 32 | -------------------------------------------------------------------------------- /NStandard/!Static/GuidEx.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Static; 2 | 3 | public static class GuidEx 4 | { 5 | public const string EmptyString = "00000000-0000-0000-0000-000000000000"; 6 | 7 | } 8 | -------------------------------------------------------------------------------- /NStandard/!Static/Linq/Expressions/ExpressionExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Linq.Expressions; 2 | using System.Reflection; 3 | 4 | namespace NStandard.Static.Linq.Expressions; 5 | 6 | public static class ExpressionEx 7 | { 8 | /// 9 | /// Get setter expression. 10 | /// 11 | public static Expression> GetSetterExpression(Expression> expression) 12 | { 13 | if (expression.Body is MemberExpression member) 14 | { 15 | var property = (PropertyInfo)member.Member; 16 | var setMethod = property.GetSetMethod() ?? throw new NotSupportedException($"SetMethod not found. ({expression})"); 17 | var param = Expression.Parameter(typeof(T), "x"); 18 | var prop = Expression.Parameter(typeof(TProperty), "p"); 19 | var setter = 20 | Expression.Lambda>( 21 | Expression.Call(param, setMethod, prop), 22 | param, 23 | prop 24 | ); 25 | return setter; 26 | } 27 | else throw new NotSupportedException("Only MemberExpression is supported."); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /NStandard/!Static/MathEx.Permut.tt: -------------------------------------------------------------------------------- 1 | <#@ template debug="false" hostspecific="false" language="C#" #> 2 | <#@ assembly name="System.Core" #> 3 | <#@ import namespace="System.Linq" #> 4 | <#@ import namespace="System.Text" #> 5 | <#@ import namespace="System.Collections.Generic" #> 6 | <#@ output extension=".cs" #> 7 | // 8 | using System; 9 | 10 | namespace NStandard.Static; 11 | 12 | public static partial class MathEx 13 | { 14 | <#=Code("int")#> 15 | 16 | <#=Code("long")#> 17 | } 18 | 19 | <#+ 20 | private string Code(string type) 21 | { 22 | return $""" 23 | /// 24 | /// Returns the number of permutations for a given number of items that can be selected. 25 | /// 26 | /// The number of items. 27 | /// The number of items in each permutation. 28 | /// 29 | public static {type} Permut({type} number, {type} chosen) 30 | {"{"} 31 | if (chosen < 0) throw new ArgumentException("The choice must be greater than zero.", nameof(chosen)); 32 | if (number < chosen) throw new ArgumentException("The total must be greater than or equal to the choice.", nameof(chosen)); 33 | 34 | {type} ret = 1; 35 | checked 36 | {"{"} 37 | for ({type} i = number; i > number - chosen; i--) 38 | {"{"} 39 | ret *= i; 40 | {"}"} 41 | {"}"} 42 | return ret; 43 | {"}"} 44 | """; 45 | } 46 | #> 47 | -------------------------------------------------------------------------------- /NStandard/!Static/Net/IPAddressEx.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | 3 | namespace NStandard.Static.Net; 4 | 5 | public static class IPAddressEx 6 | { 7 | public static IPAddress Create(uint value) 8 | { 9 | var bytes = BitConverter.GetBytes(value); 10 | Array.Reverse(bytes); 11 | return new IPAddress(bytes); 12 | } 13 | 14 | #if NET7_0_OR_GREATER 15 | public static IPAddress Create(UInt128 value) 16 | { 17 | var bytes = BitConverterEx.GetBytes(value); 18 | Array.Reverse(bytes); 19 | return new IPAddress(bytes); 20 | } 21 | #endif 22 | } 23 | -------------------------------------------------------------------------------- /NStandard/!Static/ObjectEx.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Static; 2 | 3 | public static class ObjectEx 4 | { 5 | public static void AcceptPropValues(object source, object provider) => AcceptPropValues(source, provider, null); 6 | public static void AcceptPropValues(object source, object provider, string[]? names) 7 | { 8 | var sourceProps = source.GetType().GetProperties(); 9 | var providerProps = provider.GetType().GetProperties(); 10 | 11 | names ??= sourceProps.Select(x => x.Name).Intersect(providerProps.Select(x => x.Name)).ToArray(); 12 | 13 | foreach (var name in names) 14 | { 15 | var sourceProp = sourceProps.First(x => x.Name == name); 16 | var providerProp = providerProps.First(x => x.Name == name); 17 | 18 | if (sourceProp.PropertyType == providerProp.PropertyType) 19 | sourceProp.SetValue(source, providerProp.GetValue(provider)); 20 | } 21 | } 22 | 23 | /// 24 | /// Determines whether the specified objects are equal to each other. 25 | /// 26 | /// 27 | /// 28 | /// 29 | public static bool CrossEquals(params T[] objs) 30 | { 31 | if (objs.Length < 2) return true; 32 | 33 | foreach (var window in objs.Slide(2, true)) 34 | { 35 | if (!Equals(window[0], window[1])) return false; 36 | } 37 | return true; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /NStandard/!Static/Reflection/MethodInfoEx.cs: -------------------------------------------------------------------------------- 1 | using System.Linq.Expressions; 2 | using System.Reflection; 3 | 4 | namespace NStandard.Static.Reflection; 5 | 6 | public static class MethodInfoEx 7 | { 8 | /// 9 | /// Get MethodInfo from a method. 10 | /// 11 | /// 12 | /// 13 | /// 14 | public static MethodInfo GetMethodInfo(Expression> methodSelector) 15 | { 16 | var unary = (methodSelector.Body as UnaryExpression) ?? throw new ArgumentException("The method selector must point to a method.", nameof(methodSelector)); 17 | var operand = (unary.Operand as MethodCallExpression) ?? throw new ArgumentException("The operand must be MethodCallExpression."); 18 | var constant = (operand.Object as ConstantExpression) ?? throw new ArgumentException("The operand object must be ConstantExpression."); 19 | var method = (constant.Value as MethodInfo) ?? throw new ArgumentException("The value of operand object must be MethodInfo."); 20 | return method; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /NStandard/!Static/TypeEx.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | 3 | namespace NStandard.Static; 4 | 5 | public static class TypeEx 6 | { 7 | public const BindingFlags DeclaredOnlyLookup = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; 8 | } 9 | -------------------------------------------------------------------------------- /NStandard/!internal/BitOperations.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard; 2 | 3 | internal class BitOperations 4 | { 5 | public static uint RotateLeft(uint value, int offset) 6 | { 7 | return (value << offset) | (value >> (32 - offset)); 8 | } 9 | 10 | public static uint RotateRight(uint value, int offset) 11 | { 12 | return (value >> offset) | (value << (32 - offset)); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /NStandard/Caching/!Delegates.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Caching; 2 | 3 | /// 4 | /// 5 | /// 6 | /// 7 | /// Expiration Time 8 | public delegate DateTime UpdateCacheExpirationDelegate(DateTime cacheTime); 9 | public delegate void CacheUpdateEventDelegate(DateTime cacheTime, T value); 10 | -------------------------------------------------------------------------------- /NStandard/Caching/Cache.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | 3 | namespace NStandard.Caching; 4 | 5 | public class Cache 6 | { 7 | public static UpdateCacheExpirationDelegate DefaultUpdateExpirationMethod { get; set; } = x => DateTime.MaxValue; 8 | 9 | public Func? CacheMethod { get; set; } 10 | public UpdateCacheExpirationDelegate? UpdateExpirationMethod { get; set; } 11 | public event CacheUpdateEventDelegate? OnCacheUpdated; 12 | 13 | public DateTime CacheTime { get; protected set; } 14 | public DateTime Expiration { get; protected set; } 15 | 16 | public Cache() { } 17 | public Cache(Func? cacheMethod) 18 | { 19 | CacheMethod = cacheMethod; 20 | } 21 | 22 | protected T? _Value; 23 | 24 | public T? Value 25 | { 26 | [MethodImpl(MethodImplOptions.Synchronized)] 27 | get 28 | { 29 | if (DateTime.Now >= Expiration) Update(); 30 | return _Value; 31 | } 32 | } 33 | 34 | [MethodImpl(MethodImplOptions.Synchronized)] 35 | public void Update() 36 | { 37 | if (CacheMethod is null) throw new InvalidOperationException("No cache method is set."); 38 | 39 | CacheTime = DateTime.Now; 40 | Expiration = (UpdateExpirationMethod ?? DefaultUpdateExpirationMethod)(CacheTime); 41 | _Value = CacheMethod(); 42 | OnCacheUpdated?.Invoke(CacheTime, _Value); 43 | } 44 | 45 | [MethodImpl(MethodImplOptions.Synchronized)] 46 | public void Expire() => Expiration = DateTime.MinValue; 47 | 48 | } 49 | -------------------------------------------------------------------------------- /NStandard/Caching/CacheSet.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | 3 | namespace NStandard.Caching; 4 | 5 | public class CacheSet : Dictionary> where TKey : notnull 6 | { 7 | public Func?>? CacheMethodBuilder; 8 | public UpdateCacheExpirationDelegate? UpdateExpirationMethod; 9 | 10 | public CacheSet() { } 11 | public CacheSet(Func?>? cacheMethodBuilder) 12 | { 13 | CacheMethodBuilder = cacheMethodBuilder; 14 | } 15 | 16 | public new Cache this[TKey key] 17 | { 18 | [MethodImpl(MethodImplOptions.Synchronized)] 19 | get 20 | { 21 | if (!ContainsKey(key)) 22 | { 23 | base[key] = new Cache 24 | { 25 | CacheMethod = CacheMethodBuilder?.Invoke(key), 26 | UpdateExpirationMethod = UpdateExpirationMethod, 27 | }; 28 | } 29 | return base[key]; 30 | } 31 | } 32 | 33 | [MethodImpl(MethodImplOptions.Synchronized)] 34 | public void UpdateAll() 35 | { 36 | foreach (var key in Keys) 37 | { 38 | base[key].Update(); 39 | } 40 | } 41 | 42 | [MethodImpl(MethodImplOptions.Synchronized)] 43 | public void ExpireAll() 44 | { 45 | foreach (var key in Keys) 46 | { 47 | base[key].Expire(); 48 | } 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /NStandard/ChainOrigin.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard; 2 | 3 | public enum ChainOrigin 4 | { 5 | Begin = 0, 6 | Current = 1, 7 | End = 2, 8 | } 9 | -------------------------------------------------------------------------------- /NStandard/Collections/FixedSizeQueue.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Collections; 2 | 3 | public class FixedSizeQueue 4 | { 5 | protected readonly T?[] _store; 6 | protected readonly int _maxIndex; 7 | 8 | protected int _fillCount; 9 | 10 | public int Capacity { get; } 11 | public bool IsFilled { get; protected set; } 12 | 13 | public FixedSizeQueue(int capacity) 14 | { 15 | if (capacity < 1) throw new ArgumentException("The capacity must be greater than or equal to 1.", nameof(capacity)); 16 | 17 | Capacity = capacity; 18 | _store = new T[capacity]; 19 | _maxIndex = capacity - 1; 20 | } 21 | 22 | public void Enqueue(T? obj) 23 | { 24 | var startIndex = IsFilled ? 0 : _maxIndex - _fillCount; 25 | for (int i = startIndex; i < _maxIndex; i++) 26 | { 27 | _store[i] = _store[i + 1]; 28 | } 29 | _store[_maxIndex] = obj; 30 | 31 | if (!IsFilled) 32 | { 33 | _fillCount++; 34 | if (_fillCount == Capacity) IsFilled = true; 35 | } 36 | } 37 | 38 | public T? this[int i] 39 | { 40 | get 41 | { 42 | if (i <= _maxIndex) return _store[i]; 43 | else throw new IndexOutOfRangeException($"Index out of range (0 to {_maxIndex})."); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /NStandard/Collections/Sequence.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | 3 | namespace NStandard.Collections; 4 | 5 | public class Sequence : IEnumerable, IList 6 | { 7 | private readonly List _list = []; 8 | 9 | public Sequence() 10 | { 11 | Clear(); 12 | } 13 | 14 | public T this[int index] { get => ((IList)_list)[index]; set => ((IList)_list)[index] = value; } 15 | 16 | public int Count => ((ICollection)_list).Count; 17 | 18 | public bool IsReadOnly => ((ICollection)_list).IsReadOnly; 19 | 20 | public void Add(T value) 21 | { 22 | _list.Add(value); 23 | } 24 | 25 | public void Add(IEnumerable values) 26 | { 27 | _list.AddRange(values); 28 | } 29 | 30 | public void Clear() 31 | { 32 | _list.Clear(); 33 | } 34 | 35 | public bool Contains(T item) 36 | { 37 | return ((ICollection)_list).Contains(item); 38 | } 39 | 40 | public void CopyTo(T[] array, int arrayIndex) 41 | { 42 | ((ICollection)_list).CopyTo(array, arrayIndex); 43 | } 44 | 45 | public IEnumerator GetEnumerator() 46 | { 47 | return _list.GetEnumerator(); 48 | } 49 | 50 | public int IndexOf(T item) 51 | { 52 | return ((IList)_list).IndexOf(item); 53 | } 54 | 55 | public void Insert(int index, T item) 56 | { 57 | ((IList)_list).Insert(index, item); 58 | } 59 | 60 | public bool Remove(T item) 61 | { 62 | return ((ICollection)_list).Remove(item); 63 | } 64 | 65 | public void RemoveAt(int index) 66 | { 67 | ((IList)_list).RemoveAt(index); 68 | } 69 | 70 | IEnumerator IEnumerable.GetEnumerator() 71 | { 72 | return _list.GetEnumerator(); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /NStandard/Collections/SlidingMode.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Collections; 2 | 3 | [Flags] 4 | public enum SlidingMode 5 | { 6 | None = 0, 7 | PadLeft = 1, 8 | PadRight = 2, 9 | PadBoth = PadLeft | PadRight, 10 | } 11 | -------------------------------------------------------------------------------- /NStandard/Data/MomentType.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Data; 2 | 3 | public enum MomentType 4 | { 5 | Undefined = 0, 6 | 7 | [Obsolete("Not supported")] 8 | Nanosecond = 1, 9 | [Obsolete("Not supported")] 10 | Microsecond = Nanosecond * 0b1000, 11 | 12 | Millisecond = Microsecond * 0b1000, 13 | Second = Millisecond * 0b1000, 14 | Minute = Second * 0b100, 15 | Hour = Minute * 0b100, 16 | Day = Hour * 0b100, 17 | Week = Day * 0b10, 18 | Month = Day * 0b100, 19 | Quarter = Month * 0b10, 20 | Year = Month * 0b100, 21 | } 22 | -------------------------------------------------------------------------------- /NStandard/DataBinding/IDiff.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.DataBinding; 2 | 3 | public interface IDiff 4 | { 5 | T? OldValue { get; set; } 6 | T? NewValue { get; set; } 7 | T? Value { get; set; } 8 | } 9 | -------------------------------------------------------------------------------- /NStandard/DataBinding/ValueDiff.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | 3 | namespace NStandard.DataBinding; 4 | 5 | /// 6 | /// A value which describe a difference in state. 7 | /// 8 | /// 9 | [DebuggerDisplay("{OldValue} → {NewValue}")] 10 | public sealed class ValueDiff : IDiff 11 | { 12 | public T? OldValue { get; set; } 13 | public T? NewValue { get; set; } 14 | public T? Value 15 | { 16 | get => NewValue; 17 | set 18 | { 19 | OldValue = NewValue; 20 | NewValue = value; 21 | } 22 | } 23 | 24 | public ValueDiff() 25 | { 26 | } 27 | 28 | public ValueDiff(T value) 29 | { 30 | OldValue = value; 31 | NewValue = value; 32 | } 33 | 34 | public ValueDiff(T oldValue, T newValue) 35 | { 36 | OldValue = oldValue; 37 | NewValue = newValue; 38 | } 39 | 40 | /// 41 | /// Creates a shallow copy of the original object. 42 | /// 43 | /// 44 | public ValueDiff Clone() 45 | { 46 | return new ValueDiff 47 | { 48 | OldValue = OldValue, 49 | NewValue = NewValue, 50 | }; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /NStandard/DateMode.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard; 2 | 3 | /// 4 | /// Indicates Weekday or Weekend. 5 | /// 6 | [Flags] 7 | public enum DayMode 8 | { 9 | /// 10 | /// Undefined. 11 | /// 12 | Undefined, 13 | 14 | /// 15 | /// Indicates Monday, Tuesday, Wednesday, Thursday, Friday. 16 | /// 17 | Weekday = 1, 18 | 19 | /// 20 | /// Indicates Saturday, Sunday. 21 | /// 22 | Weekend = 2, 23 | } 24 | -------------------------------------------------------------------------------- /NStandard/DateOnlyType.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard; 2 | 3 | public enum DateOnlyType 4 | { 5 | Unspecified, 6 | Year = 1, 7 | Month = 2, 8 | Day = 4, 9 | } 10 | -------------------------------------------------------------------------------- /NStandard/DateTimeType.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard; 2 | 3 | [Flags] 4 | public enum DateTimeType 5 | { 6 | Unspecified, 7 | Year = 1, 8 | Month = 2, 9 | Day = 4, 10 | Hour = 8, 11 | Minute = 16, 12 | Second = 32, 13 | } 14 | -------------------------------------------------------------------------------- /NStandard/Design/ObsoleteMessage.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | 3 | namespace NStandard.Design; 4 | 5 | [EditorBrowsable(EditorBrowsableState.Advanced)] 6 | public static class ObsoleteMessage 7 | { 8 | public const string MayChangeOrBeRemoved = "This API may change or be removed in future releases."; 9 | } 10 | -------------------------------------------------------------------------------- /NStandard/Discards.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard; 2 | 3 | [Obsolete("Maybe it will be removed in the future.")] 4 | public class Discards 5 | { 6 | public static readonly Discards _ = new(); 7 | private Discards() { } 8 | } 9 | -------------------------------------------------------------------------------- /NStandard/DpContainer.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard; 2 | 3 | public static class DpContainer 4 | { 5 | /// 6 | /// Provides dynamic programing feature. 7 | /// 8 | /// 9 | /// 10 | /// 11 | /// 12 | public static DefaultDpContainer Create(Func, TIn, TOut> stateTransferFunc) where TIn : notnull 13 | { 14 | return new(stateTransferFunc); 15 | } 16 | } 17 | 18 | public abstract class DpContainer : Dictionary where TIn : notnull 19 | { 20 | public abstract TOut StateTransfer(TIn param); 21 | 22 | public new TOut this[TIn key] 23 | { 24 | get 25 | { 26 | var @this = this as Dictionary; 27 | if (!ContainsKey(key)) @this[key] = StateTransfer(key); 28 | return @this[key]; 29 | } 30 | set => (this as Dictionary)[key] = value; 31 | } 32 | } 33 | 34 | public class DefaultDpContainer : DpContainer where TIn : notnull 35 | { 36 | private readonly Func, TIn, TOut> StateTransferFunc; 37 | 38 | public DefaultDpContainer(Func, TIn, TOut> stateTransferFunc) 39 | { 40 | StateTransferFunc = stateTransferFunc; 41 | } 42 | 43 | public override TOut StateTransfer(TIn param) => StateTransferFunc(this, param); 44 | } 45 | -------------------------------------------------------------------------------- /NStandard/Evaluators/Bracket.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | 3 | namespace NStandard.Evaluators; 4 | 5 | public struct Bracket(string start, string end) 6 | { 7 | public string Start = start; 8 | public string End = end; 9 | 10 | [EditorBrowsable(EditorBrowsableState.Never)] 11 | public void Deconstruct(out string start, out string end) 12 | { 13 | start = Start; 14 | end = End; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /NStandard/Evaluators/Node.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Evaluators; 2 | 3 | public class Node(NodeType type, string value, int index = -1) 4 | { 5 | public NodeType NodeType { get; internal set; } = type; 6 | public int Index { get; internal set; } = index; 7 | public string Value { get; internal set; } = value; 8 | } 9 | -------------------------------------------------------------------------------- /NStandard/Evaluators/NodeType.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Evaluators; 2 | 3 | [Flags] 4 | public enum NodeType 5 | { 6 | Unspecified = 0, 7 | Operand = 1, 8 | Parameter = 2, 9 | UnaryOperator = 4, 10 | BinaryOperator = 8, 11 | StartBracket = 1024, 12 | EndBracket = 2048, 13 | } 14 | -------------------------------------------------------------------------------- /NStandard/Flows/BytesFlow.cs: -------------------------------------------------------------------------------- 1 | using NStandard.Converts; 2 | using NStandard.Static; 3 | 4 | namespace NStandard.Flows; 5 | 6 | public static class BytesFlow 7 | { 8 | public static string Base58(byte[] bytes) => ConvertEx.ToBase58String(bytes); 9 | public static string Base64(byte[] bytes) => Convert.ToBase64String(bytes); 10 | public static string HexString(byte[] bytes) => BytesConvert.ToHexString(bytes); 11 | public static string UrlSafeBase64(byte[] bytes) => StringConvert.ConvertBase64ToUrlSafeBase64(Convert.ToBase64String(bytes)); 12 | 13 | } 14 | -------------------------------------------------------------------------------- /NStandard/Flows/GuidFlow.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Flows; 2 | 3 | public static class GuidFlow 4 | { 5 | public static string HexString(Guid guid) => BytesFlow.HexString(guid.ToByteArray()); 6 | public static string Base58(Guid guid) => BytesFlow.Base58(guid.ToByteArray()); 7 | public static string Base64(Guid guid) => BytesFlow.Base64(guid.ToByteArray()); 8 | public static string UrlSafeBase64(Guid guid) => BytesFlow.UrlSafeBase64(guid.ToByteArray()); 9 | 10 | } 11 | -------------------------------------------------------------------------------- /NStandard/Flows/HashFlow.cs: -------------------------------------------------------------------------------- 1 | using NStandard.Security; 2 | 3 | namespace NStandard.Flows; 4 | 5 | public static class HashFlow 6 | { 7 | public static byte[] MD5(byte[] bytes) => Md5Hasher.Hash(bytes); 8 | public static byte[] SHA1(byte[] bytes) => Sha1Hasher.Hash(bytes); 9 | } 10 | -------------------------------------------------------------------------------- /NStandard/Flows/IPAddressFlow.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | 3 | namespace NStandard.Flows; 4 | 5 | public static class IPAddressFlow 6 | { 7 | public static long Int64(IPAddress ip) => BitConverter.ToUInt32(ip.GetAddressBytes().Reverse().ToArray(), 0); 8 | public static IPAddress IPAddress(long int64) => System.Net.IPAddress.Parse(int64.ToString()); 9 | } 10 | -------------------------------------------------------------------------------- /NStandard/Flows/NumberFlow.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | 3 | namespace NStandard.Flows; 4 | 5 | public static class NumberFlow 6 | { 7 | public static double DefaultIfNonNormal(double number) => IsNormal(number) ? number : 0; 8 | public static float DefaultIfNonNormal(float number) => IsNormal(number) ? number : 0; 9 | 10 | #if NETCOREAPP1_0_OR_GREATER || NETSTANDARD1_0_OR_GREATER || NET451_OR_GREATER 11 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 12 | #endif 13 | private unsafe static int SingleToInt32Bits(float value) 14 | { 15 | return *(int*)(&value); 16 | } 17 | 18 | private static bool IsNormal(float f) 19 | { 20 | int num = SingleToInt32Bits(f); 21 | num &= 0x7FFFFFFF; 22 | if (num < 2139095040 && num != 0) 23 | { 24 | return (num & 0x7F800000) != 0; 25 | } 26 | return false; 27 | } 28 | 29 | private static bool IsNormal(double d) 30 | { 31 | long num = BitConverter.DoubleToInt64Bits(d); 32 | num &= 0x7FFFFFFFFFFFFFFFL; 33 | if (num < 9218868437227405312L && num != 0L) 34 | { 35 | return (num & 0x7FF0000000000000L) != 0; 36 | } 37 | return false; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /NStandard/FuncDelegates.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard; 2 | 3 | public delegate TOperand UnaryFunc(TOperand operand); 4 | public delegate TOperand BinaryFunc(TOperand left, TOperand right); 5 | -------------------------------------------------------------------------------- /NStandard/ISingleton.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard; 2 | 3 | public static class Singleton where T : class, ISingleton, new() 4 | { 5 | private static readonly object _sync = new(); 6 | private static T? _instance = null; 7 | 8 | /// 9 | /// Get or create a thread-safe singleton instance. 10 | /// 11 | /// 12 | public static T? GetOrCreate() 13 | { 14 | if (_instance is null) 15 | { 16 | lock (_sync) 17 | { 18 | if (_instance is null) 19 | { 20 | _instance = new T(); 21 | _instance.OnInit(); 22 | } 23 | } 24 | } 25 | return _instance; 26 | } 27 | 28 | public static void Destory() 29 | { 30 | if (_instance is not null) 31 | { 32 | lock (_sync) 33 | { 34 | _instance = null; 35 | } 36 | } 37 | } 38 | } 39 | 40 | public static class StaticSingleton where T : class, ISingleton, new() 41 | { 42 | /// 43 | /// Get the static singleton instance. 44 | /// 45 | public static readonly T Instance; 46 | 47 | static StaticSingleton() 48 | { 49 | Instance = new T(); 50 | Instance.OnInit(); 51 | } 52 | } 53 | 54 | public interface ISingleton where TSelf : ISingleton 55 | { 56 | #if NET7_0_OR_GREATER 57 | /// 58 | /// Use or to get a singleton instance. 59 | /// 60 | public abstract static TSelf Instance { get; } 61 | #endif 62 | void OnInit(); 63 | } 64 | -------------------------------------------------------------------------------- /NStandard/Infrastructure/ChainIterator.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Infrastructure; 2 | 3 | public struct ChainIterator 4 | { 5 | public ChainOrigin Origin { get; set; } 6 | public T[] Iterators { get; set; } 7 | public int Cursor { get; set; } 8 | public T Current => Iterators[Cursor]; 9 | } 10 | -------------------------------------------------------------------------------- /NStandard/Locks/TypeLockParser.cs: -------------------------------------------------------------------------------- 1 | using NStandard.Flows; 2 | using System.Threading; 3 | 4 | namespace NStandard.Locks; 5 | 6 | public class TypeLockParser 7 | { 8 | public string LockName { get; } 9 | 10 | public TypeLockParser(string lockName) 11 | { 12 | LockName = lockName; 13 | } 14 | 15 | public virtual Lock Parse(Type type) 16 | { 17 | return new Lock(string.Intern($"[{StringFlow.UrlEncode(LockName)}<{type.FullName}>]")); 18 | } 19 | public virtual Lock Parse() 20 | { 21 | return new Lock(string.Intern($"[{StringFlow.UrlEncode(LockName)}<{typeof(TType).FullName}>]")); 22 | } 23 | 24 | public virtual Lock ParseThreadLock(Type type) 25 | { 26 | return new Lock(string.Intern($"[({Thread.CurrentThread.ManagedThreadId}){StringFlow.UrlEncode(LockName)}<{type.FullName}>]")); 27 | } 28 | public virtual Lock ParseThreadLock() 29 | { 30 | return new Lock(string.Intern($"[({Thread.CurrentThread.ManagedThreadId}){StringFlow.UrlEncode(LockName)}<{typeof(TType).FullName}>]")); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /NStandard/Measures/IMeasurable.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Measures; 2 | 3 | [Obsolete("Use IMeasurable instead.")] 4 | public interface IMeasurable 5 | { 6 | TValue Value { get; set; } 7 | } 8 | 9 | public interface IAdditionMeasurable where TSelf : IMeasurable, IAdditionMeasurable 10 | { 11 | #if NET7_0_OR_GREATER 12 | static abstract bool ForceAggregate { get; } 13 | #endif 14 | bool CanAggregate(TSelf other); 15 | } 16 | 17 | public interface IMeasurable 18 | { 19 | #if NET7_0_OR_GREATER 20 | static abstract string Measure { get; } 21 | #endif 22 | decimal Value { get; set; } 23 | } 24 | -------------------------------------------------------------------------------- /NStandard/Measures/IMeasureConvertible.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Measures; 2 | 3 | public interface IMeasureConvertible where T : IMeasurable 4 | { 5 | bool CanConvert(); 6 | T Convert(); 7 | } 8 | -------------------------------------------------------------------------------- /NStandard/Measures/MeasureAttribute.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Measures; 2 | 3 | [AttributeUsage(AttributeTargets.Struct, AllowMultiple = false)] 4 | public class MeasureAttribute : Attribute 5 | { 6 | public double Coef { get; set; } 7 | 8 | public MeasureAttribute(double coef) 9 | { 10 | Coef = coef; 11 | } 12 | } 13 | 14 | [AttributeUsage(AttributeTargets.Struct, AllowMultiple = false)] 15 | public class MeasureAttribute : Attribute 16 | { 17 | public string Name { get; set; } 18 | 19 | public MeasureAttribute(string name) 20 | { 21 | Name = name; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /NStandard/MinMaxPair.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | 3 | namespace NStandard; 4 | 5 | public static class MinMaxPair 6 | { 7 | public static MinMaxPair Create(T min, T max) 8 | { 9 | return new MinMaxPair(min, max); 10 | } 11 | } 12 | 13 | public struct MinMaxPair(T min, T max) 14 | { 15 | public T Min { get; set; } = min; 16 | public T Max { get; set; } = max; 17 | 18 | [EditorBrowsable(EditorBrowsableState.Never)] 19 | public void Deconstruct(out T min, out T max) 20 | { 21 | min = Min; 22 | max = Max; 23 | } 24 | 25 | #if NET5_0_OR_GREATER 26 | public static implicit operator MinMaxPair((T Min, T Max) tuple) 27 | { 28 | return new MinMaxPair 29 | { 30 | Min = tuple.Min, 31 | Max = tuple.Max, 32 | }; 33 | } 34 | #endif 35 | } 36 | -------------------------------------------------------------------------------- /NStandard/Ref.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | 3 | namespace NStandard; 4 | 5 | [DebuggerDisplay("{Target}")] 6 | public class Ref(T target) 7 | { 8 | public T Target { get; set; } = target; 9 | 10 | public static implicit operator Ref(T target) 11 | { 12 | return new Ref(target); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /NStandard/Reflection/FieldReflector.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | 3 | namespace NStandard.Reflection; 4 | 5 | public class FieldReflector : Reflector 6 | { 7 | public readonly FieldInfo FieldInfo; 8 | public readonly object? DeclaringObject; 9 | 10 | public FieldReflector(FieldInfo fieldInfo, object? declaringObj) : this(fieldInfo, fieldInfo.FieldType, declaringObj) { } 11 | public FieldReflector(FieldInfo fieldInfo, Type type, object? declaringObj) : base(type, declaringObj) 12 | { 13 | FieldInfo = fieldInfo; 14 | DeclaringObject = declaringObj; 15 | Object = Value; 16 | } 17 | 18 | public virtual object? Value 19 | { 20 | get => DeclaringObject?.Pipe(FieldInfo.GetValue); 21 | set 22 | { 23 | if (DeclaringObject is not null) 24 | FieldInfo.SetValue(DeclaringObject, value); 25 | else throw new AccessViolationException(); 26 | } 27 | } 28 | public virtual object? GetValue() => FieldInfo.GetValue(DeclaringObject); 29 | public void SetValue(object? value) => FieldInfo.SetValue(DeclaringObject, value); 30 | } 31 | 32 | public class FieldReflector(FieldInfo fieldInfo, object? declaringObj) : FieldReflector(fieldInfo, typeof(T), declaringObj) 33 | { 34 | public new T? Value 35 | { 36 | get => base.Value is null ? default : (T)base.Value; 37 | set => base.Value = value; 38 | } 39 | public new T? GetValue() => (T?)base.GetValue(); 40 | public void SetValue(T value) => base.SetValue(value); 41 | } 42 | -------------------------------------------------------------------------------- /NStandard/Reflection/MethodReflector.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | 3 | namespace NStandard.Reflection; 4 | 5 | public class MethodReflector(MethodInfo methodInfo, object? declaringObj) 6 | { 7 | public readonly MethodInfo MethodInfo = methodInfo; 8 | public object? DeclaringObject = declaringObj; 9 | 10 | public object? Call(params object[] parameters) 11 | { 12 | return MethodInfo is null 13 | ? throw new ArgumentNullException("The method can not be null") 14 | : MethodInfo.Invoke(DeclaringObject, parameters); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /NStandard/Reflection/PropertyReflector.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | 3 | namespace NStandard.Reflection; 4 | 5 | public class PropertyReflector : Reflector 6 | { 7 | public readonly PropertyInfo PropertyInfo; 8 | public readonly object? DeclaringObject; 9 | 10 | public PropertyReflector(PropertyInfo propertyInfo, object? declaringObj) : this(propertyInfo, propertyInfo.PropertyType, declaringObj) { } 11 | public PropertyReflector(PropertyInfo propertyInfo, Type type, object? declaringObj) : base(type, declaringObj) 12 | { 13 | PropertyInfo = propertyInfo; 14 | DeclaringObject = declaringObj; 15 | Object = Value; 16 | } 17 | 18 | public virtual object? Value 19 | { 20 | get => DeclaringObject?.Pipe(PropertyInfo.GetValue); 21 | set 22 | { 23 | if (DeclaringObject is not null) 24 | { 25 | PropertyInfo.SetValue(DeclaringObject, value!); 26 | } 27 | else throw new AccessViolationException(); 28 | } 29 | } 30 | public virtual object? GetValue() => PropertyInfo.GetValue(DeclaringObject!); 31 | public void SetValue(object? value) => PropertyInfo.SetValue(DeclaringObject!, value!); 32 | } 33 | 34 | public class PropertyReflector(PropertyInfo propertyInfo, object? declaringObj) : PropertyReflector(propertyInfo, typeof(T), declaringObj) 35 | { 36 | public new T? Value 37 | { 38 | get => base.Value is null ? default : (T)base.Value; 39 | set => base.Value = value; 40 | } 41 | 42 | public new T? GetValue() => (T?)base.GetValue(); 43 | public void SetValue(T? value) => base.SetValue(value); 44 | } 45 | -------------------------------------------------------------------------------- /NStandard/Reflection/TypeFieldReflector.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | 3 | namespace NStandard.Reflection; 4 | 5 | public class TypeFieldReflector(FieldInfo fieldInfo, Type type) : TypeReflector(type) 6 | { 7 | public readonly FieldInfo FieldInfo = fieldInfo; 8 | 9 | public TypeFieldReflector(FieldInfo fieldInfo) : this(fieldInfo, fieldInfo.FieldType) 10 | { 11 | } 12 | 13 | public virtual object? GetValue(object? obj) => FieldInfo.GetValue(obj); 14 | public void SetValue(object obj, object? value) => FieldInfo.SetValue(obj, value); 15 | } 16 | 17 | public class TypeFieldReflector(FieldInfo fieldInfo) : TypeFieldReflector(fieldInfo, typeof(T)) 18 | { 19 | public new T? GetValue(object obj) => (T?)base.GetValue(obj); 20 | public void SetValue(object obj, T? value) => base.SetValue(obj, value); 21 | } 22 | -------------------------------------------------------------------------------- /NStandard/Reflection/TypeMethodReflector.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | 3 | namespace NStandard.Reflection; 4 | 5 | public class TypeMethodReflector 6 | { 7 | public readonly MethodInfo MethodInfo; 8 | 9 | public TypeMethodReflector(MethodInfo methodInfo) 10 | { 11 | MethodInfo = methodInfo; 12 | } 13 | 14 | public object? Invoke(object obj, params object[] parameters) => MethodInfo.Invoke(obj, parameters); 15 | } 16 | -------------------------------------------------------------------------------- /NStandard/Reflection/TypePropertyReflector.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | 3 | namespace NStandard.Reflection; 4 | 5 | public class TypePropertyReflector(PropertyInfo propertyInfo, Type type) : TypeReflector(type) 6 | { 7 | public readonly PropertyInfo PropertyInfo = propertyInfo; 8 | 9 | public TypePropertyReflector(PropertyInfo propertyInfo) : this(propertyInfo, propertyInfo.PropertyType) 10 | { 11 | } 12 | 13 | public virtual object? GetValue(object? obj) => PropertyInfo.GetValue(obj!); 14 | public void SetValue(object? obj, object? value) => PropertyInfo.SetValue(obj!, value!); 15 | } 16 | 17 | public class TypePropertyReflector(PropertyInfo propertyInfo) : TypePropertyReflector(propertyInfo, typeof(T)) 18 | { 19 | public new T? GetValue(object? obj) => (T?)base.GetValue(obj); 20 | public void SetValue(object? obj, T value) => base.SetValue(obj!, value); 21 | } 22 | -------------------------------------------------------------------------------- /NStandard/ResourceAccessor.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | 3 | namespace NStandard; 4 | 5 | public class ResourceAccessor 6 | { 7 | public Assembly Assembly { get; } 8 | public string? Namespace { get; } 9 | public string[] ResourceNames { get; } 10 | 11 | public ResourceAccessor(Assembly assembly) 12 | { 13 | Assembly = assembly; 14 | var names = assembly.GetManifestResourceNames(); 15 | ResourceNames = names; 16 | 17 | if (names.Any()) 18 | { 19 | var name = names[0]; 20 | var index = name.IndexOf('.'); 21 | Namespace = name.Substring(0, index); 22 | } 23 | else Namespace = null; 24 | } 25 | 26 | public Stream? OpenStream(string name) 27 | { 28 | if (Namespace is not null) 29 | return Assembly.GetManifestResourceStream($"{Namespace}.{name}")!; 30 | else return null; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /NStandard/Schema/LoopFor.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | 3 | namespace NStandard.Schema; 4 | 5 | public static class LoopFor 6 | { 7 | public static LoopFor Create(Func init, Predicate predicate, Func final) where T : struct 8 | { 9 | return new LoopFor(init, predicate, final); 10 | } 11 | } 12 | 13 | public class LoopFor : IEnumerable where T : struct 14 | { 15 | public IEnumerable Enumerable { get; private set; } 16 | 17 | public LoopFor(Func init, Predicate predicate, Func final) 18 | { 19 | Enumerable = BuildEnumerable(init, predicate, final); 20 | } 21 | 22 | public LoopFor(IEnumerable enumerable) 23 | { 24 | Enumerable = enumerable; 25 | } 26 | 27 | private IEnumerable BuildEnumerable(Func init, Predicate predicate, Func final) 28 | { 29 | for (var param = init(); predicate(param); param = final(param)) 30 | { 31 | yield return param; 32 | } 33 | } 34 | 35 | public IEnumerator GetEnumerator() => Enumerable.GetEnumerator(); 36 | IEnumerator IEnumerable.GetEnumerator() => Enumerable.GetEnumerator(); 37 | 38 | } 39 | -------------------------------------------------------------------------------- /NStandard/Security/!Hash/Md5Hasher.cs: -------------------------------------------------------------------------------- 1 | using System.Security.Cryptography; 2 | 3 | namespace NStandard.Security; 4 | 5 | public static class Md5Hasher 6 | { 7 | public static byte[] Hash(Stream inputStream) => MD5.Create().ComputeHash(inputStream); 8 | public static byte[] Hash(byte[] buffer, int offset, int count) => MD5.Create().ComputeHash(buffer, offset, count); 9 | public static byte[] Hash(byte[] buffer) => MD5.Create().ComputeHash(buffer); 10 | } 11 | -------------------------------------------------------------------------------- /NStandard/Security/!Hash/Sha1Hasher.cs: -------------------------------------------------------------------------------- 1 | using System.Security.Cryptography; 2 | 3 | namespace NStandard.Security; 4 | 5 | public static class Sha1Hasher 6 | { 7 | public static byte[] Hash(Stream inputStream) => SHA1.Create().ComputeHash(inputStream); 8 | public static byte[] Hash(byte[] buffer, int offset, int count) => SHA1.Create().ComputeHash(buffer, offset, count); 9 | public static byte[] Hash(byte[] buffer) => SHA1.Create().ComputeHash(buffer); 10 | } 11 | -------------------------------------------------------------------------------- /NStandard/Security/!Symmetric/AesCipher.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Security; 2 | 3 | public class AesCipher : SymmetricCipher 4 | { 5 | public override int IVLength => 16; 6 | } 7 | -------------------------------------------------------------------------------- /NStandard/Security/!Symmetric/AesProvider.cs: -------------------------------------------------------------------------------- 1 | using System.Security.Cryptography; 2 | 3 | namespace NStandard.Security; 4 | 5 | public class AesProvider : SymmetricProvider 6 | { 7 | public override byte[] EmptyIV => [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; 8 | 9 | /// 10 | /// Create an AesProvider. 11 | /// 12 | /// 13 | /// 14 | public AesProvider(CipherMode cipher = CipherMode.CBC, PaddingMode padding = PaddingMode.PKCS7) : base(cipher, padding) 15 | { 16 | } 17 | 18 | /// 19 | /// Create an AesProvider. 20 | /// 21 | /// The length of Key must be 16, 24 or 32. 22 | /// 23 | /// 24 | public AesProvider(byte[] key, CipherMode cipher = CipherMode.CBC, PaddingMode padding = PaddingMode.PKCS7) : base(key, cipher, padding) 25 | { 26 | } 27 | 28 | protected override SymmetricAlgorithm CreateAlgorithm() => Aes.Create(); 29 | 30 | } 31 | -------------------------------------------------------------------------------- /NStandard/Security/!Symmetric/DesCipher.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Security; 2 | 3 | public class DesCipher : SymmetricCipher 4 | { 5 | public override int IVLength => 8; 6 | } 7 | -------------------------------------------------------------------------------- /NStandard/Security/!Symmetric/DesProvider.cs: -------------------------------------------------------------------------------- 1 | using System.Security.Cryptography; 2 | 3 | namespace NStandard.Security; 4 | 5 | public class DesProvider : SymmetricProvider 6 | { 7 | public override byte[] EmptyIV => [0, 0, 0, 0, 0, 0, 0, 0]; 8 | 9 | /// 10 | /// Create a DesProvider. 11 | /// 12 | /// 13 | /// 14 | public DesProvider(CipherMode cipher = CipherMode.CBC, PaddingMode padding = PaddingMode.PKCS7) : base(cipher, padding) 15 | { 16 | } 17 | 18 | /// 19 | /// Create a DesProvider. 20 | /// 21 | /// The length of Key must be 8. 22 | /// 23 | /// 24 | public DesProvider(byte[] key, CipherMode cipher = CipherMode.CBC, PaddingMode padding = PaddingMode.PKCS7) : base(key, cipher, padding) 25 | { 26 | } 27 | 28 | protected override SymmetricAlgorithm CreateAlgorithm() => DES.Create(); 29 | 30 | } 31 | -------------------------------------------------------------------------------- /NStandard/Security/!Symmetric/SymmetricCipher.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Security; 2 | 3 | public abstract class SymmetricCipher where TSelf : SymmetricCipher, new() 4 | { 5 | public abstract int IVLength { get; } 6 | public byte[]? Cipher { get; set; } 7 | public byte[]? IV { get; set; } 8 | 9 | public byte[] ToBytes() 10 | { 11 | return [.. Cipher, .. IV]; 12 | } 13 | 14 | public TSelf FromBytes(byte[] bytes) 15 | { 16 | var pair = new TSelf 17 | { 18 | Cipher = bytes.Slice(0, -IVLength), 19 | IV = bytes.Slice(-IVLength), 20 | }; 21 | return pair; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /NStandard/Security/!Symmetric/TripleDesCipher.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Security; 2 | 3 | public class TripleDesCipher : SymmetricCipher 4 | { 5 | public override int IVLength => 8; 6 | } 7 | -------------------------------------------------------------------------------- /NStandard/Security/!Symmetric/TripleDesProvider.cs: -------------------------------------------------------------------------------- 1 | using System.Security.Cryptography; 2 | 3 | namespace NStandard.Security; 4 | 5 | public class TripleDesProvider : SymmetricProvider 6 | { 7 | public override byte[] EmptyIV => [0, 0, 0, 0, 0, 0, 0, 0]; 8 | 9 | /// 10 | /// Create a . 11 | /// 12 | /// 13 | /// 14 | public TripleDesProvider(CipherMode cipher = CipherMode.CBC, PaddingMode padding = PaddingMode.PKCS7) : base(cipher, padding) 15 | { 16 | } 17 | 18 | /// 19 | /// Create a . 20 | /// 21 | /// The length of Key must be 8. 22 | /// 23 | /// 24 | public TripleDesProvider(byte[] key, CipherMode cipher = CipherMode.CBC, PaddingMode padding = PaddingMode.PKCS7) : base(key, cipher, padding) 25 | { 26 | } 27 | 28 | protected override SymmetricAlgorithm CreateAlgorithm() => TripleDES.Create(); 29 | 30 | } 31 | -------------------------------------------------------------------------------- /NStandard/Snowflake.cs: -------------------------------------------------------------------------------- 1 | using NStandard.Algorithm; 2 | 3 | namespace NStandard; 4 | 5 | public static class Snowflake 6 | { 7 | public static long WorkerId 8 | { 9 | get => _worker.WorkerId; 10 | set => _worker.WorkerId = value; 11 | } 12 | 13 | public static long DataCenterId 14 | { 15 | get => _worker.DataCenterId; 16 | set => _worker.DataCenterId = value; 17 | } 18 | 19 | private static readonly SnowflakeWorker _worker = new(0, 0); 20 | 21 | /// 22 | /// Generate a snowflake ID with default WorkerId and DataCenterId. 23 | /// 24 | /// 25 | public static long NewId() => _worker.NewId(); 26 | } 27 | 28 | #if NET7_0_OR_GREATER 29 | public static class Snowflake128 30 | { 31 | public static Int128 WorkerId 32 | { 33 | get => _worker.WorkerId; 34 | set => _worker.WorkerId = value; 35 | } 36 | 37 | public static Int128 DataCenterId 38 | { 39 | get => _worker.DataCenterId; 40 | set => _worker.DataCenterId = value; 41 | } 42 | 43 | private static readonly SnowflakeWorker128 _worker = new(0, 0); 44 | 45 | /// 46 | /// Generate a snowflake ID with default WorkerId and DataCenterId. 47 | /// 48 | /// 49 | public static Int128 NewId() => _worker.NewId(); 50 | 51 | /// 52 | /// Generate a snowflake ID with default WorkerId and DataCenterId. 53 | /// 54 | /// 55 | public static Guid NewGuid() => _worker.NewGuid(); 56 | } 57 | #endif 58 | -------------------------------------------------------------------------------- /NStandard/Text/Json/Converters/JsonImplConverter.cs: -------------------------------------------------------------------------------- 1 | #if NET5_0_OR_GREATER 2 | using System; 3 | using System.Text.Json; 4 | using System.Text.Json.Serialization; 5 | 6 | namespace NStandard.Text.Json.Converters; 7 | 8 | public class JsonImplConverter : JsonConverter where TDeserialize : T, new() 9 | { 10 | public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) 11 | { 12 | return JsonSerializer.Deserialize(ref reader, options); 13 | } 14 | 15 | public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) 16 | { 17 | if (value is null) 18 | { 19 | JsonSerializer.Serialize(writer, null, options); 20 | } 21 | else 22 | { 23 | var type = value.GetType(); 24 | JsonSerializer.Serialize(writer, value, type, options); 25 | } 26 | } 27 | } 28 | #endif 29 | -------------------------------------------------------------------------------- /NStandard/Text/Json/Converters/JsonValueConverter.cs: -------------------------------------------------------------------------------- 1 | #if NET5_0_OR_GREATER 2 | using System; 3 | using System.Text.Json; 4 | using System.Text.Json.Serialization; 5 | 6 | namespace NStandard.Text.Json.Converters; 7 | 8 | public class JsonValueConverter : JsonConverter where T : IJsonValue, new() 9 | { 10 | public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) 11 | { 12 | var value = JsonSerializer.Deserialize(ref reader, options); 13 | var instance = new T 14 | { 15 | RawValue = value, 16 | }; 17 | return instance; 18 | } 19 | 20 | public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) 21 | { 22 | if (value is null || value.Value is null) 23 | { 24 | JsonSerializer.Serialize(writer, null, options); 25 | } 26 | else 27 | { 28 | var type = value.Value.GetType(); 29 | JsonSerializer.Serialize(writer, value.Value, type, options); 30 | } 31 | } 32 | } 33 | #endif 34 | -------------------------------------------------------------------------------- /NStandard/Text/Json/IJsonValue.cs: -------------------------------------------------------------------------------- 1 | #if NET5_0_OR_GREATER 2 | using System.Text.Json; 3 | #endif 4 | 5 | namespace NStandard.Text.Json; 6 | 7 | public interface IJsonValue 8 | { 9 | object? Value { get; } 10 | 11 | #if NET5_0_OR_GREATER 12 | JsonElement RawValue { set; } 13 | #endif 14 | } 15 | -------------------------------------------------------------------------------- /NStandard/Text/Json/JsonAsAttribute.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Text.Json; 2 | 3 | #if NET5_0_OR_GREATER 4 | using NStandard.Text.Json.Converters; 5 | using System.Text.Json.Serialization; 6 | 7 | /// 8 | /// Serialize instance by interface type. 9 | /// 10 | /// 11 | /// 12 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false)] 13 | public class JsonAsAttribute : JsonConverterAttribute where T : TSerialize, new() 14 | { 15 | public JsonAsAttribute() : base(typeof(JsonAsConverter)) 16 | { 17 | } 18 | } 19 | #else 20 | /// 21 | /// Serialize instance by interface type. 22 | /// 23 | /// 24 | /// 25 | [Obsolete("Must be manually configured based on the actual serializer used.")] 26 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false)] 27 | public class JsonAsAttribute : Attribute where T : TSerialize, new() 28 | { 29 | public JsonAsAttribute() 30 | { 31 | } 32 | } 33 | #endif 34 | -------------------------------------------------------------------------------- /NStandard/Text/Json/JsonImplAttribute.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Text.Json; 2 | 3 | #if NET5_0_OR_GREATER 4 | using NStandard.Text.Json.Converters; 5 | using System.Text.Json.Serialization; 6 | 7 | /// 8 | /// Serialize interface by instance type. 9 | /// 10 | /// 11 | /// 12 | [AttributeUsage(AttributeTargets.Interface, AllowMultiple = false)] 13 | public class JsonImplAttribute : JsonConverterAttribute where TDeserialize : T, new() 14 | { 15 | public JsonImplAttribute() : base(typeof(JsonImplConverter)) 16 | { 17 | } 18 | } 19 | #else 20 | /// 21 | /// Serialize interface by instance type. 22 | /// 23 | /// 24 | /// 25 | [Obsolete("Must be manually configured based on the actual serializer used.")] 26 | [AttributeUsage(AttributeTargets.Interface, AllowMultiple = false)] 27 | public class JsonImplAttribute : Attribute where TDeserialize : T, new() 28 | { 29 | public JsonImplAttribute() 30 | { 31 | } 32 | } 33 | #endif 34 | -------------------------------------------------------------------------------- /NStandard/Text/Json/JsonValueAttribute.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Text.Json; 2 | 3 | #if NET5_0_OR_GREATER 4 | using NStandard.Text.Json.Converters; 5 | using System.Text.Json.Serialization; 6 | 7 | /// 8 | /// Serialize interface by the value instance type. 9 | /// 10 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false)] 11 | public class JsonValueAttribute : JsonConverterAttribute where T : IJsonValue, new() 12 | { 13 | public JsonValueAttribute() : base(typeof(JsonValueConverter)) 14 | { 15 | } 16 | } 17 | #else 18 | [Obsolete("Must be manually configured based on the actual serializer used.")] 19 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false)] 20 | public class JsonValueAttribute : Attribute where T : IJsonValue, new() 21 | { 22 | public JsonValueAttribute() 23 | { 24 | } 25 | } 26 | #endif 27 | -------------------------------------------------------------------------------- /NStandard/TimePointValue.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard; 2 | 3 | public static class TimePointValue 4 | { 5 | public static TimePointValue Create(TValue value) => new(value); 6 | } 7 | 8 | public struct TimePointValue 9 | { 10 | public TimePointValue() : this(default) { } 11 | public TimePointValue(TValue? value) 12 | { 13 | TimePoint = DateTime.Now; 14 | _value = value; 15 | } 16 | 17 | public DateTime TimePoint { get; private set; } 18 | public TimeSpan TimeSpan => DateTime.Now - TimePoint; 19 | 20 | private TValue? _value; 21 | public TValue? Value 22 | { 23 | get => _value; 24 | set 25 | { 26 | if (!Equals(_value, value)) 27 | { 28 | _value = value; 29 | TimePoint = DateTime.Now; 30 | } 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /NStandard/Trees/BinaryTree.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Trees; 2 | 3 | public class BinaryTree : IBinaryTree, TModel> 4 | { 5 | public BinaryTree() { } 6 | public BinaryTree(TModel model) 7 | { 8 | Model = model; 9 | } 10 | 11 | public TModel? Model { get; set; } 12 | public BinaryTree? Parent { get; set; } 13 | 14 | private BinaryTree? _left; 15 | public BinaryTree? LeftNode 16 | { 17 | get => _left; 18 | set 19 | { 20 | if (value is not null) 21 | { 22 | value.Parent = this; 23 | _left = value; 24 | } 25 | else 26 | { 27 | if (_left is not null) 28 | { 29 | _left.Parent = null; 30 | } 31 | _left = null; 32 | } 33 | } 34 | } 35 | 36 | private BinaryTree? _right; 37 | public BinaryTree? RightNode 38 | { 39 | get => _right; 40 | set 41 | { 42 | if (value is not null) 43 | { 44 | value.Parent = this; 45 | _right = value; 46 | } 47 | else 48 | { 49 | if (_right is not null) 50 | { 51 | _right.Parent = null; 52 | } 53 | _right = null; 54 | } 55 | } 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /NStandard/Trees/ITreeVisitable.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Trees; 2 | 3 | public interface ITreeVisitable 4 | { 5 | IEnumerable RecursiveNodes { get; } 6 | IEnumerable NonLeaves { get; } 7 | IEnumerable Leaves { get; } 8 | TSelf Visit(Func predicate); 9 | } 10 | -------------------------------------------------------------------------------- /NStandard/UnitValues/ISummable.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.UnitValues; 2 | 3 | [Obsolete("Plan to remove.")] 4 | public interface ISummable where TUnitValue : struct, IUnitValue 5 | { 6 | void QuickSum(IEnumerable values); 7 | void QuickAverage(IEnumerable values); 8 | } 9 | -------------------------------------------------------------------------------- /NStandard/UnitValues/IUnitValue.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.UnitValues; 2 | 3 | [Obsolete("Use IMeasurable instead.")] 4 | public interface IUnitValue 5 | { 6 | string Unit { get; set; } 7 | } 8 | 9 | [Obsolete("Use IMeasurable instead.")] 10 | public interface IUnitValue : IUnitValue 11 | { 12 | TValue Value { get; } 13 | TValue GetValue(string unit); 14 | } 15 | -------------------------------------------------------------------------------- /NStandard/UnitValues/IUnitValueExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | 3 | namespace NStandard; 4 | 5 | [Obsolete("Plan to remove.")] 6 | [EditorBrowsable(EditorBrowsableState.Never)] 7 | public static class IUnitValueExtensions 8 | { 9 | public static TUnitValue Unit(this TUnitValue @this, string unit) where TUnitValue : struct, UnitValues.IUnitValue 10 | { 11 | @this.Unit = unit; 12 | return @this; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /NStandard/Usings.cs: -------------------------------------------------------------------------------- 1 | global using System; 2 | global using System.Collections.Generic; 3 | global using System.IO; 4 | global using System.Linq; 5 | -------------------------------------------------------------------------------- /NStandard/Val.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | 3 | namespace NStandard; 4 | 5 | [DebuggerDisplay("{Target}")] 6 | public struct Val(T target) 7 | { 8 | public T Target { get; set; } = target; 9 | 10 | public static implicit operator Val(T target) 11 | { 12 | return new Val(target); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /NStandard/ValueTuples/IndexAndValue.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | 3 | namespace NStandard.ValueTuples; 4 | 5 | public struct IndexAndValue 6 | { 7 | public int Index; 8 | public TValue Value; 9 | 10 | public IndexAndValue(int index, TValue value) 11 | { 12 | Index = index; 13 | Value = value; 14 | } 15 | 16 | [EditorBrowsable(EditorBrowsableState.Never)] 17 | public void Deconstruct(out int index, out TValue value) 18 | { 19 | index = Index; 20 | value = Value; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /NStandard/YearWeekPair.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | 3 | namespace NStandard; 4 | 5 | [DebuggerDisplay("Week {Week}, {Year}")] 6 | public record struct YearWeekPair(int Year, int Week); 7 | -------------------------------------------------------------------------------- /Tests/NStandard.NET45.Test/FormattableStringTests.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using System; 3 | using System.Runtime.CompilerServices; 4 | 5 | namespace NStandard.NET45.Test 6 | { 7 | [TestClass] 8 | public class FormattableStringTests 9 | { 10 | [TestMethod] 11 | public void FormattableStringTest() 12 | { 13 | var now = DateTime.Now; 14 | var formattable = FormattableStringFactory.Create("Hello NStandard. ({0})", now); 15 | Assert.AreEqual($"Hello NStandard. ({now})", formattable.ToString()); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Tests/NStandard.NET45.Test/HashCodeTests.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using System; 3 | 4 | namespace NStandard.NET45.Test 5 | { 6 | [TestClass] 7 | public class HashCodeTests 8 | { 9 | [TestMethod] 10 | public void Test1() 11 | { 12 | var bytes = new byte[] { 1, 2, 3, 4, 5 }; 13 | var first = HashCode.Combine(bytes); 14 | var second = HashCode.Combine(bytes); 15 | Assert.AreEqual(first, second); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Tests/NStandard.NET45.Test/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | [assembly: AssemblyTitle("NStandard.NET45.Test")] 5 | [assembly: AssemblyDescription("")] 6 | [assembly: AssemblyConfiguration("")] 7 | [assembly: AssemblyCompany("")] 8 | [assembly: AssemblyProduct("NStandard.NET45.Test")] 9 | [assembly: AssemblyCopyright("Copyright © 2021")] 10 | [assembly: AssemblyTrademark("")] 11 | [assembly: AssemblyCulture("")] 12 | 13 | [assembly: ComVisible(false)] 14 | 15 | [assembly: Guid("cfb18713-2221-456b-82a7-4f0302ba527e")] 16 | 17 | // [assembly: AssemblyVersion("1.0.*")] 18 | [assembly: AssemblyVersion("1.0.0.0")] 19 | [assembly: AssemblyFileVersion("1.0.0.0")] 20 | -------------------------------------------------------------------------------- /Tests/NStandard.NET45.Test/TupleTests.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using System; 3 | using System.Linq; 4 | 5 | namespace NStandard.NET45.Test 6 | { 7 | [TestClass] 8 | public class TupleTests 9 | { 10 | [TestMethod] 11 | public void Test1() 12 | { 13 | var arr = new[] 14 | { 15 | Tuple.Create(3, 2), 16 | Tuple.Create(3, 1), 17 | }; 18 | var ordered = arr.OrderBy(x => x).ToArray(); 19 | Assert.AreEqual(1, ordered[0].Item2); 20 | Assert.AreEqual(2, ordered[1].Item2); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Tests/NStandard.NET45.Test/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/!Extensions/!System.Collections/!Generic/LinkedListExtensionsTests.cs: -------------------------------------------------------------------------------- 1 | using Xunit; 2 | 3 | namespace NStandard.Test; 4 | 5 | public class LinkedListExtensionsTests 6 | { 7 | [Fact] 8 | public void Test1() 9 | { 10 | var arr = new[] { 1, 2, 3, 4, 5 }; 11 | var list = new LinkedList(arr); 12 | LinkedListNode node; 13 | 14 | node = list.GetNodes().First(x => x.Value == 1); 15 | Assert.Null(node.Previous); 16 | Assert.Equal(2, node.Next.Value); 17 | 18 | node = list.GetNodes().First(x => x.Value == 3); 19 | Assert.Equal(2, node.Previous.Value); 20 | Assert.Equal(4, node.Next.Value); 21 | 22 | node = list.GetNodes().First(x => x.Value == 5); 23 | Assert.Equal(4, node.Previous.Value); 24 | Assert.Null(node.Next); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/!Extensions/!System.Net/IPAddressExtensionsTests.cs: -------------------------------------------------------------------------------- 1 | using NStandard.Static.Net; 2 | using System.Net; 3 | using Xunit; 4 | 5 | namespace NStandard.Test; 6 | 7 | public class IPAddressExtensionsTests 8 | { 9 | [Fact] 10 | public void IPv4Test() 11 | { 12 | var uint32 = IPAddress.Parse("255.0.255.0").ToUInt32(); 13 | Assert.Equal(0xFF00FF00, uint32); 14 | 15 | var str = IPAddressEx.Create(uint32).ToString(); 16 | Assert.Equal("255.0.255.0", str); 17 | } 18 | 19 | #if NET7_0_OR_GREATER 20 | [Fact] 21 | public void IPv6Test2() 22 | { 23 | var uint128 = IPAddress.Parse("FFFF:0000:FFFF:0000:FFFF:0000:FFFF:0000").ToUInt128(); 24 | Assert.Equal(new UInt128(0xFFFF0000FFFF0000, 0xFFFF0000FFFF0000), uint128); 25 | 26 | var str = IPAddressEx.Create(uint128).ToString(); 27 | Assert.Equal("ffff:0:ffff:0:ffff:0:ffff:0", str); 28 | } 29 | #endif 30 | } 31 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/!Extensions/!System.Reflection/EventInfoExtensionsTests.cs: -------------------------------------------------------------------------------- 1 | using Xunit; 2 | 3 | namespace NStandard.Test; 4 | 5 | public class EventInfoExtensionsTests 6 | { 7 | private class OneClass 8 | { 9 | public static void Func(List list) => list.Add(DateTime.Now); 10 | public event Action> Event; 11 | public void CallEvent(List list) => Event?.Invoke(list); 12 | } 13 | 14 | [Fact] 15 | public void Test1() 16 | { 17 | var one = new OneClass(); 18 | var eventType = typeof(OneClass).GetEvent(nameof(OneClass.Event)); 19 | var functionType = typeof(OneClass).GetMethod(nameof(OneClass.Func)); 20 | 21 | one.Event += OneClass.Func; 22 | eventType.AddEventHandler(one, functionType); 23 | 24 | var list = new List(); 25 | one.CallEvent(list); 26 | Assert.Equal(2, list.Count); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/!Extensions/!System.Threading/!Tasks/TaskExtensionsTests.cs: -------------------------------------------------------------------------------- 1 | using Xunit; 2 | 3 | namespace NStandard.Test; 4 | 5 | public class TaskExtensionsTests 6 | { 7 | [Fact] 8 | public void CatchTest() 9 | { 10 | var task = Task.Run(() => 11 | { 12 | Thread.Sleep(1000); 13 | throw new InvalidOperationException("Exception..."); 14 | }); 15 | 16 | Exception exception = null; 17 | task.Catch(ex => exception = ex); 18 | Assert.Equal("Exception...", exception.InnerException.Message); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/!Extensions/AppDomainExtensionsTests.cs: -------------------------------------------------------------------------------- 1 | using Xunit; 2 | 3 | namespace NStandard.Test; 4 | 5 | public class AppDomainExtensionsTests 6 | { 7 | [Fact] 8 | public void Test1() 9 | { 10 | var coreLib = AppDomain.CurrentDomain.GetCoreLibAssembly(); 11 | var sr = coreLib.GetType("System.SR").GetDeclaredMethodViaQualifiedName("System.String GetResourceString(System.String)"); 12 | var resourceString = sr.Invoke(null, ["Argument_EnumTypeDoesNotMatch"]); 13 | 14 | Assert.Equal("The argument type, '{0}', is not the same as the enum type '{1}'.", resourceString); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/!Extensions/AssemblyExtensionsTests.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using Xunit; 3 | 4 | namespace NStandard.Test; 5 | 6 | public class AssemblyExtensionsTests 7 | { 8 | public interface IA { } 9 | 10 | public class A : IA { } 11 | public class B : A { } 12 | [Mark] 13 | public class C : B { } 14 | 15 | public class MarkAttribute : Attribute { } 16 | 17 | [Fact] 18 | public void Test1() 19 | { 20 | var assembly = Assembly.GetExecutingAssembly(); 21 | 22 | Assert.Equal([typeof(B)], assembly.GetTypesWhichExtends(false)); 23 | Assert.Equal([typeof(B), typeof(C)], assembly.GetTypesWhichExtends(true)); 24 | 25 | Assert.Equal([typeof(A), typeof(B), typeof(C)], assembly.GetTypesWhichImplements()); 26 | Assert.Equal([typeof(C)], assembly.GetTypesWhichMarkedAs()); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/!Static/Collections/Generic/EnumerableExTests.cs: -------------------------------------------------------------------------------- 1 | using NStandard.Static.Collections.Generic; 2 | using Xunit; 3 | 4 | namespace NStandard.Test; 5 | 6 | public class EnumerableExTests 7 | { 8 | [Fact] 9 | public void Test1() 10 | { 11 | static IEnumerable Range(int start, int end) 12 | { 13 | for (int i = start; i <= end; i++) 14 | { 15 | yield return i; 16 | } 17 | } 18 | 19 | var ranges = new[] 20 | { 21 | Range(1, 3), 22 | Range(4, 6), 23 | Range(7, 9), 24 | }.AsEnumerable(); 25 | 26 | var s = EnumerableEx.Concat(ranges).Join(""); 27 | Assert.Equal("123456789", s); 28 | } 29 | 30 | [Fact] 31 | public void Test2() 32 | { 33 | var s = new string(EnumerableEx.Concat("123", "456", "789").ToArray()); 34 | Assert.Equal("123456789", s); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/!Static/ConvertExTests.cs: -------------------------------------------------------------------------------- 1 | using NStandard.Static; 2 | using System.Text; 3 | using Xunit; 4 | 5 | namespace NStandard.Test; 6 | 7 | public class ConvertExTests 8 | { 9 | [Fact] 10 | public void ChangeTypeTest() 11 | { 12 | DateTime? ndt, expected; 13 | 14 | ndt = ConvertEx.ChangeType("2019/12/11 8:58:57", typeof(DateTime?)) as DateTime?; 15 | expected = (DateTime?)DateTime.Parse("2019/12/11 8:58:57"); 16 | Assert.Equal(expected, ndt); 17 | 18 | ndt = ConvertEx.ChangeType(null, typeof(DateTime?)) as DateTime?; 19 | Assert.Null(ndt); 20 | 21 | Assert.Throws(() => Convert.ChangeType("2019/12/11 8:58:57", typeof(DateTime?))); 22 | } 23 | 24 | [Fact] 25 | public void Base58Test() 26 | { 27 | Assert.Equal("zpsEBKbce3iT", ConvertEx.ToBase58String("NStandard".Pipe(Encoding.UTF8.GetBytes))); 28 | Assert.Equal("NStandard", ConvertEx.FromBase58String("zpsEBKbce3iT").Pipe(Encoding.UTF8.GetString)); 29 | 30 | Assert.Equal("111zpsEBKbce3iT", ConvertEx.ToBase58String("\0\0\0NStandard".Pipe(Encoding.UTF8.GetBytes))); 31 | Assert.Equal("\0\0\0NStandard", ConvertEx.FromBase58String("111zpsEBKbce3iT").Pipe(Encoding.UTF8.GetString)); 32 | } 33 | 34 | [Fact] 35 | public void Base32Test() 36 | { 37 | } 38 | 39 | } -------------------------------------------------------------------------------- /Tests/NStandard.Test/!Static/Drawing/ColorExTests.cs: -------------------------------------------------------------------------------- 1 | using NStandard.Static.Drawing; 2 | using System.Drawing; 3 | using Xunit; 4 | 5 | namespace NStandard.Test; 6 | 7 | public class ColorExTests 8 | { 9 | [Fact] 10 | public void AhsvTest() 11 | { 12 | var random = new Random(); 13 | int step(int i) => random.Next(256 - i) % 3 + 1; 14 | 15 | for (var r = 0; r < 256; r += step(r)) 16 | { 17 | for (var g = 0; g < 256; g += step(g)) 18 | { 19 | for (var b = 0; b < 256; b += step(b)) 20 | { 21 | var color = Color.FromArgb(r, g, b); 22 | var ashvColor = ColorEx.CreateFromAhsv 23 | (color.GetHueOfHsv(), color.GetSaturationOfHsv(), color.GetValueOfHsv()); 24 | 25 | Assert.Equal(color, ashvColor); 26 | } 27 | } 28 | } 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/!Static/GuidEx.cs: -------------------------------------------------------------------------------- 1 | using NStandard.Static; 2 | using Xunit; 3 | 4 | namespace NStandard.Test; 5 | 6 | public class GuidExTest 7 | { 8 | [Fact] 9 | public void Test1() 10 | { 11 | Assert.Equal(Guid.Empty.ToString(), GuidEx.EmptyString); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/!Static/Linq/Expressions/ExpressionExTests.cs: -------------------------------------------------------------------------------- 1 | using NStandard.Static.Linq.Expressions; 2 | using System.Linq.Expressions; 3 | using Xunit; 4 | namespace NStandard.Test; 5 | 6 | public class ExpressionExTests 7 | { 8 | public class Model 9 | { 10 | public string Name { get; set; } 11 | public int Value { get; set; } 12 | } 13 | 14 | [Fact] 15 | public void Test1() 16 | { 17 | var model = new Model { Name = "A" }; 18 | Expression> exp = x => x.Value; 19 | var setter = ExpressionEx.GetSetterExpression(exp).Compile(); 20 | setter(model, 100); 21 | Assert.Equal(100, model.Value); 22 | } 23 | } 24 | 25 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/!Static/ObjectExTests.cs: -------------------------------------------------------------------------------- 1 | using NStandard.Static; 2 | using Xunit; 3 | 4 | namespace NStandard.Test; 5 | 6 | public class ObjectExTests 7 | { 8 | private class Cls 9 | { 10 | public int A { get; set; } 11 | public int B { get; set; } 12 | } 13 | 14 | [Fact] 15 | public void Test1() 16 | { 17 | var a = new Cls { A = 123, B = 234 }; 18 | 19 | ObjectEx.AcceptPropValues(a, new { A = 111 }); 20 | Assert.Equal(111, a.A); 21 | Assert.Equal(234, a.B); 22 | } 23 | 24 | [Fact] 25 | public void CrossEqualsTest() 26 | { 27 | Assert.True(ObjectEx.CrossEquals(1, 1, 1)); 28 | Assert.False(ObjectEx.CrossEquals(1, 1, 2)); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/!Static/Reflection/MethodInfoExTests.cs: -------------------------------------------------------------------------------- 1 | using NStandard.Static.Reflection; 2 | using Xunit; 3 | 4 | namespace NStandard.Test; 5 | 6 | public class MethodInfoExTests 7 | { 8 | [Fact] 9 | public void Test() 10 | { 11 | var method1 = MethodInfoEx.GetMethodInfo(() => MethodInfoEx.GetMethodInfo); 12 | var method2 = MethodInfoEx.GetMethodInfo(() => MethodInfoEx.GetMethodInfo); 13 | Assert.Equal(method1, method2); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/!data-structures/IntClass.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Test; 2 | 3 | public class IntClass 4 | { 5 | public int Value { get; set; } 6 | } 7 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/!data-structures/IntStrcut.cs: -------------------------------------------------------------------------------- 1 | namespace NStandard.Test; 2 | 3 | public struct IntStrcut 4 | { 5 | public int Value { get; set; } 6 | } 7 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/!extern/IEnumerableExtensions.MaxOrDefault.cs: -------------------------------------------------------------------------------- 1 | namespace LinqSharp; 2 | 3 | public static partial class IEnumerableExtensions 4 | { 5 | public static int MaxOrDefault(this IEnumerable source, int @default = default(int)) => source.Any() ? source.Max() : @default; 6 | } 7 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/!extern/IEnumerableExtensions.WhereMax.cs: -------------------------------------------------------------------------------- 1 | namespace LinqSharp; 2 | 3 | public static partial class IEnumerableExtensions 4 | { 5 | public static IEnumerable WhereMax(this IEnumerable source, Func selector) 6 | { 7 | if (source.Any()) 8 | { 9 | var max = source.Max(selector); 10 | return source.Where(x => selector(x).Equals(max)); 11 | } 12 | else return source; 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/!extern/IEnumerableExtensions.WhereMin.cs: -------------------------------------------------------------------------------- 1 | namespace LinqSharp; 2 | 3 | public static partial class IEnumerableExtensions 4 | { 5 | public static IEnumerable WhereMin(this IEnumerable source, Func selector) 6 | { 7 | if (source.Any()) 8 | { 9 | var min = source.Min(selector); 10 | return source.Where(x => selector(x).Equals(min)); 11 | } 12 | else return source; 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/ArrayVisitorTests.cs: -------------------------------------------------------------------------------- 1 | using NStandard.Collections; 2 | using Xunit; 3 | 4 | namespace NStandard.Test; 5 | 6 | public class ArrayVisitorTests 7 | { 8 | [Fact] 9 | public void TypeNotSameTest() 10 | { 11 | var src = new string[4, 4].Let((i0, i1) => $"{i0}, {i1}"); 12 | var visitor = new ArrayVisitor(src); 13 | Assert.Throws(() => visitor.GetValue(0)); 14 | } 15 | 16 | [Fact] 17 | public void Test() 18 | { 19 | var src = new string[4, 4].Let((i0, i1) => $"{i0}, {i1}"); 20 | var visitor = new ArrayVisitor(src); 21 | visitor.SetValue("-", 15); 22 | Assert.Equal("-", src[3, 3]); 23 | Assert.Equal("-", visitor.GetValue(15)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/CacheContainerTests.cs: -------------------------------------------------------------------------------- 1 | using NStandard.Caching; 2 | using Xunit; 3 | 4 | namespace NStandard.Test; 5 | 6 | public class CacheContainerTests 7 | { 8 | [Fact] 9 | public void Test1() 10 | { 11 | var cacheContainer = new CacheSet 12 | { 13 | CacheMethodBuilder = key => () => Guid.NewGuid(), 14 | UpdateExpirationMethod = cacheTime => cacheTime.Add(TimeSpan.FromMilliseconds(100)), 15 | }; 16 | 17 | var a0 = cacheContainer["a"].Value; 18 | var a1 = cacheContainer["a"].Value; 19 | 20 | var b0 = cacheContainer["b"].Value; 21 | Thread.Sleep(100); 22 | var b1 = cacheContainer["b"].Value; 23 | 24 | Assert.Equal(a0, a1); 25 | Assert.NotEqual(b0, b1); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/CacheTests.cs: -------------------------------------------------------------------------------- 1 | using NStandard.Caching; 2 | using NStandard.Diagnostics; 3 | using Xunit; 4 | 5 | namespace NStandard.Test; 6 | 7 | public class CacheTests 8 | { 9 | [Fact] 10 | public void Test1() 11 | { 12 | var cache = new Cache 13 | { 14 | CacheMethod = () => DateTime.Now, 15 | UpdateExpirationMethod = cacheTime => cacheTime.Add(TimeSpan.FromSeconds(1)), 16 | }; 17 | 18 | var updateCount = 0; 19 | cache.OnCacheUpdated += (cacheTime, value) => updateCount += 1; 20 | 21 | var report = Concurrency.Run(id => 22 | { 23 | var value = cache.Value; 24 | Console.WriteLine($"{id}\t{cache}"); 25 | Thread.Sleep(500); 26 | return value; 27 | }, 20); 28 | 29 | var reportUpdate = report.Results.Select(x => x.Return).Distinct().Count(); 30 | Assert.Equal(updateCount, reportUpdate); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/ChainPropertyTests.cs: -------------------------------------------------------------------------------- 1 | using Xunit; 2 | 3 | namespace NStandard.Test; 4 | 5 | public class ChainPropertyTests 6 | { 7 | public class Book 8 | { 9 | public string Name { get; set; } 10 | public Editor Author { get; set; } 11 | } 12 | 13 | public class Editor 14 | { 15 | public string Description { get; set; } 16 | } 17 | 18 | private static readonly Book _book = new Book 19 | { 20 | Name = "abc", 21 | Author = new Editor 22 | { 23 | Description = "author", 24 | } 25 | }; 26 | 27 | [Fact] 28 | public void Test0() 29 | { 30 | Assert.Throws(() => typeof(Book).GetChainProperty()); 31 | } 32 | 33 | [Fact] 34 | public void Test1() 35 | { 36 | var prop = typeof(Book).GetChainProperty(nameof(Book.Author)); 37 | var author = prop.GetValue(_book); 38 | Assert.Equal(_book.Author, author); 39 | } 40 | 41 | [Fact] 42 | public void Test2() 43 | { 44 | var prop = typeof(Book).GetChainProperty(nameof(Book.Author), nameof(Editor.Description)); 45 | var desc = prop.GetValue(_book.Author); 46 | Assert.Equal(_book.Author.Description, desc); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/Collections/FixedSizeQueueTests.cs: -------------------------------------------------------------------------------- 1 | using Xunit; 2 | 3 | namespace NStandard.Collections.Test; 4 | 5 | public class FixedSizeQueueTests 6 | { 7 | [Fact] 8 | public void Test() 9 | { 10 | var queue = new FixedSizeQueue(2); 11 | queue.Enqueue(1); 12 | queue.Enqueue(2); 13 | 14 | Assert.Equal(1, queue[0]); 15 | Assert.Equal(2, queue[1]); 16 | 17 | queue.Enqueue(3); 18 | 19 | Assert.Equal(2, queue[0]); 20 | Assert.Equal(3, queue[1]); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/Collections/SequnceTests.cs: -------------------------------------------------------------------------------- 1 | using Xunit; 2 | 3 | namespace NStandard.Collections.Test; 4 | 5 | public class SequnceTests 6 | { 7 | [Fact] 8 | public void Test1() 9 | { 10 | var sequence = new Sequence 11 | { 12 | 1, 2, 3, 13 | new[] { 4, 5 }, 14 | }; 15 | Assert.Equal(new[] 16 | { 17 | 1, 2, 3, 4, 5 18 | }, sequence); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/ConsoleContextTests.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | using Xunit; 3 | 4 | namespace NStandard.Test; 5 | 6 | public class ConsoleContextTests 7 | { 8 | [Fact] 9 | public void UseDefeaultWriterTest() 10 | { 11 | var outBuilder = new StringBuilder(); 12 | var errorBuilder = new StringBuilder(); 13 | 14 | using (ConsoleContext.Begin()) 15 | { 16 | Console.SetOut(new StringWriter(outBuilder)); 17 | Console.SetError(new StringWriter(errorBuilder)); 18 | 19 | Console.Write(123); 20 | Console.Error.Write("e"); 21 | Console.Write(456); 22 | Assert.Equal("123456", outBuilder.ToString()); 23 | Assert.Equal("e", errorBuilder.ToString()); 24 | } 25 | 26 | outBuilder.Clear(); 27 | errorBuilder.Clear(); 28 | 29 | using (ConsoleContext.Begin()) 30 | { 31 | Console.SetOut(new StringWriter(outBuilder)); 32 | 33 | Console.Write(123); 34 | Console.Error.Write("e"); 35 | Console.Write(456); 36 | Assert.Equal("123456", outBuilder.ToString()); 37 | Assert.Equal("", errorBuilder.ToString()); 38 | } 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/Data/FractionTests.cs: -------------------------------------------------------------------------------- 1 | using NStandard.Data; 2 | using Xunit; 3 | 4 | namespace NStandard.Test.Data; 5 | 6 | public class FractionTests 7 | { 8 | [Fact] 9 | public void PowTest() 10 | { 11 | var fraction = new Fraction(2, 3); 12 | Assert.Equal(Fraction.One, fraction.Pow(0)); 13 | Assert.Equal(fraction, fraction.Pow(1)); 14 | Assert.Equal(new(4, 9), fraction.Pow(2)); 15 | Assert.Equal(new(8, 27), fraction.Pow(3)); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/Data/MathFunctionTests.cs: -------------------------------------------------------------------------------- 1 | using NStandard.Data.Mathematics; 2 | using Xunit; 3 | 4 | namespace NStandard.Data.Test; 5 | 6 | public class MathFunctionTests 7 | { 8 | static Func x = MathConstant.Parameter; 9 | static Func inverse = MathConstant.Inverse; 10 | 11 | [Fact] 12 | public void Test() 13 | { 14 | var y = 2 * x(2) + 2 * x(1) + 1; 15 | Assert.Equal("2·x^{2} + 2·x + 1", y.ToString()); 16 | var y_1 = inverse(y); 17 | Assert.Equal("\\frac{1}{2} · \\sqrt{2·x - 1} - \\frac{1}{2}", y_1.ToString()); 18 | } 19 | 20 | [Fact] 21 | public void Temperature_CtoF_Test() 22 | { 23 | var f = (320 + 18 * x(1)) / 10; 24 | Assert.Equal("\\frac{9}{5}·x + 32", f.ToString()); 25 | var c = inverse(f); 26 | Assert.Equal("\\frac{5}{9}·x - \\frac{160}{9}", c.ToString()); 27 | } 28 | 29 | [Fact] 30 | public void Temperature_FtoC_Test() 31 | { 32 | var c = (10 * x(1) - 320) / 18; 33 | Assert.Equal("\\frac{5}{9}·x - \\frac{160}{9}", c.ToString()); 34 | var f = inverse(c); 35 | Assert.Equal("\\frac{9}{5}·x + 32", f.ToString()); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/DpContainerTests - DpCoin.cs: -------------------------------------------------------------------------------- 1 | using LinqSharp; 2 | using Xunit; 3 | 4 | namespace NStandard.Test; 5 | 6 | public partial class DpContainerTests 7 | { 8 | public class DpCoin : DpContainer 9 | { 10 | public class Result 11 | { 12 | public int CoinCount; 13 | public int[] Coins; 14 | } 15 | 16 | public int[] CoinValues { get; private set; } 17 | 18 | public DpCoin(int[] coinValues) 19 | { 20 | CoinValues = coinValues; 21 | } 22 | 23 | public override Result StateTransfer(int n) 24 | { 25 | // dp(n) = 0 if n = 0 26 | // dp(n) = min { v | d(n-v) + 1 } if n - v >= 0, v = { CoinValues } 27 | 28 | if (n == 0) return new Result { CoinCount = 0, Coins = Array.Empty() }; 29 | 30 | var take_v = CoinValues 31 | .Where(v => n - v >= 0) 32 | .WhereMin(v => this[n - v].CoinCount) 33 | .First(); 34 | var preResult = this[n - take_v]; 35 | 36 | return new Result 37 | { 38 | CoinCount = preResult.CoinCount + 1, 39 | Coins = [.. preResult.Coins, take_v], 40 | }; 41 | } 42 | } 43 | 44 | [Fact] 45 | public void DpCoinTest() 46 | { 47 | var dpCoin = new DpCoin([1, 2, 4, 5]); 48 | var result8 = dpCoin[8]; 49 | 50 | Assert.Equal(2, result8.CoinCount); 51 | Assert.Equal([4, 4], result8.Coins); 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/DpContainerTests - DpFib.cs: -------------------------------------------------------------------------------- 1 | using Xunit; 2 | 3 | namespace NStandard.Test; 4 | 5 | public partial class DpContainerTests 6 | { 7 | public class DpFib : DpContainer 8 | { 9 | public override int StateTransfer(int n) 10 | { 11 | if (n == 0 || n == 1) return 1; 12 | else return this[n - 1] + this[n - 2]; 13 | } 14 | } 15 | 16 | [Fact] 17 | public void DpFibTest1() 18 | { 19 | var fib = new DpFib(); 20 | Assert.Equal(1836311903, fib[45]); 21 | } 22 | 23 | public int BadFib(int n) 24 | { 25 | if (n == 0 || n == 1) return 1; 26 | else return BadFib(n - 1) + BadFib(n - 2); 27 | } 28 | 29 | public int Fib(DefaultDpContainer dp, int n) 30 | { 31 | if (n == 0 || n == 1) return 1; 32 | else return dp[n - 1] + dp[n - 2]; 33 | } 34 | 35 | [Fact] 36 | public void DpFibTest2() 37 | { 38 | var fib = DpContainer.Create(Fib); 39 | Assert.Equal(1836311903, fib[45]); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/EnumOptionTests.cs: -------------------------------------------------------------------------------- 1 | using Xunit; 2 | 3 | namespace NStandard.Test; 4 | 5 | public class EnumOptionTests 6 | { 7 | private enum ETest { Default = 16 } 8 | 9 | [Fact] 10 | public void Test1() 11 | { 12 | var a0 = new EnumOption(typeof(ETest), nameof(ETest.Default)); 13 | var a1 = new EnumOption(typeof(ETest), nameof(ETest.Default)); 14 | Assert.Equal(a0, a1); 15 | } 16 | 17 | [Fact] 18 | public void Test2() 19 | { 20 | var a0 = new EnumOption(typeof(ETest), nameof(ETest.Default)); 21 | var b0 = new EnumOption(nameof(ETest.Default)); 22 | var b1 = new EnumOption(16); 23 | Assert.Equal(a0, b0); 24 | Assert.Equal(b0, a0); 25 | Assert.Equal(b0, b1); 26 | Assert.Throws(() => new EnumOption(16)); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/Flows/GuidFlowTests.cs: -------------------------------------------------------------------------------- 1 | using NStandard.Flows; 2 | using Xunit; 3 | 4 | namespace NStandard.Test; 5 | 6 | public class GuidFlowTests 7 | { 8 | [Fact] 9 | public void Test1() 10 | { 11 | var guid = Guid.Parse("d19eaa91-337a-4853-9e93-52dfb50b3e31"); 12 | 13 | Assert.Equal("kaqe0XozU0iek1LftQs-MQ", guid.Pipe(GuidFlow.UrlSafeBase64)); 14 | Assert.Equal(guid, "kaqe0XozU0iek1LftQs-MQ".Pipe(StringFlow.GuidFromUrlSafeBase64)); 15 | 16 | Assert.Equal("91aa9ed17a3353489e9352dfb50b3e31", guid.Pipe(GuidFlow.HexString)); 17 | Assert.Equal(guid, "91aa9ed17a3353489e9352dfb50b3e31".Pipe(StringFlow.GuidFromHexString)); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/Flows/IPAddressFlowTests.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using Xunit; 3 | 4 | namespace NStandard.Flows.Test; 5 | 6 | public class IPAddressFlowTests 7 | { 8 | [Fact] 9 | public void Test1() 10 | { 11 | Assert.Equal(0x7f000001, IPAddress.Parse("127.0.0.1").Pipe(IPAddressFlow.Int64)); 12 | Assert.Equal(0x7f000002, IPAddress.Parse("127.0.0.2").Pipe(IPAddressFlow.Int64)); 13 | 14 | Assert.Equal("127.0.0.1", ((long)0x7f000001).Pipe(IPAddressFlow.IPAddress).ToString()); 15 | Assert.Equal("127.0.0.2", ((long)0x7f000002).Pipe(IPAddressFlow.IPAddress).ToString()); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/IO/SequenceInputStreamTests.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | using Xunit; 3 | 4 | namespace NStandard.IO.Test; 5 | 6 | public class SequenceInputStreamTests 7 | { 8 | [Fact] 9 | public void Test1() 10 | { 11 | using var stream = new SequenceInputStream( 12 | new MemoryStream("123".Pipe(Encoding.UTF8.GetBytes)), 13 | new MemoryStream("456".Pipe(Encoding.UTF8.GetBytes)), 14 | new MemoryStream("789".Pipe(Encoding.UTF8.GetBytes)) 15 | ); 16 | using var reader = new StreamReader(stream); 17 | 18 | Assert.Equal("123456789", reader.ReadToEnd()); 19 | } 20 | } -------------------------------------------------------------------------------- /Tests/NStandard.Test/ISliceTests.cs: -------------------------------------------------------------------------------- 1 | using Xunit; 2 | 3 | namespace NStandard.Test; 4 | 5 | public class ISliceTests 6 | { 7 | public class SliceCount : ISliceCount 8 | { 9 | public int[] Numbers = [0, 1, 2, 3]; 10 | 11 | public int Count => Numbers.Length; 12 | 13 | public int[] Slice(int start, int length) 14 | { 15 | var slice = new int[length]; 16 | Array.Copy(Numbers, start, slice, 0, length); 17 | return slice; 18 | } 19 | } 20 | 21 | public class SliceLength : ISliceLength 22 | { 23 | public int[] Numbers = [0, 1, 2, 3]; 24 | public int Length => Numbers.Length; 25 | 26 | public int[] Slice(int start, int length) 27 | { 28 | var slice = new int[length]; 29 | Array.Copy(Numbers, start, slice, 0, length); 30 | return slice; 31 | } 32 | } 33 | 34 | [Fact] 35 | public void SliceCountTest() 36 | { 37 | var slice = new SliceCount(); 38 | var result = slice[1..^1]; 39 | Assert.Equal([1, 2], result); 40 | } 41 | 42 | [Fact] 43 | public void SliceLengthTest() 44 | { 45 | var slice = new SliceLength(); 46 | var result = slice[1..^1]; 47 | Assert.Equal([1, 2], result); 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/Json/DateOnlyTests.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using NStandard.Json.Converters; 3 | using NStandard.Static; 4 | using System.Text.Json; 5 | using Xunit; 6 | using NewtonsoftJson = Newtonsoft.Json.JsonConvert; 7 | using SystemJson = System.Text.Json.JsonSerializer; 8 | 9 | namespace NStandard.Json.Test; 10 | 11 | public class DateOnlyTests 12 | { 13 | private readonly JsonSerializerOptions _options = Any.Create(() => 14 | { 15 | var options = new JsonSerializerOptions(); 16 | options.Converters.Add(new DateOnlyConverter()); 17 | return options; 18 | }); 19 | private readonly JsonSerializerSettings _settings = new() 20 | { 21 | Converters = [new Net.Converters.DateOnlyConverter()], 22 | }; 23 | 24 | private void Assert_Serialize(string expected, T actual) 25 | { 26 | Assert.Equal(expected, SystemJson.Serialize(actual, _options)); 27 | Assert.Equal(expected, NewtonsoftJson.SerializeObject(actual, _settings)); 28 | } 29 | private void Assert_Deserialize(T expected, string actual) 30 | { 31 | Assert.Equal(expected, SystemJson.Deserialize(actual, _options)); 32 | Assert.Equal(expected, NewtonsoftJson.DeserializeObject(actual, _settings)); 33 | } 34 | 35 | private readonly DateOnly Today = DateOnlyEx.Today; 36 | private readonly DateOnly? NullableToday = null; 37 | 38 | [Fact] 39 | public void SerializeTest() 40 | { 41 | Assert_Serialize($"\"{Today:O}\"", Today); 42 | Assert_Serialize("null", NullableToday); 43 | } 44 | 45 | [Fact] 46 | public void DeserializeTest() 47 | { 48 | Assert_Deserialize(Today, $"\"{Today:O}\""); 49 | Assert_Deserialize(NullableToday, "null"); 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/Locks/InstanceLockTest.cs: -------------------------------------------------------------------------------- 1 | using NStandard.Diagnostics; 2 | using Xunit; 3 | 4 | namespace NStandard.Locks.Test; 5 | 6 | public class InstanceLockTest 7 | { 8 | public enum Sex { Male, Female } 9 | 10 | public class Model 11 | { 12 | public int Year { get; set; } 13 | public int Month { get; set; } 14 | public object Obj { get; set; } 15 | public Sex Sex { get; set; } 16 | public string Name { get; set; } 17 | } 18 | 19 | [Fact] 20 | public void Test() 21 | { 22 | var lockParser = new InstanceLockParser(nameof(NStandard), x => x.Year, x => x.Month, x => x.Sex, x => "const"); 23 | var model = new Model { Year = 2012, Month = 4, }; 24 | 25 | var report = Concurrency.Run(resultId => 26 | { 27 | using var _lock = lockParser.Parse(model).TryBegin(500); 28 | 29 | if (_lock.Value) 30 | { 31 | Thread.Sleep(1000); 32 | return "Entered"; 33 | } 34 | else return "Timeout"; 35 | }, level: 2, threadCount: 2); 36 | 37 | Assert.Equal(1, report.Results.Count(x => x.Return == "Entered")); 38 | Assert.Equal(1, report.Results.Count(x => x.Return == "Timeout")); 39 | Assert.True(report.AverageElapsed?.TotalMilliseconds < 2000); 40 | } 41 | 42 | [Fact] 43 | public void WrongInitializeTest() 44 | { 45 | Assert.ThrowsAny(() => new InstanceLockParser(nameof(NStandard), x => x.Year, x => x.Obj)); 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/Locks/TypeLockTest.cs: -------------------------------------------------------------------------------- 1 | using NStandard.Diagnostics; 2 | using Xunit; 3 | 4 | namespace NStandard.Locks.Test; 5 | 6 | public class TypeLockTest 7 | { 8 | [Fact] 9 | public void Test() 10 | { 11 | var lockParser = new TypeLockParser(nameof(NStandard)); 12 | 13 | var report = Concurrency.Run(resultId => 14 | { 15 | using var _lock = lockParser.Parse().TryBegin(500); 16 | 17 | if (_lock.Value) 18 | { 19 | Thread.Sleep(1000); 20 | return "Entered"; 21 | } 22 | else return "Timeout"; 23 | }, level: 2, threadCount: 2); 24 | 25 | Assert.Equal(1, report.Results.Count(x => x.Return == "Entered")); 26 | Assert.Equal(1, report.Results.Count(x => x.Return == "Timeout")); 27 | Assert.True(report.AverageElapsed?.TotalMilliseconds < 2000); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/Measures/WeightTests.cs: -------------------------------------------------------------------------------- 1 | using Xunit; 2 | 3 | namespace NStandard.Measures.Test; 4 | 5 | [Measure("g")] public partial struct g { } 6 | [Measure("kg"), Measure(1000)] public partial struct kg { } 7 | [Measure("t"), Measure(1000)] public partial struct t { } 8 | 9 | public class WeightTests 10 | { 11 | [Fact] 12 | public void AddTest() 13 | { 14 | var kg100 = new kg(100); 15 | var kg200 = kg100 + kg100; 16 | 17 | Assert.Equal(200_000, (g)kg200); 18 | Assert.Equal(200, kg200); 19 | Assert.Equal(0.2m, (t)kg200); 20 | } 21 | 22 | [Fact] 23 | public void SubTest() 24 | { 25 | var kg100 = new kg(100); 26 | var kg40 = new kg(40); 27 | var kg60 = kg100 - kg40; 28 | 29 | Assert.Equal(60_000, (g)kg60); 30 | Assert.Equal(60, kg60); 31 | Assert.Equal(0.06m, (t)kg60); 32 | } 33 | 34 | [Fact] 35 | public void MulTest() 36 | { 37 | var kg100 = new kg(100); 38 | var kg200 = kg100 * 2; 39 | 40 | Assert.Equal(200_000, (g)kg200); 41 | Assert.Equal(200, kg200); 42 | Assert.Equal(0.2, (t)kg200); 43 | } 44 | 45 | [Fact] 46 | public void DivTest() 47 | { 48 | var kg100 = new kg(100); 49 | var kg50 = kg100 / 2; 50 | 51 | Assert.Equal(50_000, (g)kg50); 52 | Assert.Equal(50, kg50); 53 | Assert.Equal(0.05, (t)kg50); 54 | Assert.Equal(2, kg100 / kg50); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/NStandard.Test.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net7.0 5 | false 6 | NStandard.Test 7 | preview 8 | enable 9 | true 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/RefTests.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics.CodeAnalysis; 2 | using Xunit; 3 | 4 | namespace NStandard.Test; 5 | 6 | public class RefTests 7 | { 8 | [Fact] 9 | [SuppressMessage("Assertions", "xUnit2005:Do not use identity check on value type", Justification = "")] 10 | public void StructTest() 11 | { 12 | var refs = new Ref[] { 8, 8 }; 13 | 14 | Assert.NotEqual(refs[0], refs[1]); 15 | Assert.NotSame(refs[0], refs[1]); 16 | 17 | Assert.Equal(refs[0].Target, refs[1].Target); 18 | Assert.NotSame(refs[0].Target, refs[1].Target); 19 | } 20 | 21 | [Fact] 22 | public void ClassTest() 23 | { 24 | var str = "str"; 25 | var refs = new Ref[] { str, str }; 26 | 27 | Assert.NotEqual(refs[0], refs[1]); 28 | Assert.NotSame(refs[0], refs[1]); 29 | 30 | Assert.Equal(refs[0].Target, refs[1].Target); 31 | Assert.Same(refs[0].Target, refs[1].Target); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/Reference/DotNetFrameworkTests.cs: -------------------------------------------------------------------------------- 1 | using Xunit; 2 | 3 | namespace NStandard.Runtime.Test; 4 | 5 | public class DotNetFrameworkTests 6 | { 7 | [Fact] 8 | public void Test1() 9 | { 10 | var fws = DotNetFramework.Parse("net451").Compatibility.Select(x => x.ToString()).ToArray(); 11 | Assert.Equal( 12 | [ 13 | "net451", "netstandard1.2", 14 | "net45", "netstandard1.1", "netstandard1.0", 15 | "net403", "net40", "net35", "net20", "net11" 16 | ], fws); 17 | } 18 | 19 | [Fact] 20 | public void NotDeclaredTFMTest() 21 | { 22 | Assert.Throws(() => 23 | { 24 | DotNetFramework.Parse("netcoreapp??").Compatibility.Select(x => x.ToString()).ToArray(); 25 | }); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/RuntimeTests.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | using Xunit; 3 | 4 | namespace NStandard.Test; 5 | 6 | public class RuntimeTests 7 | { 8 | #pragma warning disable CS0618 // Type or member is obsolete 9 | [Fact] 10 | public void AddressOfClassTest() 11 | { 12 | var str = new string("abc"); 13 | var ptr = Native.AddressOf(str, true); 14 | var length = BitConverter.ToInt32(Native.ReadMemory(ptr, sizeof(int)), 0); 15 | var pStrPart = ptr + sizeof(int); 16 | 17 | Assert.Equal(str.Length, length); 18 | Assert.Equal("abc", str); 19 | 20 | Native.WriteMemory(pStrPart, Encoding.Default.GetBytes("A")); 21 | Assert.Equal("Abc", str); 22 | } 23 | 24 | [Fact] 25 | public unsafe void AddressOfStructTest() 26 | { 27 | var astruct = new IntStrcut { Value = 255 }; 28 | var ptr = Native.AddressOf(ref astruct); 29 | Assert.Equal((IntPtr)(&astruct), ptr); 30 | } 31 | 32 | [Fact] 33 | public unsafe void AddressOfWrappedStructTest() 34 | { 35 | var astruct = new IntStrcut { Value = 255 }; 36 | var ptr = Native.AddressOf(ref astruct); 37 | var wrappedPtr = Native.AddressOf((object)astruct, false); 38 | Assert.Equal((IntPtr)(&astruct), ptr); 39 | Assert.NotEqual((IntPtr)(&astruct), wrappedPtr); 40 | } 41 | #pragma warning restore CS0618 // Type or member is obsolete 42 | 43 | [Fact] 44 | public void AreSameTest() 45 | { 46 | var s1 = "abc"; 47 | var s2 = "abc"; 48 | Assert.Same(s1, s2); 49 | 50 | s2 = "ABC"; 51 | Assert.NotSame(s1, s2); 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/Schema/LoopForTests.cs: -------------------------------------------------------------------------------- 1 | using Xunit; 2 | 3 | namespace NStandard.Schema.Test; 4 | 5 | public class LoopForTests 6 | { 7 | [Fact] 8 | public void Test1() 9 | { 10 | var lfor = new LoopFor([1, 3, 5]); 11 | var array = lfor.ToArray(); 12 | Assert.Equal([1, 3, 5], array); 13 | } 14 | 15 | [Fact] 16 | public void Test2() 17 | { 18 | var lfor = new LoopFor(() => 1, i => i < 7, i => i += 2); 19 | var array = lfor.ToArray(); 20 | Assert.Equal([1, 3, 5], array); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/Schema/LoopTests.cs: -------------------------------------------------------------------------------- 1 | using Xunit; 2 | 3 | namespace NStandard.Schema.Test; 4 | 5 | public class LoopTests 6 | { 7 | [Fact] 8 | public void Test1() 9 | { 10 | var values = Loop.Create(2, 3).ToArray(); 11 | Assert.Equal( 12 | [ 13 | [0, 0], [0, 1], [0, 2], 14 | [1, 0], [1, 1], [1, 2], 15 | ], values); 16 | } 17 | 18 | [Fact] 19 | public void Test2() 20 | { 21 | var values = Loop.Create([1, 2], [3, 4]).ToArray(); 22 | Assert.Equal( 23 | [ 24 | [1, 3], [1, 4], 25 | [2, 3], [2, 4], 26 | ], values); 27 | } 28 | 29 | [Fact] 30 | public void Test3() 31 | { 32 | var values = Loop.Create( 33 | LoopFor.Create(() => 1, i => i < 4, i => i += 2), 34 | LoopFor.Create(() => 2, i => i < 5, i => i += 2)).ToArray(); 35 | 36 | Assert.Equal( 37 | [ 38 | [1, 2], [1, 4], 39 | [3, 2], [3, 4], 40 | ], values); 41 | } 42 | 43 | [Fact] 44 | public void Test4() 45 | { 46 | var values = Loop.Create(2, 0, 3).ToArray(); 47 | Assert.Equal( 48 | [ 49 | [0, null, null], 50 | [1, null, null], 51 | ], values); 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/SingletonTests.cs: -------------------------------------------------------------------------------- 1 | using Xunit; 2 | 3 | namespace NStandard.Test; 4 | 5 | public class SingletonTests 6 | { 7 | public class SingletonSample : ISingleton 8 | { 9 | /// 10 | /// 11 | /// 12 | public static SingletonSample Instance => Singleton.GetOrCreate(); 13 | 14 | public static int Number { get; set; } 15 | 16 | public void OnInit() 17 | { 18 | Number += 100; 19 | } 20 | } 21 | 22 | [Fact] 23 | public void SingletonTest() 24 | { 25 | Assert.Equal(0, SingletonSample.Number); 26 | 27 | _ = SingletonSample.Instance; 28 | Assert.Equal(100, SingletonSample.Number); 29 | 30 | _ = SingletonSample.Instance; 31 | Assert.Equal(100, SingletonSample.Number); 32 | } 33 | 34 | public class StaticSingletonSample : ISingleton 35 | { 36 | /// 37 | /// 38 | /// 39 | public static StaticSingletonSample Instance => StaticSingleton.Instance; 40 | 41 | public static int Number { get; set; } 42 | 43 | public void OnInit() 44 | { 45 | Number += 100; 46 | } 47 | } 48 | 49 | [Fact] 50 | public void StaticSingletonTest() 51 | { 52 | Assert.Equal(0, StaticSingletonSample.Number); 53 | 54 | _ = StaticSingletonSample.Instance; 55 | Assert.Equal(100, StaticSingletonSample.Number); 56 | 57 | _ = StaticSingletonSample.Instance; 58 | Assert.Equal(100, StaticSingletonSample.Number); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/SnowflakeTests.cs: -------------------------------------------------------------------------------- 1 | using NStandard.Algorithm; 2 | using Xunit; 3 | 4 | namespace NStandard.Test; 5 | 6 | public class SnowflakeTests 7 | { 8 | private class FixedSnowflakeWorker : SnowflakeWorker 9 | { 10 | public FixedSnowflakeWorker(long workerId, long dataCenterId) : base(workerId, dataCenterId) 11 | { 12 | } 13 | 14 | protected override long NewTimestamp() => 0x12c148d03c1; 15 | } 16 | 17 | private class FixedSnowflakeWorker128 : SnowflakeWorker128 18 | { 19 | public FixedSnowflakeWorker128(long workerId, long dataCenterId) : base(workerId, dataCenterId) 20 | { 21 | } 22 | 23 | protected override Int128 NewTimestamp() => 0x12c148d03c1; 24 | } 25 | 26 | [Fact] 27 | public void LongTest() 28 | { 29 | var snowflake = new FixedSnowflakeWorker(31, 31); 30 | var id = snowflake.NewId(); 31 | Assert.Equal(4190208, id); 32 | } 33 | 34 | [Fact] 35 | public void Int128Test() 36 | { 37 | var snowflake = new FixedSnowflakeWorker128(0xff, 0xcc); 38 | var id = snowflake.NewId(); 39 | Assert.Equal(new Int128(0x0000012c148d03c1, 0x00cc00ff00000000), id); 40 | } 41 | 42 | [Fact] 43 | public void GuidTest() 44 | { 45 | var snowflake = new FixedSnowflakeWorker128(0xff, 0xcc); 46 | var guid = snowflake.NewGuid(); 47 | Assert.Equal(Guid.Parse("00000000-00ff-00cc-c103-8d142c010000"), guid); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/SpanExtensionsTests.cs: -------------------------------------------------------------------------------- 1 | using Xunit; 2 | 3 | namespace NStandard.Test; 4 | 5 | public class SpanExtensionsTests 6 | { 7 | [Fact] 8 | public void DeconstructTest() 9 | { 10 | var arr = new[] { 1, 2, 3, 4, 5, 6, 7, 8 }.AsSpan(); 11 | var (i1, i2, i3, i4, i5, i6, i7, (i8, _)) = arr; 12 | Assert.Equal(1, i1); 13 | Assert.Equal(2, i2); 14 | Assert.Equal(3, i3); 15 | Assert.Equal(4, i4); 16 | Assert.Equal(5, i5); 17 | Assert.Equal(6, i6); 18 | Assert.Equal(7, i7); 19 | Assert.Equal(8, i8); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/StructTupleTests.cs: -------------------------------------------------------------------------------- 1 | using Xunit; 2 | 3 | namespace NStandard.Test; 4 | 5 | public class StructTupleTests 6 | { 7 | [Fact] 8 | public void StructTupleTest() 9 | { 10 | var tuple = StructTuple.Create("1", "2"); 11 | (string a, string b) = tuple; 12 | 13 | Assert.Equal(a, tuple.Item1); 14 | Assert.Equal(b, tuple.Item2); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/TimePointValueTests.cs: -------------------------------------------------------------------------------- 1 | using Xunit; 2 | 3 | namespace NStandard.Test; 4 | 5 | public class TimePointValueTests 6 | { 7 | [Fact] 8 | public void NormalTest() 9 | { 10 | var pointValue = new TimePointValue(1); 11 | 12 | Thread.Sleep(200); 13 | pointValue.Value = 1; 14 | Assert.True(pointValue.TimeSpan.TotalMilliseconds > 200); 15 | 16 | Thread.Sleep(200); 17 | pointValue.Value = 2; 18 | Assert.True(pointValue.TimeSpan.TotalMilliseconds < 200); 19 | 20 | Thread.Sleep(200); 21 | pointValue.Value = 1; 22 | Assert.True(pointValue.TimeSpan.TotalMilliseconds < 200); 23 | } 24 | 25 | [Fact] 26 | public void NullTest() 27 | { 28 | var pointValue = new TimePointValue(); 29 | 30 | Thread.Sleep(200); 31 | pointValue.Value = null; 32 | Assert.True(pointValue.TimeSpan.TotalMilliseconds > 200); 33 | 34 | Thread.Sleep(200); 35 | pointValue.Value = "string"; 36 | Assert.True(pointValue.TimeSpan.TotalMilliseconds < 200); 37 | 38 | Thread.Sleep(200); 39 | pointValue.Value = null; 40 | Assert.True(pointValue.TimeSpan.TotalMilliseconds < 200); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/Trees/BinaryTreeTests.cs: -------------------------------------------------------------------------------- 1 | using Xunit; 2 | 3 | namespace NStandard.Trees.Test; 4 | 5 | public class BinaryTreeTests 6 | { 7 | private readonly int[] InOrder = [4, 7, 2, 1, 5, 3, 8, 6]; 8 | private readonly int[] PreOrder = [1, 2, 4, 7, 3, 5, 6, 8]; 9 | private readonly int[] PostOrder = [7, 4, 2, 5, 8, 6, 3, 1]; 10 | /* 11 | * 1 12 | * / \ 13 | * 2 3 14 | * / / \ 15 | * 4 5 6 16 | * \ / 17 | * 7 8 18 | */ 19 | 20 | [Fact] 21 | public void Test1() 22 | { 23 | var tree = BinaryTreeConstructor.ConstructFrom_InPreOrder(InOrder, PreOrder); 24 | Assert.Equal(InOrder, tree.GetInOrderNodes().Select(x => x.Model)); 25 | Assert.Equal(PreOrder, tree.GetPreOrderNodes().Select(x => x.Model)); 26 | Assert.Equal(PostOrder, tree.GetPostOrderNodes().Select(x => x.Model)); 27 | } 28 | 29 | [Fact] 30 | public void Test2() 31 | { 32 | var tree = BinaryTreeConstructor.ConstructFrom_InPostOrder(InOrder, PostOrder); 33 | Assert.Equal(InOrder, tree.GetInOrderNodes().Select(x => x.Model)); 34 | Assert.Equal(PreOrder, tree.GetPreOrderNodes().Select(x => x.Model)); 35 | Assert.Equal(PostOrder, tree.GetPostOrderNodes().Select(x => x.Model)); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/UsableTests.cs: -------------------------------------------------------------------------------- 1 | using Xunit; 2 | 3 | namespace NStandard.Test; 4 | 5 | public class UsableTests 6 | { 7 | [Fact] 8 | public void Test1() 9 | { 10 | int number = 0; 11 | var usable = Usable.Begin(() => number = 414, () => number = 416); 12 | using (usable) 13 | { 14 | Assert.Equal(414, number); 15 | } 16 | Assert.Equal(416, number); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/ValTests.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics.CodeAnalysis; 2 | using Xunit; 3 | 4 | namespace NStandard.Test; 5 | 6 | public class ValTests 7 | { 8 | [Fact] 9 | [SuppressMessage("Assertions", "xUnit2005:Do not use identity check on value type", Justification = "")] 10 | public void StructTest() 11 | { 12 | var vals = new Val[] { 8, 8 }; 13 | 14 | Assert.Equal(vals[0], vals[1]); 15 | Assert.NotSame(vals[0], vals[1]); 16 | 17 | Assert.Equal(vals[0].Target, vals[1].Target); 18 | Assert.NotSame(vals[0].Target, vals[1].Target); 19 | } 20 | 21 | [Fact] 22 | [SuppressMessage("Assertions", "xUnit2005:Do not use identity check on value type", Justification = "")] 23 | public void ClassTest() 24 | { 25 | var str = "str"; 26 | var vals = new Val[] { str, str }; 27 | 28 | Assert.Equal(vals[0], vals[1]); 29 | Assert.NotSame(vals[0], vals[1]); 30 | 31 | Assert.Equal(vals[0].Target, vals[1].Target); 32 | Assert.Same(vals[0].Target, vals[1].Target); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /Tests/NStandard.Test/VariantTests.cs: -------------------------------------------------------------------------------- 1 | using Xunit; 2 | 3 | namespace NStandard.Test; 4 | 5 | public class VariantTests 6 | { 7 | [Fact] 8 | public void Test1() 9 | { 10 | Assert.True(new Variant("true")); 11 | Assert.False(new Variant("false")); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /docs/cn/Any.Forward.md: -------------------------------------------------------------------------------- 1 | ## Any.Forward 2 | 3 | 按指定路径依次获取元素。 4 | 5 |
6 | 7 | ### 深层遍历 8 | 9 | **示例 1** (最里面的 **Exception**) 10 | 11 | ```csharp 12 | var exception = new Exception("3", new Exception("2", new Exception("1"))); 13 | var forwards = Any.Forward(exception, x => x.InnerException); 14 | 15 | /* 16 | * Exception 3 = First 17 | * - Exception 2 18 | * - - Exception 1 = Last 19 | */ 20 | Assert.Equal("1", (from ex in forwards select ex).Last().Message); 21 | ``` 22 | 23 |
24 | 25 | -------------------------------------------------------------------------------- /docs/cn/Any.ReDim.md: -------------------------------------------------------------------------------- 1 | ## Any.ReDim 2 | 3 | 为数组重新分配空间。 4 | 5 |
6 | 7 | **示例 1**(减少维度空间) 8 | 9 | ```csharp 10 | var d2 = new int[3, 3] 11 | { 12 | { 0, 1, 2 }, 13 | { 3, 4, 5 }, 14 | { 6, 7, 8 } 15 | }; 16 | Any.ReDim(ref d2, 2, 2); 17 | 18 | for (int i = 0; i < d2.GetLength(0); i++) 19 | { 20 | var row = new int[d2.GetLength(1)].Let(j => d2[i, j]); 21 | Console.WriteLine(row.Join(", ")); 22 | } 23 | ``` 24 | 25 | > 0, 1
3, 4 26 | 27 |
28 | 29 | **示例 2**(扩大维度空间) 30 | 31 | ```csharp 32 | var d2 = new int[3, 3] 33 | { 34 | { 0, 1, 2 }, 35 | { 3, 4, 5 }, 36 | { 6, 7, 8 } 37 | }; 38 | Any.ReDim(ref d2, 4, 4); 39 | 40 | for (int i = 0; i < d2.GetLength(0); i++) 41 | { 42 | var row = new int[d2.GetLength(1)].Let(j => d2[i, j]); 43 | Console.WriteLine(row.Join(", ")); 44 | } 45 | ``` 46 | 47 | > 0, 1, 2, 0
3, 4, 5, 0
6, 7, 8, 0
0, 0, 0, 0 48 | 49 |
50 | 51 | -------------------------------------------------------------------------------- /docs/cn/Compatibility.md: -------------------------------------------------------------------------------- 1 | ## Compatibility 2 | 3 | **NStandard** 移植了 **.NET Core** 的部分功能,以便在 **.NET Framework** 中使用。 4 | 5 |
6 | 7 | | 命名空间 | Class / Strcut | 兼容性 | 8 | | ------------------ | ------------------------------------------------------- | ------------------------------------------------------------ | 9 | | System | **HashCode** | = .NET Framework
< .NET Standard 2.1
< .NET Core App 2.1 | 10 | | System | **ITuple** | < .NET Framework 4.7
< .NET Standard 2.1
< .NET Core App 2.0 | 11 | | System | **Tuple** | < .NET Framework 4.5.1 | 12 | | System | **FormattableString** | < .NET Framework 4.6
< .NET Standard 1.3 | 13 | | System.Collections | **IStructuralComparable**
**IStructuralEquatable** | < .NET Framework 4.5.1 | 14 | | System.Reflection | **CustomAttributeExtensions** | < .NET Framework 4.5.1 | 15 | 16 | -------------------------------------------------------------------------------- /docs/cn/DpContainer.md: -------------------------------------------------------------------------------- 1 | ## DpContainer 2 | 3 | **DpContainer** 用于动态规划计算。 4 | 5 |
6 | 7 | 以**斐波那契**函数为例。 8 | 9 | ### 递归代码 10 | 11 | ```csharp 12 | int Fib(int n) 13 | { 14 | if (n == 0 || n == 1) return 1; 15 | else return Fib(n - 1) + Fib(n - 2); 16 | } 17 | 18 | void Main() 19 | { 20 | Fib(42).Dump(); 21 | } 22 | ``` 23 | 24 | ### DP 代码 1(使用 class) 25 | 26 | ```csharp 27 | class DpFib : DpContainer 28 | { 29 | public override int StateTransfer(int n) 30 | { 31 | if (n == 0 || n == 1) return 1; 32 | else return this[n - 1] + this[n - 2]; 33 | } 34 | } 35 | 36 | void Main() 37 | { 38 | var fib = new DpFib(); 39 | fib[42].Dump(); 40 | } 41 | ``` 42 | 43 | ### DP 代码 2(使用函数) 44 | 45 | ```csharp 46 | int Fib(DefaultDpContainer dp, int n) 47 | { 48 | if (n == 0 || n == 1) return 1; 49 | else return dp[n - 1] + dp[n - 2]; 50 | } 51 | 52 | void Main() 53 | { 54 | var fib = DpContainer.Create(Fib); 55 | fib[42].Dump(); // same as Fib(fib, 42).Dump(); 56 | } 57 | ``` 58 | 59 |
60 | 61 | 正确结果是 **433494437**. 62 | 63 | 上述代码得到正确结果所需的时间大致如下: 64 | 65 | | | Name | Elapsed | 66 | | ---- | ----------------------- | ------------- | 67 | | | 递归代码 | 约 3.823 秒。 | 68 | | * | DP 代码 1(使用 class) | 约 0.010 秒。 | 69 | | | DP 代码 2(使用函数) | 约 0.011 秒。 | 70 | 71 | -------------------------------------------------------------------------------- /docs/cn/SequenceInputStream.md: -------------------------------------------------------------------------------- 1 | ## SequenceInputStream 2 | 3 | **SequenceInputStream** 可以将多个流组合成一个流。 4 | 5 |
6 | 7 | **示例** 8 | 9 | ```csharp 10 | using var stream = new SequenceInputStream( 11 | new MemoryStream("123".Bytes(Encoding.UTF8)), 12 | new MemoryStream("456".Bytes(Encoding.UTF8)), 13 | new MemoryStream("789".Bytes(Encoding.UTF8)) 14 | ); 15 | using var reader = new StreamReader(stream); 16 | var result = reader.ReadToEnd(); // 123456789 17 | ``` 18 | 19 |
20 | 21 | -------------------------------------------------------------------------------- /docs/cn/UnitValue.md: -------------------------------------------------------------------------------- 1 | ## UnitValue 2 | 3 | **UnitValue** 用于对执行带单位的数值运算。 4 | 5 |
6 | 7 | 例如,**StorageValue** 是实现了 **IUnitValue** 的结构体: 8 | 9 | ```csharp 10 | var a = StorageValue.Parse(".5 MB"); 11 | var b = new StorageValue(512, "KB"); 12 | var c = a + b; 13 | 14 | var mb = c.GetValue("MB"); // 1 15 | var kb = c.GetValue("KB"); // 1024 16 | ``` 17 | 18 | 支持数学运算: 19 | 20 | - **加法** (+) 21 | 22 | ```csharp 23 | a + b 24 | ``` 25 | 26 | - **减法** (-) 27 | 28 | ```csharp 29 | a - b 30 | ``` 31 | 32 | - **乘法** (*) 33 | 34 | ```csharp 35 | a * 2 36 | ``` 37 | 38 | - **除法** (/) 39 | 40 | ```csharp 41 | a / 2 42 | ``` 43 | 44 | - **比较** ( ==, !=, <, <=, >, >= ) 45 | 46 | ```csharp 47 | a == b 48 | a != b 49 | a < b 50 | a <= b 51 | a > b 52 | a >= b 53 | ``` 54 | 55 |
56 | 57 | ### 多值相加 58 | 59 | 构建复杂结构体是一项相对耗时的操作。 因此,将每个数值依次相加是低效的。 60 | 61 | 我们提供了更高效的方法(使用 **QuickSum** 函数)来处理这种情况。 62 | 63 |
64 | 65 | 例如,现在有若干 **StorageValues**: 66 | 67 | ```csharp 68 | var values = new StorageValue[100_000_000].Let(i => new StorageValue(i)); 69 | ``` 70 | 71 | 然后,计算他们的和值: 72 | 73 | ✔️ 考虑使用(约 1.00 秒) 74 | 75 | ```csharp 76 | var sum = new StorageValue(); 77 | sum.QuickSum(values); 78 | ``` 79 | 80 | ❌ 避免使用(约 4.00 秒) 81 | 82 | ```csharp 83 | var sum = new StorageValue(); 84 | foreach (var value in values) 85 | { 86 | sum += value; 87 | } 88 | ``` 89 | 90 | #### 使用 LinqSharp 91 | 92 | ✔️ 考虑使用(约 1.00 秒) 93 | 94 | ```csharp 95 | var sum = values.QSum(); 96 | ``` 97 | 98 | ❌ 避免使用(约 4.00 秒) 99 | 100 | ```csharp 101 | var sum = values.Sum(); 102 | ``` 103 | 104 |
105 | 106 | -------------------------------------------------------------------------------- /docs/en/Any.Forward.md: -------------------------------------------------------------------------------- 1 | ## Any.Forward 2 | 3 | Get elements sequentially by the specified path. 4 | 5 |
6 | 7 | ### Deep traversal 8 | 9 | **Example 1** ( Innermost **Exception** ) 10 | 11 | ```csharp 12 | var exception = new Exception("3", new Exception("2", new Exception("1"))); 13 | var forwards = Any.Forward(exception, x => x.InnerException); 14 | 15 | /* 16 | * Exception 3 = First 17 | * - Exception 2 18 | * - - Exception 1 = Last 19 | */ 20 | Assert.Equal("1", (from ex in forwards select ex).Last().Message); 21 | ``` 22 | 23 |
24 | 25 | -------------------------------------------------------------------------------- /docs/en/Any.ReDim.md: -------------------------------------------------------------------------------- 1 | ## Any.ReDim 2 | 3 | Reallocates storage space for an array variable. 4 | 5 |
6 | 7 | **Example 1** ( Shrink space ) 8 | 9 | ```csharp 10 | var d2 = new int[3, 3] 11 | { 12 | { 0, 1, 2 }, 13 | { 3, 4, 5 }, 14 | { 6, 7, 8 } 15 | }; 16 | Any.ReDim(ref d2, 2, 2); 17 | 18 | for (int i = 0; i < d2.GetLength(0); i++) 19 | { 20 | var row = new int[d2.GetLength(1)].Let(j => d2[i, j]); 21 | Console.WriteLine(row.Join(", ")); 22 | } 23 | ``` 24 | 25 | > 0, 1
3, 4 26 | 27 |
28 | 29 | **Example 2** ( Expand space ) 30 | 31 | ```csharp 32 | var d2 = new int[3, 3] 33 | { 34 | { 0, 1, 2 }, 35 | { 3, 4, 5 }, 36 | { 6, 7, 8 } 37 | }; 38 | Any.ReDim(ref d2, 4, 4); 39 | 40 | for (int i = 0; i < d2.GetLength(0); i++) 41 | { 42 | var row = new int[d2.GetLength(1)].Let(j => d2[i, j]); 43 | Console.WriteLine(row.Join(", ")); 44 | } 45 | ``` 46 | 47 | > 0, 1, 2, 0
3, 4, 5, 0
6, 7, 8, 0
0, 0, 0, 0 48 | 49 |
50 | 51 | -------------------------------------------------------------------------------- /docs/en/Compatibility.md: -------------------------------------------------------------------------------- 1 | ## Compatibility 2 | 3 | **NStandard** ports parts of **.NET Core** for use within the **.NET Framework**. 4 | 5 |
6 | 7 | | Namespace | Class or Strcut | Compatibility | 8 | | ------------------ | ------------------------------------------------------- | ------------------------------------------------------------ | 9 | | System | **HashCode** | = .NET Framework
< .NET Standard 2.1
< .NET Core App 2.1 | 10 | | System | **ITuple** | < .NET Framework 4.7
< .NET Standard 2.1
< .NET Core App 2.0 | 11 | | System | **Tuple** | < .NET Framework 4.5.1 | 12 | | System | **FormattableString** | < .NET Framework 4.6
< .NET Standard 1.3 | 13 | | System.Collections | **IStructuralComparable**
**IStructuralEquatable** | < .NET Framework 4.5.1 | 14 | | System.Reflection | **CustomAttributeExtensions** | < .NET Framework 4.5.1 | 15 | 16 | -------------------------------------------------------------------------------- /docs/en/DpContainer.md: -------------------------------------------------------------------------------- 1 | ## DpContainer 2 | 3 | **DpContainer** is used for dynamic programming calculations. 4 | 5 |
6 | 7 | Take the **Fibonacci** function as an example. 8 | 9 | ### Recursion Code 10 | 11 | ```csharp 12 | int Fib(int n) 13 | { 14 | if (n == 0 || n == 1) return 1; 15 | else return Fib(n - 1) + Fib(n - 2); 16 | } 17 | 18 | void Main() 19 | { 20 | Fib(42).Dump(); 21 | } 22 | ``` 23 | 24 | ### DP Code 1 (Using class) 25 | 26 | ```csharp 27 | class DpFib : DpContainer 28 | { 29 | public override int StateTransfer(int n) 30 | { 31 | if (n == 0 || n == 1) return 1; 32 | else return this[n - 1] + this[n - 2]; 33 | } 34 | } 35 | 36 | void Main() 37 | { 38 | var fib = new DpFib(); 39 | fib[42].Dump(); 40 | } 41 | ``` 42 | 43 | ### DP Code 2 (Using function) 44 | 45 | ```csharp 46 | int Fib(DefaultDpContainer dp, int n) 47 | { 48 | if (n == 0 || n == 1) return 1; 49 | else return dp[n - 1] + dp[n - 2]; 50 | } 51 | 52 | void Main() 53 | { 54 | var fib = DpContainer.Create(Fib); 55 | fib[42].Dump(); // same as Fib(fib, 42).Dump(); 56 | } 57 | ``` 58 | 59 |
60 | 61 | The correct answer is **433494437**. 62 | 63 | And the time required for the above code to get the correct result is roughly as follows: 64 | 65 | | | Name | Elapsed | 66 | | ---- | -------------------------- | -------------------- | 67 | | | Recursion Code | about 3.823 seconds. | 68 | | * | DP Code 1 (Using class) | about 0.010 seconds. | 69 | | | DP Code 2 (Using function) | about 0.011 seconds. | 70 | 71 | -------------------------------------------------------------------------------- /docs/en/SequenceInputStream.md: -------------------------------------------------------------------------------- 1 | ## SequenceInputStream 2 | 3 | **SequenceInputStream** can combine multiple streams into a single stream. 4 | 5 |
6 | 7 | **Example** 8 | 9 | ```csharp 10 | using var stream = new SequenceInputStream( 11 | new MemoryStream("123".Bytes(Encoding.UTF8)), 12 | new MemoryStream("456".Bytes(Encoding.UTF8)), 13 | new MemoryStream("789".Bytes(Encoding.UTF8)) 14 | ); 15 | using var reader = new StreamReader(stream); 16 | var result = reader.ReadToEnd(); // 123456789 17 | ``` 18 | 19 |
20 | 21 | -------------------------------------------------------------------------------- /docs/images/State-001.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zmjack/NStandard/981f5c0b77e938d5855cd7b0ee168302ad332ba8/docs/images/State-001.png -------------------------------------------------------------------------------- /docs/images/State-002.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zmjack/NStandard/981f5c0b77e938d5855cd7b0ee168302ad332ba8/docs/images/State-002.png -------------------------------------------------------------------------------- /docs/images/State-003.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zmjack/NStandard/981f5c0b77e938d5855cd7b0ee168302ad332ba8/docs/images/State-003.png -------------------------------------------------------------------------------- /docs/images/State-004.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zmjack/NStandard/981f5c0b77e938d5855cd7b0ee168302ad332ba8/docs/images/State-004.png -------------------------------------------------------------------------------- /docs/images/State-005.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zmjack/NStandard/981f5c0b77e938d5855cd7b0ee168302ad332ba8/docs/images/State-005.png -------------------------------------------------------------------------------- /docs/images/State-006.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zmjack/NStandard/981f5c0b77e938d5855cd7b0ee168302ad332ba8/docs/images/State-006.png -------------------------------------------------------------------------------- /docs/images/image-20221227131745251.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zmjack/NStandard/981f5c0b77e938d5855cd7b0ee168302ad332ba8/docs/images/image-20221227131745251.png -------------------------------------------------------------------------------- /docs/images/image-20221227134222183.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zmjack/NStandard/981f5c0b77e938d5855cd7b0ee168302ad332ba8/docs/images/image-20221227134222183.png -------------------------------------------------------------------------------- /docs/images/image-20221227134321883.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zmjack/NStandard/981f5c0b77e938d5855cd7b0ee168302ad332ba8/docs/images/image-20221227134321883.png -------------------------------------------------------------------------------- /nstandard.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zmjack/NStandard/981f5c0b77e938d5855cd7b0ee168302ad332ba8/nstandard.png -------------------------------------------------------------------------------- /push.cmd: -------------------------------------------------------------------------------- 1 | nuget push "NStandard/bin/Release/NStandard.0.90.0.nupkg" -source nuget.org 2 | nuget push "NStandard.Analyzer/bin/Release/NStandard.Analyzer.0.90.0.nupkg" -source nuget.org 3 | nuget push "NStandard.Json/bin/Release/NStandard.Json.0.90.0.nupkg" -source nuget.org 4 | 5 | nuget push "NStandard.Encoding/bin/Release/NStandard.Encoding.0.8.5.nupkg" -source nuget.org 6 | nuget push "NStandard.Runtime/bin/Release/NStandard.Runtime.1.9.0.nupkg" -source nuget.org 7 | pause 8 | -------------------------------------------------------------------------------- /testEnvironments.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1", 3 | "environments": [ 4 | // See https://aka.ms/remotetesting for more details 5 | // about how to configure remote environments. 6 | //{ 7 | // "name": "WSL Ubuntu", 8 | // "type": "wsl", 9 | // "wslDistribution": "Ubuntu" 10 | //}, 11 | //{ 12 | // "name": "Docker dotnet/sdk", 13 | // "type": "docker", 14 | // "dockerImage": "mcr.microsoft.com/dotnet/sdk" 15 | //} 16 | ] 17 | } --------------------------------------------------------------------------------