commit ef5d53a67f45a8d193c35c6ef8f3661ad1eb291f Author: JustFixMe Date: Thu Dec 14 21:48:48 2023 +0400 first commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8a30d25 --- /dev/null +++ b/.gitignore @@ -0,0 +1,398 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..09cb4c4 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,4 @@ +{ + "dotnet.defaultSolution": "JustDotNet.Core.sln", + "dotnetAcquisitionExtension.enableTelemetry": false +} diff --git a/Core.Tests/Base32Conversions/Decode.cs b/Core.Tests/Base32Conversions/Decode.cs new file mode 100644 index 0000000..322a4bc --- /dev/null +++ b/Core.Tests/Base32Conversions/Decode.cs @@ -0,0 +1,79 @@ +namespace Just.Core.Tests.Base32Conversions; + +public class Decode +{ + [Theory] + [InlineData(15243)] + [InlineData(812010)] + [InlineData(97331334)] + [InlineData(20354)] + public void WhenEncodedToString_ShouldBeDecodedToTheSameByteArray(int seed) + { + var rng = new Random(seed); + + for (int i = 1; i <= 512; i++) + { + var testBytes = new byte[i]; + rng.NextBytes(testBytes); + + var resultString = Base32.Encode(testBytes); + var resultBytes = Base32.Decode(resultString); + + resultBytes.Should().BeEquivalentTo(testBytes); + } + } + + [Theory] + [InlineData("FG4M3ZQM3TVWDMBUP5L7N7V3JS7KBM2E", new byte[] { 0x29, 0xb8, 0xcd, 0xe6, 0x0c, 0xdc, 0xeb, 0x61, 0xb0, 0x34, 0x7f, 0x57, 0xf6, 0xfe, 0xbb, 0x4c, 0xbe, 0xa0, 0xb3, 0x44, })] + [InlineData("WXYEOQUZULMCY6ZQTDOLTRUZZMKQ====", new byte[] { 0xb5, 0xf0, 0x47, 0x42, 0x99, 0xa2, 0xd8, 0x2c, 0x7b, 0x30, 0x98, 0xdc, 0xb9, 0xc6, 0x99, 0xcb, 0x15, })] + [InlineData("2IO2HTALCXZWCBD2", new byte[] { 0xd2, 0x1d, 0xa3, 0xcc, 0x0b, 0x15, 0xf3, 0x61, 0x04, 0x7a, })] + [InlineData("ZFXJMF5N", new byte[] { 0b11001001, 0b01101110, 0b10010110, 0b00010111, 0b10101101, })] + [InlineData("CPIKTMY=", new byte[] { 0b00010011, 0b11010000, 0b10101001, 0b10110011, })] + [InlineData("JVNJA===", new byte[] { 0b01001101, 0b01011010, 0b10010000, })] + [InlineData("74OQ====", new byte[] { 0b11111111, 0b00011101, })] + public void WhenCalledWithValidString_ShouldReturnValidByteArray(string str, byte[] expected) + { + var actualBytesArray = Base32.Decode(str); + actualBytesArray.Should().Equal(expected); + } + + [Theory] + [InlineData("ZFXJMF5N====", new byte[] { 0b11001001, 0b01101110, 0b10010110, 0b00010111, 0b10101101, })] + [InlineData("CPIKTMY=====", new byte[] { 0b00010011, 0b11010000, 0b10101001, 0b10110011, })] + [InlineData("JVNJA=======", new byte[] { 0b01001101, 0b01011010, 0b10010000, })] + public void WhenCalledWithValidStringThatEndsWithPaddingSign_ShouldReturnValidByteArray(string testString, byte[] expected) + { + var actualBytesArray = Base32.Decode(testString); + actualBytesArray.Should().Equal(expected); + } + + [Theory] + [InlineData("ZFXJMF5N", new byte[] { 0b11001001, 0b01101110, 0b10010110, 0b00010111, 0b10101101, })] + [InlineData("CPIKTMY", new byte[] { 0b00010011, 0b11010000, 0b10101001, 0b10110011, })] + [InlineData("JVNJA", new byte[] { 0b01001101, 0b01011010, 0b10010000, })] + public void WhenCalledWithValidStringWithoutPaddingSign_ShouldReturnValidByteArray(string testString, byte[] expected) + { + var actualBytesArray = Base32.Decode(testString); + actualBytesArray.Should().Equal(expected); + } + + [Theory] + [InlineData(" ")] + [InlineData("hg2515i3215")] + [InlineData("hg712)21")] + [InlineData("hg712f 21")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1806:Do not ignore method results", Justification = "Test case")] + public void WhenCalledWithNotValidString_ShouldThrowFormatException(string testString) + { + Action action = () => Base32.Decode(testString); + action.Should().Throw(); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + public void WhenCalledWithNullString_ShouldReturnEmptyArray(string testString) + { + Base32.Decode(testString).Should().BeEmpty(); + } +} diff --git a/Core.Tests/Base32Conversions/Encode.cs b/Core.Tests/Base32Conversions/Encode.cs new file mode 100644 index 0000000..acee2a2 --- /dev/null +++ b/Core.Tests/Base32Conversions/Encode.cs @@ -0,0 +1,56 @@ + namespace Just.Core.Tests.Base32Conversions; + +public class Encode +{ + [Theory] + [InlineData("TQ======")] + [InlineData("3X3A====")] + [InlineData("426G6===")] + [InlineData("C3V3Y===")] + [InlineData("2JDBWKVU")] + [InlineData("ELCQNL477Q======")] + [InlineData("52Q2JBWZ36AQ====")] + [InlineData("INANSVEXD4FQ====")] + [InlineData("5HHUA5YXV5EEQ===")] + [InlineData("K7QEZW5N7H4TGIQ=")] + [InlineData("HVC7AUT2MZA646QS")] + [InlineData("ZHMQCLPPTQMSDSFKMI======")] + [InlineData("C4GQGXL5ZPMB5PIRAE======")] + [InlineData("OD4LXSFOWCJCVRZG63OA====")] + [InlineData("7XLZBFDEWHSU2ZZWE7XYK===")] + [InlineData("DCIEHJ672Z3DSGAR762Z6===")] + [InlineData("4OY6MNQ5R35Y3OK23U66CDI=")] + [InlineData("GSHXGB5ORKNDSFLSU2YWALI=")] + [InlineData("TMFSC64ZZNPQSNGCFIODS7TR")] + [InlineData("ZTDUBU4QZFFMDJKBII334EIB")] + public void WhenDecodedFromString_ShouldBeEncodedToTheSameString(string testString) + { + var resultBytes = Base32.Decode(testString); + var resultString = Base32.Encode(resultBytes); + + resultString.Should().BeEquivalentTo(testString); + } + + [Theory] + [InlineData("FG4M3ZQM3TVWDMBUP5L7N7V3JS7KBM2E", new byte[] { 0x29, 0xb8, 0xcd, 0xe6, 0x0c, 0xdc, 0xeb, 0x61, 0xb0, 0x34, 0x7f, 0x57, 0xf6, 0xfe, 0xbb, 0x4c, 0xbe, 0xa0, 0xb3, 0x44, })] + [InlineData("WXYEOQUZULMCY6ZQTDOLTRUZZMKQ====", new byte[] { 0xb5, 0xf0, 0x47, 0x42, 0x99, 0xa2, 0xd8, 0x2c, 0x7b, 0x30, 0x98, 0xdc, 0xb9, 0xc6, 0x99, 0xcb, 0x15, })] + [InlineData("2IO2HTALCXZWCBD2", new byte[] { 0xd2, 0x1d, 0xa3, 0xcc, 0x0b, 0x15, 0xf3, 0x61, 0x04, 0x7a, })] + [InlineData("ZFXJMF5N", new byte[] { 0b11001001, 0b01101110, 0b10010110, 0b00010111, 0b10101101, })] + [InlineData("CPIKTMY=", new byte[] { 0b00010011, 0b11010000, 0b10101001, 0b10110011, })] + [InlineData("JVNJA===", new byte[] { 0b01001101, 0b01011010, 0b10010000, })] + [InlineData("74OQ====", new byte[] { 0b11111111, 0b00011101, })] + public void WhenCalledWithNotEmptyByteArray_ShouldReturnValidString(string expected, byte[] testArray) + { + var str = Base32.Encode(testArray); + str.Should().Be(expected); + } + + [Theory] + [InlineData(new byte[] { })] + [InlineData(null)] + public void WhenCalledWithEmptyByteArray_ShouldReturnEmptyString(byte[] testArray) + { + var actualBase32 = Base32.Encode(testArray); + actualBase32?.Should().Be(string.Empty); + } +} diff --git a/Core.Tests/Base64UrlConversions/Decode.cs b/Core.Tests/Base64UrlConversions/Decode.cs new file mode 100644 index 0000000..978107f --- /dev/null +++ b/Core.Tests/Base64UrlConversions/Decode.cs @@ -0,0 +1,53 @@ +namespace Just.Core.Tests.Base64UrlConversions; + +public class Decode +{ + [Theory] + [InlineData(72121)] + [InlineData(554121)] + [InlineData(100454567)] + [InlineData(3210589)] + public void WhenEncodedToString_ShouldBeDecodedToTheSameByteArray(int seed) + { + var rng = new Random(seed); + + for (int i = 1; i <= 512; i++) + { + var testBytes = new byte[i]; + rng.NextBytes(testBytes); + + var resultString = Base64Url.Encode(testBytes); + var resultBytes = Base64Url.Decode(resultString); + + resultBytes.Should().BeEquivalentTo(testBytes); + } + } + + [Theory] + [InlineData("5QrdUxDUVkCAEGw8pvLsEw", "53dd0ae5-d410-4056-8010-6c3ca6f2ec13")] + [InlineData("6nE2uKQ4_0ar9kpmybgkdw", "b83671ea-38a4-46ff-abf6-4a66c9b82477")] + [InlineData("PyD6zwDqXkGbS1HPsp41wQ", "cffa203f-ea00-415e-9b4b-51cfb29e35c1")] + [InlineData("AdOlPOh3wEe9PlyQgTMt2g", "3ca5d301-77e8-47c0-bd3e-5c9081332dda")] + [InlineData("0elO0Lr-UkWwTarBeY6HRA", "d04ee9d1-feba-4552-b04d-aac1798e8744")] + public void WhenCalled_ShouldReturnValidGuid(string testString, string expectedStr) + { + var result = Base64Url.DecodeGuid(testString); + var expected = Guid.Parse(expectedStr); + result.Should().Be(expected); + } + + [Theory] + [InlineData("IA", new byte[]{ 0x20, })] + [InlineData("Ag", new byte[]{ 0x02, })] + [InlineData("ELg", new byte[]{ 0x10, 0xb8, })] + [InlineData("Vv0", new byte[]{ 0x56, 0xfd, })] + [InlineData("aVLO", new byte[]{ 0x69, 0x52, 0xce, })] + [InlineData("Ww2w", new byte[]{ 0x5b, 0x0d, 0xb0, })] + [InlineData("UKO0cR-OjLiM", new byte[]{ 0x50, 0xa3, 0xb4, 0x71, 0x1f, 0x8e, 0x8c, 0xb8, 0x8c, })] + [InlineData("hOb_nnjJRirORuTzYA", new byte[]{ 0x84, 0xe6, 0xff, 0x9e, 0x78, 0xc9, 0x46, 0x2a, 0xce, 0x46, 0xe4, 0xf3, 0x60, })] + public void WhenCalled_ShouldReturnValidBytes(string testString, byte[] expected) + { + var result = Base64Url.Decode(testString); + result.Should().BeEquivalentTo(expected); + } +} diff --git a/Core.Tests/Base64UrlConversions/Encode.cs b/Core.Tests/Base64UrlConversions/Encode.cs new file mode 100644 index 0000000..a11dfda --- /dev/null +++ b/Core.Tests/Base64UrlConversions/Encode.cs @@ -0,0 +1,32 @@ +namespace Just.Core.Tests.Base64UrlConversions; + +public class Encode +{ + [Theory] + [InlineData("5QrdUxDUVkCAEGw8pvLsEw", "53dd0ae5-d410-4056-8010-6c3ca6f2ec13")] + [InlineData("6nE2uKQ4_0ar9kpmybgkdw", "b83671ea-38a4-46ff-abf6-4a66c9b82477")] + [InlineData("PyD6zwDqXkGbS1HPsp41wQ", "cffa203f-ea00-415e-9b4b-51cfb29e35c1")] + [InlineData("AdOlPOh3wEe9PlyQgTMt2g", "3ca5d301-77e8-47c0-bd3e-5c9081332dda")] + [InlineData("0elO0Lr-UkWwTarBeY6HRA", "d04ee9d1-feba-4552-b04d-aac1798e8744")] + public void WhenCalledWithGuid_ShouldReturnValidString(string expected, string testGuidString) + { + var testGuid = Guid.Parse(testGuidString); + var result = Base64Url.Encode(testGuid); + result.Should().Be(expected); + } + + [Theory] + [InlineData("IA", new byte[]{ 0x20, })] + [InlineData("Ag", new byte[]{ 0x02, })] + [InlineData("ELg", new byte[]{ 0x10, 0xb8, })] + [InlineData("Vv0", new byte[]{ 0x56, 0xfd, })] + [InlineData("aVLO", new byte[]{ 0x69, 0x52, 0xce, })] + [InlineData("Ww2w", new byte[]{ 0x5b, 0x0d, 0xb0, })] + [InlineData("UKO0cR-OjLiM", new byte[]{ 0x50, 0xa3, 0xb4, 0x71, 0x1f, 0x8e, 0x8c, 0xb8, 0x8c, })] + [InlineData("hOb_nnjJRirORuTzYA", new byte[]{ 0x84, 0xe6, 0xff, 0x9e, 0x78, 0xc9, 0x46, 0x2a, 0xce, 0x46, 0xe4, 0xf3, 0x60, })] + public void WhenCalled_ShouldReturnValidString(string expected, byte[] testBytes) + { + var result = Base64Url.Encode(testBytes); + result.Should().Be(expected); + } +} diff --git a/Core.Tests/Core.Tests.csproj b/Core.Tests/Core.Tests.csproj new file mode 100644 index 0000000..c42aacf --- /dev/null +++ b/Core.Tests/Core.Tests.csproj @@ -0,0 +1,34 @@ + + + + net8.0 + enable + enable + + Just.Core.Tests + Just.Core.Tests + + false + true + true + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + diff --git a/Core.Tests/GlobalUsings.cs b/Core.Tests/GlobalUsings.cs new file mode 100644 index 0000000..91743bb --- /dev/null +++ b/Core.Tests/GlobalUsings.cs @@ -0,0 +1,2 @@ +global using Xunit; +global using FluentAssertions; diff --git a/Core/Base32.cs b/Core/Base32.cs new file mode 100644 index 0000000..9c83fa1 --- /dev/null +++ b/Core/Base32.cs @@ -0,0 +1,137 @@ +namespace Just.Core; + +public static class Base32 +{ + public const string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; + public const char Padding = '='; + + [Pure] + public static string Encode(ReadOnlySpan input) + { + if (input.Length == 0) + { + return string.Empty; + } + + int outLength = 8 * ((input.Length + 4) / 5); + Span output = stackalloc char[outLength]; + + _ = Encode(input, output); + + return new string(output); + } + + [Pure] + public static int Encode(ReadOnlySpan input, Span output) + { + int i = 0; + ReadOnlySpan alphabet = Alphabet; + for (int offset = 0; offset < input.Length;) + { + int numCharsToOutput = GetNextGroup(input, ref offset, out byte a, out byte b, out byte c, out byte d, out byte e, out byte f, out byte g, out byte h); + + output[i++] = (numCharsToOutput > 0) ? alphabet[a] : Padding; + output[i++] = (numCharsToOutput > 1) ? alphabet[b] : Padding; + output[i++] = (numCharsToOutput > 2) ? alphabet[c] : Padding; + output[i++] = (numCharsToOutput > 3) ? alphabet[d] : Padding; + output[i++] = (numCharsToOutput > 4) ? alphabet[e] : Padding; + output[i++] = (numCharsToOutput > 5) ? alphabet[f] : Padding; + output[i++] = (numCharsToOutput > 6) ? alphabet[g] : Padding; + output[i++] = (numCharsToOutput > 7) ? alphabet[h] : Padding; + } + return i; + } + + [Pure] + public static byte[] Decode(ReadOnlySpan input) + { + if (input.IsEmpty) return []; + + Span output = stackalloc byte[5 * input.Length / 8]; + + var size = Decode(input, output); + + return output[..size].ToArray(); + } + + [Pure] + public static int Decode(ReadOnlySpan input, Span output) + { + input = input.TrimEnd(Padding); + Span inputspan = stackalloc char[input.Length]; + input.ToUpperInvariant(inputspan); + + int bitIndex = 0; + int inputIndex = 0; + int outputBits = 0; + int outputIndex = 0; + int bitPos; + int outBitPos; + int bits; + + ReadOnlySpan alphabet = Alphabet; + while (inputIndex < input.Length) + { + var byteIndex = alphabet.IndexOf(inputspan[inputIndex]); + if (byteIndex < 0) + { + throw new FormatException("Provided string contains invalid characters."); + } + + bitPos = 5 - bitIndex; + outBitPos = 8 - outputBits; + bits = bitPos < outBitPos ? bitPos : outBitPos; + + output[outputIndex] <<= bits; + output[outputIndex] |= (byte)(byteIndex >> (bitPos - bits)); + + outputBits += bits; + if (outputBits >= 8) + { + outputIndex++; + outputBits = 0; + } + + bitIndex += bits; + if (bitIndex >= 5) + { + inputIndex++; + bitIndex = 0; + } + else if (inputIndex == input.Length -1) break; + } + + return outputIndex + (outputBits + 7) / 8; + } + + + // returns the number of bytes that were output + [Pure] + private static int GetNextGroup(ReadOnlySpan input, ref int offset, out byte a, out byte b, out byte c, out byte d, out byte e, out byte f, out byte g, out byte h) + { + var retVal = (input.Length - offset) switch + { + 1 => 2, + 2 => 4, + 3 => 5, + 4 => 7, + _ => 8, + }; + uint b1 = (offset < input.Length) ? input[offset++] : 0U; + uint b2 = (offset < input.Length) ? input[offset++] : 0U; + uint b3 = (offset < input.Length) ? input[offset++] : 0U; + uint b4 = (offset < input.Length) ? input[offset++] : 0U; + uint b5 = (offset < input.Length) ? input[offset++] : 0U; + + a = (byte)(b1 >> 3); + b = (byte)(((b1 & 0x07) << 2) | (b2 >> 6)); + c = (byte)((b2 >> 1) & 0x1f); + d = (byte)(((b2 & 0x01) << 4) | (b3 >> 4)); + e = (byte)(((b3 & 0x0f) << 1) | (b4 >> 7)); + f = (byte)((b4 >> 2) & 0x1f); + g = (byte)(((b4 & 0x3) << 3) | (b5 >> 5)); + h = (byte)(b5 & 0x1f); + + return retVal; + } +} diff --git a/Core/Base64Url.cs b/Core/Base64Url.cs new file mode 100644 index 0000000..d79d2f2 --- /dev/null +++ b/Core/Base64Url.cs @@ -0,0 +1,118 @@ +namespace Just.Core; + +public static class Base64Url +{ + [Pure] public static Guid DecodeGuid(ReadOnlySpan value) + { + ArgumentOutOfRangeException.ThrowIfNotEqual(value.Length, 22); + + Span guidBytes = stackalloc byte[16]; + Span chars = stackalloc char[24]; + value.CopyTo(chars); + for (int i = 0; i < value.Length; i++) + { + switch (value[i]) + { + case '-': chars[i] = '+'; continue; + case '_': chars[i] = '/'; continue; + default: continue; + } + } + chars[^2..].Fill('='); + if (!Convert.TryFromBase64Chars(chars, guidBytes, out int _)) + throw new FormatException("Invalid Base64 string."); + + return new Guid(guidBytes); + } + + [Pure] public static byte[] Decode(ReadOnlySpan input) + { + if (input.IsEmpty) return []; + + Span output = stackalloc byte[3 * ((input.Length + 3) / 4)]; + + var size = Decode(input, output); + + return output[..size].ToArray(); + } + + [Pure] public static int Decode(ReadOnlySpan value, Span output) + { + var padding = (4 - (value.Length & 3)) & 3; + var charlen = value.Length + padding; + var outputBytes = charlen / 4; + ArgumentOutOfRangeException.ThrowIfLessThan(output.Length, outputBytes); + Span chars = stackalloc char[charlen]; + + value.CopyTo(chars); + for (int i = 0; i < value.Length; i++) + { + switch (value[i]) + { + case '-': chars[i] = '+'; continue; + case '_': chars[i] = '/'; continue; + default: continue; + } + } + chars[^padding..].Fill('='); + + if (!Convert.TryFromBase64Chars(chars, output, out outputBytes)) + throw new FormatException("Invalid Base64 string."); + + return outputBytes; + } + + [Pure] public static string Encode(in Guid id) + { + Span guidBytes = stackalloc byte[16]; + id.TryWriteBytes(guidBytes); + Span chars = stackalloc char[24]; + Convert.TryToBase64Chars(guidBytes, chars, out int _); + + for (int i = 0; i < chars.Length - 2; i++) + { + switch (chars[i]) + { + case '+': chars[i] = '-'; continue; + case '/': chars[i] = '_'; continue; + default: continue; + } + } + + return new string(chars[..^2]); + } + + [Pure] public static string Encode(ReadOnlySpan input) + { + if (input.IsEmpty) return string.Empty; + + int outLength = 8 * ((input.Length + 5) / 6); + Span output = stackalloc char[outLength]; + + int strlen = Encode(input, output); + return new string(output[..strlen]); + } + + [Pure] public static int Encode(ReadOnlySpan input, Span output) + { + var charlen = 8 * ((input.Length + 5) / 6); + Span chars = stackalloc char[charlen]; + Convert.TryToBase64Chars(input, chars, out int charsWritten); + + int i; + for (i = 0; i < charsWritten; i++) + { + switch (chars[i]) + { + case '+': chars[i] = '-'; continue; + case '/': chars[i] = '_'; continue; + case '=': goto exitLoop; + default: continue; + } + } + exitLoop: + chars[..i].CopyTo(output); + + return i; + } +} diff --git a/Core/Collections/DataMap.cs b/Core/Collections/DataMap.cs new file mode 100644 index 0000000..8176cb0 --- /dev/null +++ b/Core/Collections/DataMap.cs @@ -0,0 +1,87 @@ +using System.Numerics; + +namespace Just.Core.Collections; + +public class DataMap : Map, IDataMap, ICloneable + where T : IComparisonOperators, IEqualityOperators +{ + internal MapPoint MinCache = default; + internal MapPoint MaxCache = default; + + internal DataMap(int width, int height, T[] values) + : base(width, height, values) + { + } + + public DataMap(ReadOnlySpan values, int width, int height) + : base(values, width, height) + { + } + + public DataMap(T[] values, int width, int height) + : base(values, width, height) + { + } + + public DataMap(T[,] values) + : base(values) + { + } + + [Pure] public MapPoint Min + { + get + { + if (MinCache.Map is null) FindMinMax(); + return MinCache; + } + } + + [Pure] public MapPoint Max + { + get + { + if (MaxCache.Map is null) FindMinMax(); + return MaxCache; + } + } + + private void FindMinMax() + { + var data = _values.AsSpan(); + + T min = data[0]; + T max = data[0]; + int minId = 0; + int maxId = 0; + + for (int i = 0; i < data.Length; i++) + { + if (data[i] < min) + { + min = data[i]; + minId = i; + continue; + } + + if (data[i] > max) + { + max = data[i]; + maxId = i; + } + } + + MinCache = new(min, minId % Width, minId / Width, this); + MaxCache = new(max, maxId % Width, maxId / Width, this); + } + + [Pure] public DataMap Clone() + { + var clone = new DataMap(Width, Height, [.. _values]); + clone.MinCache = new(clone._values[(MinCache.Y * Width) + MinCache.X], MinCache.X, MinCache.Y, clone); + clone.MaxCache = new(clone._values[(MaxCache.Y * Width) + MaxCache.X], MaxCache.X, MaxCache.Y, clone); + return clone; + } + + object ICloneable.Clone() => Clone(); +} diff --git a/Core/Collections/IDataMap.cs b/Core/Collections/IDataMap.cs new file mode 100644 index 0000000..0054c14 --- /dev/null +++ b/Core/Collections/IDataMap.cs @@ -0,0 +1,10 @@ +using System.Numerics; + +namespace Just.Core.Collections; + +public interface IDataMap : IMap, ICloneable + where T : IComparisonOperators, IEqualityOperators +{ + MapPoint Min { get; } + MapPoint Max { get; } +} diff --git a/Core/Collections/IMap.cs b/Core/Collections/IMap.cs new file mode 100644 index 0000000..e4ea7ba --- /dev/null +++ b/Core/Collections/IMap.cs @@ -0,0 +1,12 @@ +namespace Just.Core.Collections; + +public interface IMap : IReadOnlyCollection> +{ + int Width { get; } + int Height { get; } + ref readonly T this[int x, int y] { get; } + ref readonly T this[double x, double y] { get; } + MapPoint Get(int x, int y); + MapPoint Get(double x, double y); + T[,] ToArray(); +} diff --git a/Core/Collections/Map.cs b/Core/Collections/Map.cs new file mode 100644 index 0000000..86ed521 --- /dev/null +++ b/Core/Collections/Map.cs @@ -0,0 +1,172 @@ +using System.Collections; + +namespace Just.Core.Collections; + +public class Map : IMap +{ + internal readonly T[] _values; + + internal Map(int width, int height, T[] values) + { + Width = width; + Height = height; + _values = values; + } + public Map(ReadOnlySpan values, int width, int height) + { + ArgumentOutOfRangeException.ThrowIfLessThan(width, 1); + ArgumentOutOfRangeException.ThrowIfLessThan(height, 1); + ArgumentOutOfRangeException.ThrowIfNotEqual(width * height, values.Length); + + Width = width; + Height = height; + _values = new T[values.Length]; + values.CopyTo(_values); + } + + public Map(T[] values, int width, int height) + { + ArgumentNullException.ThrowIfNull(values); + ArgumentOutOfRangeException.ThrowIfLessThan(width, 1); + ArgumentOutOfRangeException.ThrowIfLessThan(height, 1); + ArgumentOutOfRangeException.ThrowIfNotEqual(width * height, values.Length); + + Width = width; + Height = height; + _values = new T[Width * Height]; + values.CopyTo(_values.AsSpan()); + } + public Map(T[,] values) + { + ArgumentNullException.ThrowIfNull(values); + ArgumentOutOfRangeException.ThrowIfZero(values.Length); + Width = values.GetLength(0); + Height = values.GetLength(1); + + _values = new T[Width * Height]; + + var data = _values.AsSpan(); + for (int y = 0; y < Height; y++) + { + int idy = y * Width; + for (int x = 0; x < Width; x++) + { + int id = idy + x; + data[id] = values[x, y]; + } + } + } + + [Pure] public ReadOnlySpan AsSpan() => _values; + [Pure] public ReadOnlyMemory AsMemory() => _values; + + public int Width { get; } + public int Height { get; } + public int Count => _values.Length; + + [Pure] public ref readonly T this[int x, int y] + { + get + { + x = Math.Clamp(x, 0, Width); + y = Math.Clamp(y, 0, Height); + return ref _values[(y * Width) + x]; + } + } + [Pure] public ref readonly T this[double x, double y] + { + get + { + int xi = Math.Clamp((int)x, 0, Width - 1); + int yi = Math.Clamp((int)y, 0, Height - 1); + + return ref _values[(yi * Width) + xi]; + } + } + + [Pure] public MapPoint Get(int x, int y) + { + x = Math.Clamp(x, 0, Width - 1); + y = Math.Clamp(y, 0, Height - 1); + return new(_values[(y * Width) + x], x, y, this); + } + [Pure] public MapPoint Get(double x, double y) + { + int xi = Math.Clamp((int)x, 0, Width - 1); + int yi = Math.Clamp((int)y, 0, Height - 1); + + return new(_values[(yi * Width) + xi], xi, yi, this); + } + + [Pure] public T[,] ToArray() + { + T[,] arr = new T[Width, Height]; + + var data = _values.AsSpan(); + for (int y = 0; y < Height; y++) + { + int idy = y * Width; + for (int x = 0; x < Width; x++) + { + int id = idy + x; + arr[x, y] = data[id]; + } + } + + return arr; + } + public Enumerator GetEnumerator() => new(this); + IEnumerator> IEnumerable>.GetEnumerator() => new Enumerator(this); + IEnumerator IEnumerable.GetEnumerator() => new Enumerator(this); + + public struct Enumerator : IEnumerator>, IEnumerator + { + private readonly Map _map; + private int _index; + private MapPoint _current; + + internal Enumerator(Map map) + { + _map = map; + _index = 0; + _current = default; + } + + public readonly void Dispose() { } + public bool MoveNext() + { + if ((uint)_index < (uint)_map.Count) + { + _current = new( + _map._values[_index], + _index % _map.Width, + _index / _map.Width, + _map); + _index++; + return true; + } + + _index = _map.Count + 1; + _current = default; + return false; + } + + public readonly MapPoint Current => _current!; + readonly object? IEnumerator.Current + { + get + { + if (_index == 0 || _index == _map.Count + 1) + { + throw new InvalidOperationException(); + } + return Current; + } + } + void IEnumerator.Reset() + { + _index = 0; + _current = default; + } + } +} diff --git a/Core/Collections/MapPoint.cs b/Core/Collections/MapPoint.cs new file mode 100644 index 0000000..bce1e93 --- /dev/null +++ b/Core/Collections/MapPoint.cs @@ -0,0 +1,9 @@ +namespace Just.Core.Collections; + +public readonly struct MapPoint(T value, int x, int y, IMap map) +{ + public readonly T Value = value; + public IMap Map { get; } = map; + public int X { get; } = x; + public int Y { get; } = y; +} diff --git a/Core/Core.csproj b/Core/Core.csproj new file mode 100644 index 0000000..ed9c859 --- /dev/null +++ b/Core/Core.csproj @@ -0,0 +1,34 @@ + + + + net8.0 + enable + enable + Just.Core + Just.Core + + Small .Net library with useful helper classes, functions and extensions. + extensions;helpers;helper-functions + JustFixMe + Copyright (c) 2023 JustFixMe + LICENSE + README.md + https://github.com/JustFixMe/Just.Core/ + + true + 1.0.0 + $(VersionSuffix) + $(ReleaseVersion) + $(ReleaseVersion) + $(ReleaseVersion) + + + + + + + + + + + diff --git a/Core/Extensions/SystemIOStreamExtensions.cs b/Core/Extensions/SystemIOStreamExtensions.cs new file mode 100644 index 0000000..fc05fb8 --- /dev/null +++ b/Core/Extensions/SystemIOStreamExtensions.cs @@ -0,0 +1,46 @@ +namespace Just.Core.Extensions; + +public static class SystemIOStreamExtensions +{ + public static void Populate(this Stream stream, byte[] buffer, int offset, int length) + => stream.Populate(buffer.AsSpan(offset, length)); + public static void Populate(this Stream stream, byte[] buffer) + => stream.Populate(buffer.AsSpan()); + public static void Populate(this Stream stream, Span buffer) + { + do + { + var readed = stream.Read(buffer); + + if (readed == 0) + { + throw new EndOfStreamException(); + } + + buffer = buffer[readed..]; + } + while (buffer.Length > 0); + } + + public static async ValueTask PopulateAsync(this Stream stream, byte[] buffer, CancellationToken cancellationToken = default) + => await stream.PopulateAsync(buffer.AsMemory(), cancellationToken); + public static async ValueTask PopulateAsync(this Stream stream, byte[] buffer, int offset, int length, CancellationToken cancellationToken = default) + => await stream.PopulateAsync(buffer.AsMemory(offset, length), cancellationToken); + public static async ValueTask PopulateAsync(this Stream stream, Memory buffer, CancellationToken cancellationToken = default) + { + do + { + cancellationToken.ThrowIfCancellationRequested(); + + var readed = await stream.ReadAsync(buffer, cancellationToken); + + if (readed == 0) + { + throw new EndOfStreamException(); + } + + buffer = buffer[readed..]; + } + while (buffer.Length > 0); + } +} diff --git a/Core/Extensions/SystemStringExtensions.cs b/Core/Extensions/SystemStringExtensions.cs new file mode 100644 index 0000000..227d885 --- /dev/null +++ b/Core/Extensions/SystemStringExtensions.cs @@ -0,0 +1,36 @@ +namespace Just.Core.Extensions; + +public static class SystemStringExtensions +{ + /// + /// Indicates whether the specified string is null or an empty string (""). + /// + /// The string to test. + /// true if the value parameter is null or an empty string (""); otherwise, false. + public static bool IsNullOrEmpty([NotNullWhen(false)] this string? str) => string.IsNullOrEmpty(str); + + /// + /// Indicates whether a specified string is null, empty, or consists only of white-space + /// characters. + /// + /// The string to test. + /// true if the value parameter is null or , or if value consists + /// exclusively of white-space characters. + public static bool IsNullOrWhiteSpace([NotNullWhen(false)] this string? str) => string.IsNullOrWhiteSpace(str); + + + /// + /// Indicates whether the specified string contains any characters. + /// + /// The string to test. + /// true if the value parameter contains any characters; otherwise, false. + public static bool IsNotNullOrEmpty([NotNullWhen(true)] this string? str) => !string.IsNullOrEmpty(str); + + /// + /// Indicates whether a specified string contains non white-space characters. + /// + /// The string to test. + /// true if the value parameter contains non white-space characters; otherwise, false. + public static bool IsNotNullOrWhiteSpace([NotNullWhen(true)] this string? str) => !string.IsNullOrWhiteSpace(str); + +} diff --git a/Core/usings.cs b/Core/usings.cs new file mode 100644 index 0000000..4b6f5ad --- /dev/null +++ b/Core/usings.cs @@ -0,0 +1,3 @@ +global using System.Diagnostics.CodeAnalysis; +global using System.Diagnostics.Contracts; +global using System.Runtime.CompilerServices; diff --git a/JustDotNet.Core.sln b/JustDotNet.Core.sln new file mode 100644 index 0000000..a9adb91 --- /dev/null +++ b/JustDotNet.Core.sln @@ -0,0 +1,28 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Core", "Core\Core.csproj", "{C709D8C9-FE18-4B70-ABE0-57A1850C3398}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Core.Tests", "Core.Tests\Core.Tests.csproj", "{CBA236E8-5CAC-4587-AD7C-A480CD998EB8}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C709D8C9-FE18-4B70-ABE0-57A1850C3398}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C709D8C9-FE18-4B70-ABE0-57A1850C3398}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C709D8C9-FE18-4B70-ABE0-57A1850C3398}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C709D8C9-FE18-4B70-ABE0-57A1850C3398}.Release|Any CPU.Build.0 = Release|Any CPU + {CBA236E8-5CAC-4587-AD7C-A480CD998EB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CBA236E8-5CAC-4587-AD7C-A480CD998EB8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CBA236E8-5CAC-4587-AD7C-A480CD998EB8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CBA236E8-5CAC-4587-AD7C-A480CD998EB8}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..93713a2 --- /dev/null +++ b/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2023 JustFixMe + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..a6d30af --- /dev/null +++ b/README.md @@ -0,0 +1,18 @@ +# .Net library with helpers, functions and extensions + +Just some stuff that is used in different projects... + +## Features + +- ```Map``` and ```DataMap``` collection types +- Extensions for ```System.String``` and ```System.IO.Stream``` +- Small converters for **Base32** and **Base64Url** encodings + +## Getting Started + +### Install from NuGet.org + +```sh +# install the package using NuGet +dotnet add package Just.Core +```