first commit

This commit is contained in:
2023-12-14 21:48:48 +04:00
commit ef5d53a67f
22 changed files with 1387 additions and 0 deletions

398
.gitignore vendored Normal file
View File

@@ -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

4
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,4 @@
{
"dotnet.defaultSolution": "JustDotNet.Core.sln",
"dotnetAcquisitionExtension.enableTelemetry": false
}

View File

@@ -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<FormatException>();
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void WhenCalledWithNullString_ShouldReturnEmptyArray(string testString)
{
Base32.Decode(testString).Should().BeEmpty();
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -0,0 +1,34 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<AssemblyName>Just.Core.Tests</AssemblyName>
<RootNamespace>Just.Core.Tests</RootNamespace>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="FluentAssertions" Version="6.12.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.0" />
<PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="6.0.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Core\Core.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,2 @@
global using Xunit;
global using FluentAssertions;

137
Core/Base32.cs Normal file
View File

@@ -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<byte> input)
{
if (input.Length == 0)
{
return string.Empty;
}
int outLength = 8 * ((input.Length + 4) / 5);
Span<char> output = stackalloc char[outLength];
_ = Encode(input, output);
return new string(output);
}
[Pure]
public static int Encode(ReadOnlySpan<byte> input, Span<char> output)
{
int i = 0;
ReadOnlySpan<char> 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<char> input)
{
if (input.IsEmpty) return [];
Span<byte> output = stackalloc byte[5 * input.Length / 8];
var size = Decode(input, output);
return output[..size].ToArray();
}
[Pure]
public static int Decode(ReadOnlySpan<char> input, Span<byte> output)
{
input = input.TrimEnd(Padding);
Span<char> 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<char> 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<byte> 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;
}
}

118
Core/Base64Url.cs Normal file
View File

@@ -0,0 +1,118 @@
namespace Just.Core;
public static class Base64Url
{
[Pure] public static Guid DecodeGuid(ReadOnlySpan<char> value)
{
ArgumentOutOfRangeException.ThrowIfNotEqual(value.Length, 22);
Span<byte> guidBytes = stackalloc byte[16];
Span<char> 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<char> input)
{
if (input.IsEmpty) return [];
Span<byte> output = stackalloc byte[3 * ((input.Length + 3) / 4)];
var size = Decode(input, output);
return output[..size].ToArray();
}
[Pure] public static int Decode(ReadOnlySpan<char> value, Span<byte> output)
{
var padding = (4 - (value.Length & 3)) & 3;
var charlen = value.Length + padding;
var outputBytes = charlen / 4;
ArgumentOutOfRangeException.ThrowIfLessThan(output.Length, outputBytes);
Span<char> 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<byte> guidBytes = stackalloc byte[16];
id.TryWriteBytes(guidBytes);
Span<char> 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<byte> input)
{
if (input.IsEmpty) return string.Empty;
int outLength = 8 * ((input.Length + 5) / 6);
Span<char> output = stackalloc char[outLength];
int strlen = Encode(input, output);
return new string(output[..strlen]);
}
[Pure] public static int Encode(ReadOnlySpan<byte> input, Span<char> output)
{
var charlen = 8 * ((input.Length + 5) / 6);
Span<char> 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;
}
}

View File

@@ -0,0 +1,87 @@
using System.Numerics;
namespace Just.Core.Collections;
public class DataMap<T> : Map<T>, IDataMap<T>, ICloneable
where T : IComparisonOperators<T, T, bool>, IEqualityOperators<T, T, bool>
{
internal MapPoint<T> MinCache = default;
internal MapPoint<T> MaxCache = default;
internal DataMap(int width, int height, T[] values)
: base(width, height, values)
{
}
public DataMap(ReadOnlySpan<T> 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<T> Min
{
get
{
if (MinCache.Map is null) FindMinMax();
return MinCache;
}
}
[Pure] public MapPoint<T> 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<T> Clone()
{
var clone = new DataMap<T>(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();
}

View File

@@ -0,0 +1,10 @@
using System.Numerics;
namespace Just.Core.Collections;
public interface IDataMap<T> : IMap<T>, ICloneable
where T : IComparisonOperators<T, T, bool>, IEqualityOperators<T, T, bool>
{
MapPoint<T> Min { get; }
MapPoint<T> Max { get; }
}

12
Core/Collections/IMap.cs Normal file
View File

@@ -0,0 +1,12 @@
namespace Just.Core.Collections;
public interface IMap<T> : IReadOnlyCollection<MapPoint<T>>
{
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<T> Get(int x, int y);
MapPoint<T> Get(double x, double y);
T[,] ToArray();
}

172
Core/Collections/Map.cs Normal file
View File

@@ -0,0 +1,172 @@
using System.Collections;
namespace Just.Core.Collections;
public class Map<T> : IMap<T>
{
internal readonly T[] _values;
internal Map(int width, int height, T[] values)
{
Width = width;
Height = height;
_values = values;
}
public Map(ReadOnlySpan<T> 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<T> AsSpan() => _values;
[Pure] public ReadOnlyMemory<T> 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<T> 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<T> 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<MapPoint<T>> IEnumerable<MapPoint<T>>.GetEnumerator() => new Enumerator(this);
IEnumerator IEnumerable.GetEnumerator() => new Enumerator(this);
public struct Enumerator : IEnumerator<MapPoint<T>>, IEnumerator
{
private readonly Map<T> _map;
private int _index;
private MapPoint<T> _current;
internal Enumerator(Map<T> 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<T> 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;
}
}
}

View File

@@ -0,0 +1,9 @@
namespace Just.Core.Collections;
public readonly struct MapPoint<T>(T value, int x, int y, IMap<T> map)
{
public readonly T Value = value;
public IMap<T> Map { get; } = map;
public int X { get; } = x;
public int Y { get; } = y;
}

34
Core/Core.csproj Normal file
View File

@@ -0,0 +1,34 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<AssemblyName>Just.Core</AssemblyName>
<RootNamespace>Just.Core</RootNamespace>
<Description>Small .Net library with useful helper classes, functions and extensions.</Description>
<PackageTags>extensions;helpers;helper-functions</PackageTags>
<Authors>JustFixMe</Authors>
<Copyright>Copyright (c) 2023 JustFixMe</Copyright>
<PackageLicenseFile>LICENSE</PackageLicenseFile>
<PackageReadmeFile>README.md</PackageReadmeFile>
<RepositoryUrl>https://github.com/JustFixMe/Just.Core/</RepositoryUrl>
<EmitCompilerGeneratedFiles Condition="'$(Configuration)'=='Debug'">true</EmitCompilerGeneratedFiles>
<ReleaseVersion Condition=" '$(ReleaseVersion)' == '' ">1.0.0</ReleaseVersion>
<VersionSuffix Condition=" '$(VersionSuffix)' != '' ">$(VersionSuffix)</VersionSuffix>
<VersionPrefix Condition=" '$(VersionSuffix)' != '' ">$(ReleaseVersion)</VersionPrefix>
<Version Condition=" '$(VersionSuffix)' == '' ">$(ReleaseVersion)</Version>
<AssemblyVersion>$(ReleaseVersion)</AssemblyVersion>
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="$(AssemblyName).Tests" />
</ItemGroup>
<ItemGroup>
<None Include="..\README.md" Pack="true" PackagePath=""/>
<None Include="..\LICENSE" Pack="true" Visible="false" PackagePath=""/>
</ItemGroup>
</Project>

View File

@@ -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<byte> 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<byte> 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);
}
}

View File

@@ -0,0 +1,36 @@
namespace Just.Core.Extensions;
public static class SystemStringExtensions
{
/// <summary>
/// Indicates whether the specified string is null or an empty string ("").
/// </summary>
/// <param name="str">The string to test.</param>
/// <returns>true if the value parameter is null or an empty string (""); otherwise, false.</returns>
public static bool IsNullOrEmpty([NotNullWhen(false)] this string? str) => string.IsNullOrEmpty(str);
/// <summary>
/// Indicates whether a specified string is null, empty, or consists only of white-space
/// characters.
/// </summary>
/// <param name="str">The string to test.</param>
/// <returns>true if the value parameter is null or <see cref="System.String.Empty"/>, or if value consists
/// exclusively of white-space characters.</returns>
public static bool IsNullOrWhiteSpace([NotNullWhen(false)] this string? str) => string.IsNullOrWhiteSpace(str);
/// <summary>
/// Indicates whether the specified string contains any characters.
/// </summary>
/// <param name="str">The string to test.</param>
/// <returns>true if the value parameter contains any characters; otherwise, false.</returns>
public static bool IsNotNullOrEmpty([NotNullWhen(true)] this string? str) => !string.IsNullOrEmpty(str);
/// <summary>
/// Indicates whether a specified string contains non white-space characters.
/// </summary>
/// <param name="str">The string to test.</param>
/// <returns>true if the value parameter contains non white-space characters; otherwise, false.</returns>
public static bool IsNotNullOrWhiteSpace([NotNullWhen(true)] this string? str) => !string.IsNullOrWhiteSpace(str);
}

3
Core/usings.cs Normal file
View File

@@ -0,0 +1,3 @@
global using System.Diagnostics.CodeAnalysis;
global using System.Diagnostics.Contracts;
global using System.Runtime.CompilerServices;

28
JustDotNet.Core.sln Normal file
View File

@@ -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

19
LICENSE Normal file
View File

@@ -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.

18
README.md Normal file
View File

@@ -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
```