From 6df5a85530ba3631d87fb625fd31bf1fbab77035 Mon Sep 17 00:00:00 2001 From: Latency McLaughlin Date: Tue, 9 Apr 2024 02:02:11 -0700 Subject: [PATCH] Update to .NET 9.0 Core --- .github/FUNDING.yml | 14 + .github/ISSUE_TEMPLATE/bug_report.md | 38 ++ .github/ISSUE_TEMPLATE/feature_request.md | 20 + .github/workflows/delete_workflows.yml | 76 ++++ .github/workflows/dotnet.yml | 58 +++ .github/workflows/release.yml | 157 ++++++++ .gitignore | 423 ++++++++++++---------- BitFields.sln | 18 +- BitFields/BtFields.csproj | 26 -- GUI/GUI.csproj | 11 +- LICENSE.txt | 165 --------- MIT-LICENSE.txt | 20 + README - Short.md | 20 - README.md | 97 +++-- Tests/T_EnumExtensions.cs | 101 ------ Tests/Tests.csproj | 17 - Unit Tests/Base.cs | 22 ++ Unit Tests/GlobalUsings.cs | 10 + Unit Tests/T_EnumExtensions.cs | 107 ++++++ Unit Tests/Tests.cs | 14 + Unit Tests/Unit Tests.csproj | 20 + {BitFields => src}/BitField.cs | 0 src/BtFields.csproj | 14 + {BitFields => src}/EnumExtensions.cs | 0 {BitFields => src}/Flags.cs | 0 {BitFields => src}/IToString.cs | 0 src/README_BODY.md | 253 +++++++++++++ {BitFields => src}/ToStringSwitchboard.cs | 0 28 files changed, 1127 insertions(+), 574 deletions(-) create mode 100644 .github/FUNDING.yml create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md create mode 100644 .github/ISSUE_TEMPLATE/feature_request.md create mode 100644 .github/workflows/delete_workflows.yml create mode 100644 .github/workflows/dotnet.yml create mode 100644 .github/workflows/release.yml delete mode 100644 BitFields/BtFields.csproj delete mode 100644 LICENSE.txt create mode 100644 MIT-LICENSE.txt delete mode 100644 README - Short.md delete mode 100644 Tests/T_EnumExtensions.cs delete mode 100644 Tests/Tests.csproj create mode 100644 Unit Tests/Base.cs create mode 100644 Unit Tests/GlobalUsings.cs create mode 100644 Unit Tests/T_EnumExtensions.cs create mode 100644 Unit Tests/Tests.cs create mode 100644 Unit Tests/Unit Tests.csproj rename {BitFields => src}/BitField.cs (100%) create mode 100644 src/BtFields.csproj rename {BitFields => src}/EnumExtensions.cs (100%) rename {BitFields => src}/Flags.cs (100%) rename {BitFields => src}/IToString.cs (100%) create mode 100644 src/README_BODY.md rename {BitFields => src}/ToStringSwitchboard.cs (100%) diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..8876c8a --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,14 @@ +# These are supported funding model platforms + +github: [Latency] +patreon: +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry +polar: # Replace with a single Polar username +buy_me_a_coffee: latency +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..dd84ea7 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,38 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: '' +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Desktop (please complete the following information):** + - OS: [e.g. iOS] + - Browser [e.g. chrome, safari] + - Version [e.g. 22] + +**Smartphone (please complete the following information):** + - Device: [e.g. iPhone6] + - OS: [e.g. iOS8.1] + - Browser [e.g. stock browser, safari] + - Version [e.g. 22] + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..bbcbbe7 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: '' +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/workflows/delete_workflows.yml b/.github/workflows/delete_workflows.yml new file mode 100644 index 0000000..f773e89 --- /dev/null +++ b/.github/workflows/delete_workflows.yml @@ -0,0 +1,76 @@ +name: Delete Workflow Runs +on: + workflow_dispatch: + inputs: + days: + description: 'Days-worth of runs to keep for each workflow' + required: true + default: '30' + minimum_runs: + description: 'Minimum runs to keep for each workflow' + required: true + default: '6' + delete_workflow_pattern: + description: 'Name or filename of the workflow (if not set, all workflows are targeted)' + required: false + delete_workflow_by_state_pattern: + description: 'Filter workflows by state: active, deleted, disabled_fork, disabled_inactivity, disabled_manually' + required: true + default: "ALL" + type: choice + options: + - "ALL" + - active + - deleted + - disabled_inactivity + - disabled_manually + delete_run_by_conclusion_pattern: + description: 'Remove runs based on conclusion: action_required, cancelled, failure, skipped, success' + required: true + default: "ALL" + type: choice + options: + - "ALL" + - "Unsuccessful: action_required,cancelled,failure,skipped" + - action_required + - cancelled + - failure + - skipped + - success + dry_run: + description: 'Dry Run' + default: false + type: boolean + required: false + +jobs: + del_runs: + runs-on: ubuntu-latest + permissions: + actions: write + contents: read + steps: + - name: Delete workflow runs + run: | + if [ ${{ github.event.inputs.dry_run }} = true ]; then + echo "DRY_RUN=${{ github.event.inputs.dry_run }}" >> $GITHUB_ENV + else + echo "DRY_RUN=" >> $GITHUB_ENV + fi + + - name: Delete workflow runs + uses: Mattraks/delete-workflow-runs@v2.0.6 + with: + token: ${{ github.token }} + repository: ${{ github.repository }} + retain_days: ${{ github.event.inputs.days }} + keep_minimum_runs: ${{ github.event.inputs.minimum_runs }} + delete_workflow_pattern: ${{ github.event.inputs.delete_workflow_pattern }} + delete_workflow_by_state_pattern: ${{ github.event.inputs.delete_workflow_by_state_pattern }} + delete_run_by_conclusion_pattern: >- + ${{ + startsWith(github.event.inputs.delete_run_by_conclusion_pattern, 'Unsuccessful:') + && 'action_required,cancelled,failure,skipped' + || github.event.inputs.delete_run_by_conclusion_pattern + }} + dry_run: ${{ env.DRY_RUN }} diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml new file mode 100644 index 0000000..b60ea52 --- /dev/null +++ b/.github/workflows/dotnet.yml @@ -0,0 +1,58 @@ +name: .NET Core Desktop Build +env: + NUGET_SERVER_URL: "https://nuget.pkg.github.com/${{ github.repository_owner }}/index.json" + NUGET_CONFIG: "../NuGet.config" + GH_TOKEN: ${{ secrets.LATENCY_PAT }} + +on: + push: + branches: master + + pull_request: + + workflow_dispatch: + +jobs: + build: + if: ${{ startsWith(github.ref, 'refs/tags/') == false }} + runs-on: ${{ matrix.os }} + + strategy: + matrix: + os: [self-hosted] #, ubuntu-latest, windows-latest] + BuildConfiguration: [ Release ] + max-parallel: 2 + + steps: + + - name: Copy NuGet.Config Template + shell: bash + run: | + cp ../NuGet.Config.template ../NuGet.Config + + - name: Update NuGet Config + shell: bash + run: | + nuget config -Set defaultPushSource="${{ env.NUGET_SERVER_URL }}" -ConfigFile ${{ env.NUGET_CONFIG }} + dotnet nuget add source --username ${{ github.repository_owner }} --password ${{ secrets.NUGET_AUTH_TOKEN }} --protocol-version 3 --configfile ${{ env.NUGET_CONFIG }} --store-password-in-clear-text --name github "${{ env.NUGET_SERVER_URL }}" + + - uses: actions/checkout@v4.1.1 + with: + fetch-depth: '0' + + - uses: actions/setup-dotnet@v4.0.0 + if: matrix.os != 'self-hosted' + with: + dotnet-version: '8.0.x' + dotnet-quality: 'signed' + source-url: ${{ env.NUGET_SERVER_URL }} + env: + NUGET_AUTH_TOKEN: ${{ secrets.NUGET_AUTH_TOKEN }} + + - name: Restore dependencies + run: dotnet restore + + - name: Build + id: build + run: | + dotnet build --no-restore --configuration ${{ matrix.BuildConfiguration }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..81b5c38 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,157 @@ +name: .NET Core Desktop Release +env: + NUGET_SERVER_URL: "https://nuget.pkg.github.com/${{ github.repository_owner }}/index.json" + GH_TOKEN: ${{ secrets.LATENCY_PAT }} + +on: + push: + tags: 'v[0-9]+.[0-9]+.[0-9]+' + + workflow_dispatch: + +jobs: + pre_job: + runs-on: ubuntu-latest + outputs: + should_skip: ${{ steps.skip_check.outputs.should_skip }} + steps: + - id: skip_check + uses: fkirc/skip-duplicate-actions@v5.3.1 + with: + skip_after_successful_duplicate: 'true' + + release: + needs: pre_job + if: ${{ needs.pre_job.outputs.should_skip != 'true' }} + runs-on: ${{ matrix.os }} + + permissions: + packages: write + contents: write # write permission is required to create a github release + pull-requests: write # write permission is required for autolabeler otherwise, read permission is required at least + + strategy: + matrix: + os: [self-hosted] #, ubuntu-latest, windows-latest] + BuildConfiguration: [ Release ] + max-parallel: 2 + + steps: + + - name: Get PROJECT_NAME + id: project-name + shell: bash + run: | + if [ "$RUNNER_OS" == "Linux" ]; then + split=(${GITHUB_REPOSITORY//\// }) + elif [ "$RUNNER_OS" == "Windows" ]; then + split=(${GITHUB_REPOSITORY////// }) + else + echo "$RUNNER_OS not supported" + exit 1 + fi + index=$((${#split[@]}-1)) + project_tag=${split[$index]} + echo "$project_tag" + echo "PROJECT_NAME=$project_tag" >> $GITHUB_ENV + + - name: Get README.md Description & PACKAGE_VERSION + id: readme-desc + shell: bash + run: | + if [ "$RUNNER_OS" == "Linux" ]; then + filenames=$(ls ${{ github.workspace }}) + elif [ "$RUNNER_OS" == "Windows" ]; then + filenames=$(ls ${GITHUB_WORKSPACE//\//\\ }) + else + echo "$RUNNER_OS not supported" + exit 1 + fi + for filename in ${filenames[@]}; do + if [ -f $filename -a "$filename" = "README.md" ]; then + desc=$(sed -n '2{P;q;}' $filename | sed 's/\n$//' | sed 's/\r$//' | cut -c 5- ) + echo "$desc" + echo "README_DESC=$desc" >> $GITHUB_ENV + + regex='\| VERSION:.*-([0-9]+(\.[0-9]+){2,})[-a-z]*' + if [[ $(grep VERSION: $filename) =~ $regex ]]; then + package_version=${BASH_REMATCH[1]} + echo "$package_version" + echo "PACKAGE_VERSION=$package_version" >> $GITHUB_ENV + fi + + break + fi + done + + - name: Query Release (if exists) + shell: bash + run: | + version=v${{ env.PACKAGE_VERSION }} + cd src + array=$(gh release list -O asc | cut -f3) + cd .. + echo "FIRST_RELEASE=$(echo $array | awk '{print $1}')" >> $GITHUB_ENV + if [[ ${array[@]} =~ $version ]]; then + echo "Release '$version' was found." + echo "RELEASE_FOUND=true" >> $GITHUB_ENV + else + echo "No release exists with version '$version'." + echo "RELEASE_FOUND=false" >> $GITHUB_ENV + fi + + - name: Delete Release + if: ${{ env.release_found == 'true' }} + shell: bash + run: | + echo "Deleting current release '$version'" + gh release delete $version --cleanup-tag + env: + release_found: '${{ env.RELEASE_FOUND }}' + version: 'v${{ env.PACKAGE_VERSION }}' + + - name: Create Release + shell: bash + run: | + draft=false + prerelease=false + body="${{ env.README_DESC }} + ${{ steps.github_release.outputs.changelog }}" + if [ "$draft" = "true" ]; then + d='-d ' + fi + if [ "$prerelease" = "true" ]; then + p='-p ' + fi + echo "gh release create \"v${{ env.PACKAGE_VERSION }}\" ${p}${d}--generate-notes --notes-start-tag \"${{ env.FIRST_RELEASE }}\" --title \"${{ env.PROJECT_NAME }}\" -n \"$body\"" + gh release create "v${{ env.PACKAGE_VERSION }}" ${p}${d}--generate-notes --notes-start-tag "${{ env.FIRST_RELEASE }}" --title "${{ env.PROJECT_NAME }}" -n "$body" + + - name: Check If NuGet Package Exists + id: locate-package + shell: bash + run: | + echo "nuget-exists=false" >> $GITHUB_OUTPUT + array=$(nuget search "${{ env.PROJECT_NAME }}" -Source "github" | grep "No results found.\|^>") + if [ "$array" != "No results found." ]; then + ary=($(echo "$array" | grep '^> ' | cut -c 3- | awk '{print $1} {print $3}')) + name=${ary[0]} + version=${ary[1]} + if [ "$name" = "${{ env.PROJECT_NAME }}" -a "$version" = "${{ env.PACKAGE_VERSION }}" ]; then + echo "Package '${{ env.PROJECT_NAME }}.${{ env.PACKAGE_VERSION }}.nupkg' was found to exist." + echo "nuget-exists=true" >> $GITHUB_OUTPUT + fi + fi + + - name: Remove Existing NuGet Package + if: ${{ steps.locate-package.outputs.nuget-exists == 'true' }} + #run: dotnet nuget delete ${{ env.PROJECT_NAME }} ${{ env.PACKAGE_VERSION }} --api-key ${{ secrets.NUGET_AUTH_TOKEN }} --non-interactive + uses: actions/delete-package-versions@v5.0.0 + with: + owner: ${{ github.repository_owner }} + package-name: ${{ env.PROJECT_NAME }} + package-type: 'nuget' + token: ${{ secrets.NUGET_AUTH_TOKEN }} + + - name: Push package to GitHub packages + run: | + dotnet nuget push "D:\Source\Packages\${{ env.PROJECT_NAME }}.${{ env.PACKAGE_VERSION }}.nupkg" -n --skip-duplicate -k ${{ secrets.NUGET_AUTH_TOKEN }} diff --git a/.gitignore b/.gitignore index bbebba1..d82e07c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,201 +1,222 @@ -## Ignore Visual Studio temporary files, build results, and -## files generated by popular Visual Studio add-ons. - -# User-specific files -*.suo -*.user -*.userosscache -*.sln.docstates - -# User-specific files (MonoDevelop/Xamarin Studio) -*.userprefs - -# Build results -[Dd]ebug/ -[Dd]ebugPublic/ -[Rr]elease/ -[Rr]eleases/ -x64/ -x86/ -build/ -bld/ -[Bb]in/ -[Oo]bj/ - -# Visual Studo 2015 cache/options directory -.vs/ - -# MSTest test Results -[Tt]est[Rr]esult*/ -[Bb]uild[Ll]og.* - -# NUNIT -*.VisualState.xml -TestResult.xml - -# Build Results of an ATL Project -[Dd]ebugPS/ -[Rr]eleasePS/ -dlldata.c - -*_i.c -*_p.c -*_i.h -*.ilk -*.meta -*.obj -*.pch -*.pdb -*.pgc -*.pgd -*.rsp -*.sbr -*.tlb -*.tli -*.tlh -*.tmp -*.tmp_proj -*.log -*.vspscc -*.vssscc -.builds -*.pidb -*.svclog -*.scc - -# Chutzpah Test files -_Chutzpah* - -# Visual C++ cache files -ipch/ -*.aps -*.ncb -*.opensdf -*.sdf -*.cachefile - -# Visual Studio profiler -*.psess -*.vsp -*.vspx - -# TFS 2012 Local Workspace -$tf/ - -# Guidance Automation Toolkit -*.gpState - -# ReSharper is a .NET coding add-in -_ReSharper*/ -*.[Rr]e[Ss]harper -*.DotSettings.user - -# JustCode is a .NET coding addin-in -.JustCode - -# TeamCity is a build add-in -_TeamCity* - -# DotCover is a Code Coverage Tool -*.dotCover - -# NCrunch -_NCrunch_* -.*crunch*.local.xml - -# 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 -# TODO: 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 - -# The packages folder can be ignored because of Package Restore -**/packages/* -# except build/, which is used as an MSBuild target. -!**/packages/build/ -# Uncomment if necessary however generally it will be regenerated when needed -#!**/packages/repositories.config - -# Windows Azure Build Output -csx/ -*.build.csdef - -# Windows Store app package directory -AppPackages/ - -# Others -*.[Cc]ache -ClientBin/ -[Ss]tyle[Cc]op.* -~$* -*~ -*.dbmdl -*.dbproj.schemaview -*.pfx -*.publishsettings -node_modules/ -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 - -# SQL Server files -*.mdf -*.ldf - -# Business Intelligence projects -*.rdl.data -*.bim.layout -*.bim_*.settings - -# Microsoft Fakes -FakesAssemblies/ - -# Node.js Tools for Visual Studio -.ntvs_analysis.dat - -# Visual Studio 6 build log -*.plg - -# Visual Studio 6 workspace options file -*.opt - -# NuGet -NuGet/ - -# Git -.gitignore -.gitattributes +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +src/**/build/ +tests/**/build/ +bld/ +[Bb]in/ +[Oo]bj/ +packages/ + +# Visual Studo 2015 cache/options directory +.vs/ + +# Jetbrains Rider cache/options directory +.idea/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opensdf +*.sdf +*.cachefile + +# Visual Studio profiler +*.psess +*.vsp +*.vspx + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper + +# Visual Studio preference files +*.DotSettings.user +*.csproj.user +*.vcxproj.filters + +# JustCode is a .NET coding addin-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml + +# 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 +# TODO: 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 + +# NuGet Packages +#*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config + +# Windows Azure Build Output +csx/ +*.build.csdef + +# Windows Store app package directory +AppPackages/ + +# Others +*.[Cc]ache +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.publishsettings +node_modules/ +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 + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +**/node_modules +**/node_modules/* +**/Images/ActualOutput +**/Images/ReferenceOutput + +# ASP.NET 5 +project.lock.json + +#BenchmarkDotNet +**/BenchmarkDotNet.Artifacts/ + +# Build process +*.csproj.bak + +# Advanced Installer +*-cache/ +*-SetupFiles/ + +# LFS +.lfsconfig \ No newline at end of file diff --git a/BitFields.sln b/BitFields.sln index eb2e72e..0fa1bdc 100644 --- a/BitFields.sln +++ b/BitFields.sln @@ -1,13 +1,13 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.26730.16 +# Visual Studio Version 17 +VisualStudioVersion = 17.9.34723.18 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GUI", "GUI\GUI.csproj", "{32E2B0E5-3F0D-4132-A0FA-16D9BFE99B87}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GUI", "GUI\GUI.csproj", "{32E2B0E5-3F0D-4132-A0FA-16D9BFE99B87}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BtFields", "BitFields\BtFields.csproj", "{6910A029-9C6A-4DD8-B965-4D26A0D81230}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BtFields", "src\BtFields.csproj", "{6910A029-9C6A-4DD8-B965-4D26A0D81230}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Tests", "Tests\Tests.csproj", "{CBAB6A28-BBC9-4CE4-8842-8C32C58734C9}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Unit Tests", "Unit Tests\Unit Tests.csproj", "{AD228C25-2BF6-4C8A-B7F3-4749FAE387AE}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -23,10 +23,10 @@ Global {6910A029-9C6A-4DD8-B965-4D26A0D81230}.Debug|Any CPU.Build.0 = Debug|Any CPU {6910A029-9C6A-4DD8-B965-4D26A0D81230}.Release|Any CPU.ActiveCfg = Release|Any CPU {6910A029-9C6A-4DD8-B965-4D26A0D81230}.Release|Any CPU.Build.0 = Release|Any CPU - {CBAB6A28-BBC9-4CE4-8842-8C32C58734C9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {CBAB6A28-BBC9-4CE4-8842-8C32C58734C9}.Debug|Any CPU.Build.0 = Debug|Any CPU - {CBAB6A28-BBC9-4CE4-8842-8C32C58734C9}.Release|Any CPU.ActiveCfg = Release|Any CPU - {CBAB6A28-BBC9-4CE4-8842-8C32C58734C9}.Release|Any CPU.Build.0 = Release|Any CPU + {AD228C25-2BF6-4C8A-B7F3-4749FAE387AE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AD228C25-2BF6-4C8A-B7F3-4749FAE387AE}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AD228C25-2BF6-4C8A-B7F3-4749FAE387AE}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AD228C25-2BF6-4C8A-B7F3-4749FAE387AE}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/BitFields/BtFields.csproj b/BitFields/BtFields.csproj deleted file mode 100644 index e53b869..0000000 --- a/BitFields/BtFields.csproj +++ /dev/null @@ -1,26 +0,0 @@ - - - - net48;netcoreapp3.1;net5.0 - BitFields - BitField.Extensions - 1.0.3 - .NET Library For BitField & Enum Extensions - http://latency.github.io/BitFields/ - https://github.com/Latency/BitFields - BitField BitFields C# Enum Enums Library - Port to .NET 5.0 - true - ..\..\..\snKey.snk - BitField.Extensions - project.png - - - - - True - - - - - \ No newline at end of file diff --git a/GUI/GUI.csproj b/GUI/GUI.csproj index fa0533e..65cb500 100644 --- a/GUI/GUI.csproj +++ b/GUI/GUI.csproj @@ -2,21 +2,14 @@ WinExe - net5.0-windows + net9.0-windows true - true - ..\..\..\snKey.snk - ..\..\..\project.ico GUI.Program false - - - - - + \ No newline at end of file diff --git a/LICENSE.txt b/LICENSE.txt deleted file mode 100644 index 1dd90f2..0000000 --- a/LICENSE.txt +++ /dev/null @@ -1,165 +0,0 @@ -GNU LESSER GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - - This version of the GNU Lesser General Public License incorporates -the terms and conditions of version 3 of the GNU General Public -License, supplemented by the additional permissions listed below. - - 0. Additional Definitions. - - As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the GNU -General Public License. - - "The Library" refers to a covered work governed by this License, -other than an Application or a Combined Work as defined below. - - An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - - A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - - The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - - The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - - 1. Exception to Section 3 of the GNU GPL. - - You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - - 2. Conveying Modified Versions. - - If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - - a) under this License, provided that you make a good faith effort to - ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or - - b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - - 3. Object Code Incorporating Material from Library Header Files. - - The object code form of an Application may incorporate material from -a header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the - Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the object code with a copy of the GNU GPL and this license - document. - - 4. Combined Works. - - You may convey a Combined Work under terms of your choice that, -taken together, effectively do not restrict modification of the -portions of the Library contained in the Combined Work and reverse -engineering for debugging such modifications, if you also do each of -the following: - - a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the Combined Work with a copy of the GNU GPL and this license - document. - - c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. - - d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of this - License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (a) uses at run time - a copy of the Library already present on the user's computer - system, and (b) will operate properly with a modified version - of the Library that is interface-compatible with the Linked - Version. - - e) Provide Installation Information, but only if you would otherwise - be required to provide such information under section 6 of the - GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the - Application with a modified version of the Linked Version. (If - you use option 4d0, the Installation Information must accompany - the Minimal Corresponding Source and Corresponding Application - Code. If you use option 4d1, you must provide the Installation - Information in the manner specified by section 6 of the GNU GPL - for conveying Corresponding Source.) - - 5. Combined Libraries. - - You may place library facilities that are a work based on the -Library side by side in a single library together with other library -facilities that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based - on the Library, uncombined with any other library facilities, - conveyed under the terms of this License. - - b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - - 6. Revised Versions of the GNU Lesser General Public License. - - The Free Software Foundation may publish revised and/or new versions -of the GNU Lesser General Public License from time to time. Such new -versions will be similar in spirit to the present version, but may -differ in detail to address new problems or concerns. - - Each version is given a distinguishing version number. If the -Library as you received it specifies that a certain numbered version -of the GNU Lesser General Public License "or any later version" -applies to it, you have the option of following the terms and -conditions either of that published version or of any later version -published by the Free Software Foundation. If the Library as you -received it does not specify a version number of the GNU Lesser -General Public License, you may choose any version of the GNU Lesser -General Public License ever published by the Free Software Foundation. - - If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the -Library. \ No newline at end of file diff --git a/MIT-LICENSE.txt b/MIT-LICENSE.txt new file mode 100644 index 0000000..46737c3 --- /dev/null +++ b/MIT-LICENSE.txt @@ -0,0 +1,20 @@ +Copyright (c) 2012-2024 Scott Chacon and others + +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. diff --git a/README - Short.md b/README - Short.md deleted file mode 100644 index d314eb1..0000000 --- a/README - Short.md +++ /dev/null @@ -1,20 +0,0 @@ -# BitFields.Extensions - -### .NET API library for BitFields - ---- - -* CREATED BY: [Latency McLaughlin] -* FRAMEWORK: [.NET] v4.8 - v5.0, & Core v[3.1](https://www.microsoft.com/net/download/windows) -* LANGUAGE: [C#] (v8.0) -* GFX SUBSYS: [WinForms] -* SUPPORTS: [Visual Studio] 2019, 2017, 2015, 2013, 2012, 2010, 2008 -* UPDATED: 01/09/2021 -* VERSION: [1.0.3](https://www.nuget.org/packages/BitField.Extensions/1.0.3/) -* TAGS: [API], [.NET], [C#], [WinForms] - ---- - -![Sample Image](http://bio-hazard.us/bitfields/images/BitFields.jpg) - -A simple use of bit fields as flags. Bit fields allow packaging of data into simple structures, and they are particularly useful when bandwidth, memory or data storage is at a premium. This might not appear to be an issue with modern day equipment or every day applications, but we can save up to 16 times more memory and storage when using bit fields instead of other value types such as Boolean. \ No newline at end of file diff --git a/README.md b/README.md index f7fff74..78e72bb 100644 --- a/README.md +++ b/README.md @@ -1,32 +1,52 @@ -# BitFields.Extensions +# BtFields +### .NET Library For BitField & Enum Extensions -### .NET API library for BitFields --- -* CREATED BY: [Latency McLaughlin] -* FRAMEWORK: [.NET] v4.8 - v5.0, & Core v[3.1](https://www.microsoft.com/net/download/windows) -* LANGUAGE: [C#] (v8.0) -* GFX SUBSYS: [WinForms] -* SUPPORTS: [Visual Studio] 2019, 2017, 2015, 2013, 2012, 2010, 2008 -* UPDATED: 01/09/2021 -* VERSION: [1.0.3](https://www.nuget.org/packages/BitField.Extensions/1.0.3/) -* TAGS: [API], [.NET], [C#], [WinForms] ---- +| | Description | +|--------------|----------------------------------------------------------------| +| CREATED BY: | Latency McLaughlin | +| UPDATED: | 4/9/2024 | +| FRAMEWORK: | [net452], [netstandard2.0], [netstandard2.1] ([Latest]) | +| LANGUAGE: | [C#] preview | +| OUTPUT TYPE: | Library [API] | +| SUPPORTS: | [Visual Studio] | +| GFX SUBSYS: | [None] | +| TAGS: | [BitField BitFields C# Enum Enums Library] | +| STATUS | [![.NET](https://github.com/Latency/BtFields/actions/workflows/dotnet.yml/badge.svg)](https://github.com/Latency/BtFields/actions/workflows/dotnet.yml) | +| LICENSE: | [![License](https://img.shields.io/badge/MIT-License-yellowgreen.svg)](https://github.com/Latency/BtFields/blob/master/MIT-LICENSE.txt) | +| VERSION: | [![GitHub Release](https://img.shields.io/badge/Version-1.0.4-blue)](https://github.com/Latency/BtFields/releases) | +

Sample image

+ +
+ +## Navigation + + +
+

Introduction

+

This article demonstrates a simple use of bit fields as flags for Windows forms. Bit fields allow packaging of data into simple structures, and they are particularly useful when bandwidth, memory or data storage is at a premium. This might not appear to be an issue with modern day equipment or every day applications, but we can save up to 16 times more memory and storage when using bit fields instead of other value types such as boolean.

+

Background

+

Storage

Consider a boolean value in .NET:

bool bVal;

Boolean value data types are stored as 16-bit (2-byte) numbers that can only be true or false. Consider an unsigned 16-bit number which ranges from 0 to 65535:

Decimal        Hexidecimal    Binary
@@ -55,7 +75,10 @@
 16384          0x4000         0100000000000000
 32768          0x8000         1000000000000000

With only 16 settings, this might not appear to be an issue and one would more than likely store the settings as Boolean values, however, storing a history of those settings can quickly add up, and saving space by a factor of 16 can make a difference. Ever tried loading a 100MB file into memory and then manipulating it? How about a 1.6GB file?

-

Understanding bit shifting <<

f1 = 0x01        // 0x01        1    00000001
+
+

Understanding bit shifting <<

+ +
f1 = 0x01        // 0x01        1    00000001
 f2 = f1 << 1,    // 0x02        2    00000010
 f3 = f2 << 1,    // 0x04        4    00000100
 f4 = f3 << 1,    // 0x08        8    00001000
@@ -66,13 +89,17 @@
  • >> for shifting to the right.
  • If a shift operation causes some number of bits to go outside of an underlying data type, then those bits are discarded. Empty bit positions created by the shift operation are always filled with 0s in a left shift operation and in a positive right shift operation. If a negative number of bit places is requested in a right shift operation f2 >> -2, then the vacated bit positions are filled with 1s.

    +

    Understanding bitwise operations

    +

    Bitwise operations are used to manipulate the bit field, and determine if a specified flag is set. The following truth tables illustrate the truth values of some operations:

    Mask OR Flag     Mask AND NOT Flag    Mask XOR Flag        
     0 | 0 = 0        0 & ~0 = 0           0 ^ 0 = 0                     
     1 | 0 = 1        1 & ~0 = 1           1 ^ 0 = 1                     
     0 | 1 = 1        0 & ~1 = 0           0 ^ 1 = 1                     
     1 | 1 = 1        1 & ~1 = 0           1 ^ 1 = 0
    +

    Using the code

    +

    The BitField class/structure uses an enumeration to define the flags in the bit field. The field can store up to 64 unique flags using the 64-bit unsigned ulong value type. The flags can have any name, but be careful with the Clear flag as this has a special value that is used to clear and fill the entire bit field.

    [Flags]
     public enum Flag : ulong {
       Clear  = 0x00,
    @@ -96,7 +123,10 @@
         _Mask = value;
       }
     }
    -

    Methods

    + + +

    Methods

    +

    The SetField method sets the specified flag in the mask and turns all other flags off.

    • Bits that are set to 1 in the flag will be set to one in the mask. @@ -199,7 +229,9 @@

      To check if a Flag is on, use:

      if (bitField.IsOn(BitField.Flag.f1)) {
         Console.WriteLine("Flag F1 is On");
       }
      +

      Points of Interest

      +

      The mask value is a 64-bit number that can be stored, retrieved, or passed to other processes and applications that support 64-bit numbers. The BitField class/structure can then be used to retrieve and manipulate the mask. I did not find any resources that explains how bitwise operations are implemented in .NET, and if the operations are implemented efficiently. There might be ways to optimize the code but I have not found a good resource for this yet.

      It is also important to note that there is some overhead in creating a class object, as classes are reference types and structures are value types. If this is an issue then it is possible to implement the bit field operations directly in your code, but that would defeat the purpose of the object-oriented model.

      Another option to consider is using a structure instead of the class.

      @@ -219,12 +251,25 @@
    • You need unlimited event handling support.

    A similar bit field class and bit field structure are included in the source code and demo project. Depending on the use, it might be preferable to use one over the other. It would be interesting to time them and compare actual results to see under which circumstances and how much more efficiently the system can handle the structure.

    +

    References

    +

    Edward Smoljanovic, 20 Apr 2004 - Masks and flags using bit fields in .NET

    -

    License

    -
    -

    - GNU LESSER GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 -

    -
    + +

    Installation

    + +This library can be installed using NuGet found [here](https://www.nuget.org/packages/BitField.Extensions/). + +

    License

    + +The source code for the site is licensed under the MIT license, which you can find in +the [MIT-LICENSE].txt file. + +All graphical assets are licensed under the +[Creative Commons Attribution 3.0 Unported License](https://creativecommons.org/licenses/by/3.0/). + +[//]: # (These are reference links used in the body of this note and get stripped out when the markdown processor does its job.) + + [GNU LESSER GENERAL PUBLIC LICENSE]: + [MSDN article]: + [MIT-License]: diff --git a/Tests/T_EnumExtensions.cs b/Tests/T_EnumExtensions.cs deleted file mode 100644 index ba2e3b9..0000000 --- a/Tests/T_EnumExtensions.cs +++ /dev/null @@ -1,101 +0,0 @@ -// **************************************************************************** -// Project: Tests -// File: T_EnumExtensions.cs -// Author: Latency McLaughlin -// Date: 01/09/2021 -// **************************************************************************** - -using System; -using System.Linq; -using BitFields; -using NUnit.Framework; - -namespace BitFields_Tests { - // ReSharper disable once InconsistentNaming - public class T_EnumExtensions { - [Test] - public void GetAllItems() { - var collectionA = Flag.F1.GetAllItems().ToList(); - Assert.AreEqual(65, collectionA.Count); - - var collectionB = EnumExtensions.GetAllItems().ToList(); - Assert.AreEqual(65, collectionB.Count); - -#if DEBUG - foreach (var enm in collectionB) - Console.WriteLine(enm.GetEnumDescription()); -#endif - } - - [Test] - public void GetAllSelectedItems() { - // If enum is not bitvectored, this will compose (1 | 4) - var collectionA = MyEnum.Test5.GetAllSelectedItems().ToList(); - Assert.AreEqual(1, collectionA.Count); -#if DEBUG - Console.WriteLine("Test ColectionA: Single"); - foreach (var enm in collectionA) - Console.WriteLine(enm.GetEnumDescription()); -#endif - - var collectionB = (MyEnum.Test4 | MyEnum.Test3).GetAllSelectedItems().ToList(); - Assert.AreEqual(2, collectionB.Count); -#if DEBUG - Console.WriteLine("Test ColectionB: Composite"); - foreach (var enm in collectionB) - Console.WriteLine(enm.GetEnumDescription()); -#endif - // Make sure the field (0) is not being transposed from internal ordered mapping. - var collectionC = MyEnum.Test0.GetAllSelectedItems().ToList(); - Assert.AreEqual(1, collectionC.Count); -#if DEBUG - Console.WriteLine("Test ColectionC: Single"); - foreach (var enm in collectionC) - Console.WriteLine(enm.GetEnumDescription()); -#endif - - // Check 1 + 2 = 3 field to see if it is being counted as single. - var collectionD = (MyEnum.Test1 | MyEnum.Test0).GetAllSelectedItems().ToList(); - Assert.AreEqual(2, collectionD.Count); -#if DEBUG - Console.WriteLine("Test ColectionD: Composite"); - foreach (var enm in collectionD) - Console.WriteLine(enm.GetEnumDescription()); -#endif - - // Test overloaded method w/ mask as input. (Test1 | Test0) - var collectionE = EnumExtensions.GetAllSelectedItems(3).ToList(); - Assert.AreEqual(2, collectionE.Count); -#if DEBUG - Console.WriteLine("Test ColectionE: Value->Mapped"); - foreach (var enm in collectionE) - Console.WriteLine(enm.GetEnumDescription()); -#endif - } - - [Test] - public void Contains() { - Assert.IsFalse(MyEnum.Test1.Contains(MyEnum.Test0)); - Assert.IsTrue(MyEnum.Test3.Contains(MyEnum.Test3)); - Assert.IsTrue(EnumExtensions.Contains(5UL, MyEnum.Test0 | MyEnum.Test2)); - Assert.IsTrue(EnumExtensions.Contains(5UL, MyEnum.Test0)); - Assert.IsFalse(EnumExtensions.Contains(5UL, MyEnum.Test1)); - } - - [Test] - public void GetEnumDescription() => Assert.AreEqual("Test1", MyEnum.Test1.GetEnumDescription()); - - /// - /// Create dummy enum to test against internal mapping of values and descriptions accordingly. - /// - [Flags] - private enum MyEnum { - Test0 = 1 << 0, - Test1 = 1 << 1, - Test2 = 1 << 2, - Test3 = 1 << 3, - Test4 = 1 << 4, - Test5 = 1 << 5 - } - } -} \ No newline at end of file diff --git a/Tests/Tests.csproj b/Tests/Tests.csproj deleted file mode 100644 index 4ce4dbf..0000000 --- a/Tests/Tests.csproj +++ /dev/null @@ -1,17 +0,0 @@ - - - - net5.0 - - - - - - - - - - - - - diff --git a/Unit Tests/Base.cs b/Unit Tests/Base.cs new file mode 100644 index 0000000..c8e06cf --- /dev/null +++ b/Unit Tests/Base.cs @@ -0,0 +1,22 @@ +// 1**************************************************************************** +// Project: UnitTests +// File: Base.cs +// Author: Latency McLaughlin +// Date: 1/22/2024 +// **************************************************************************** + +using System.Diagnostics; +using Xunit.Abstractions; + +namespace AssemblyLoader_Unit_Tests +{ + /// + /// Primary Constructor + /// + /// + public abstract class Base(ITestOutputHelper console) + { + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + protected readonly ITestOutputHelper Console = console; + } +} \ No newline at end of file diff --git a/Unit Tests/GlobalUsings.cs b/Unit Tests/GlobalUsings.cs new file mode 100644 index 0000000..4769773 --- /dev/null +++ b/Unit Tests/GlobalUsings.cs @@ -0,0 +1,10 @@ +// 1**************************************************************************** +// Project: UnitTests +// File: GlobalUsings.cs +// Author: Latency McLaughlin +// Date: 1/22/2024 +// **************************************************************************** + +global using Xunit; +global using System.Diagnostics; +global using Xunit.Abstractions; \ No newline at end of file diff --git a/Unit Tests/T_EnumExtensions.cs b/Unit Tests/T_EnumExtensions.cs new file mode 100644 index 0000000..4ce474b --- /dev/null +++ b/Unit Tests/T_EnumExtensions.cs @@ -0,0 +1,107 @@ +// 04**************************************************************************** +// Project: Unit Tests +// File: T_EnumExtensions.cs +// Author: Latency McLaughlin +// Date: 04/09/2024 +// **************************************************************************** + +using System; +using System.Linq; +using BitFields; + +namespace Unit_Tests; +public partial class Tests +{ + [Fact] + public void GetAllItems() + { + var collectionA = Flag.F1.GetAllItems().ToList(); + Assert.Equal(65, collectionA.Count); + + var collectionB = EnumExtensions.GetAllItems().ToList(); + Assert.Equal(65, collectionB.Count); + + #if DEBUG + foreach (var enm in collectionB) + Console.WriteLine(enm.GetEnumDescription()); + #endif + } + + + [Fact] + public void GetAllSelectedItems() + { + // If enum is not bitvectored, this will compose (1 | 4) + var collectionA = MyEnum.Test5.GetAllSelectedItems().ToList(); + Assert.Equal(1, collectionA.Count); + #if DEBUG + Console.WriteLine("Test ColectionA: Single"); + foreach (var enm in collectionA) + Console.WriteLine(enm.GetEnumDescription()); + #endif + + var collectionB = (MyEnum.Test4 | MyEnum.Test3).GetAllSelectedItems().ToList(); + Assert.Equal(2, collectionB.Count); + #if DEBUG + Console.WriteLine("Test ColectionB: Composite"); + foreach (var enm in collectionB) + Console.WriteLine(enm.GetEnumDescription()); + #endif + // Make sure the field (0) is not being transposed from internal ordered mapping. + var collectionC = MyEnum.Test0.GetAllSelectedItems().ToList(); + Assert.Equal(1, collectionC.Count); + #if DEBUG + Console.WriteLine("Test ColectionC: Single"); + foreach (var enm in collectionC) + Console.WriteLine(enm.GetEnumDescription()); + #endif + + // Check 1 + 2 = 3 field to see if it is being counted as single. + var collectionD = (MyEnum.Test1 | MyEnum.Test0).GetAllSelectedItems().ToList(); + Assert.Equal(2, collectionD.Count); + #if DEBUG + Console.WriteLine("Test ColectionD: Composite"); + foreach (var enm in collectionD) + Console.WriteLine(enm.GetEnumDescription()); + #endif + + // Test overloaded method w/ mask as input. (Test1 | Test0) + var collectionE = EnumExtensions.GetAllSelectedItems(3).ToList(); + Assert.Equal(2, collectionE.Count); + #if DEBUG + Console.WriteLine("Test ColectionE: Value->Mapped"); + foreach (var enm in collectionE) + Console.WriteLine(enm.GetEnumDescription()); + #endif + } + + + [Fact] + public void Contains() + { + Assert.False(MyEnum.Test1.Contains(MyEnum.Test0)); + Assert.True(MyEnum.Test3.Contains(MyEnum.Test3)); + Assert.True(EnumExtensions.Contains(5UL, MyEnum.Test0 | MyEnum.Test2)); + Assert.True(EnumExtensions.Contains(5UL, MyEnum.Test0)); + Assert.False(EnumExtensions.Contains(5UL, MyEnum.Test1)); + } + + + [Fact] + public void GetEnumDescription() => Assert.Equal("Test1", MyEnum.Test1.GetEnumDescription()); + + + /// + /// Create dummy enum to test against internal mapping of values and descriptions accordingly. + /// + [Flags] + private enum MyEnum + { + Test0 = 1 << 0, + Test1 = 1 << 1, + Test2 = 1 << 2, + Test3 = 1 << 3, + Test4 = 1 << 4, + Test5 = 1 << 5 + } +} \ No newline at end of file diff --git a/Unit Tests/Tests.cs b/Unit Tests/Tests.cs new file mode 100644 index 0000000..b918e43 --- /dev/null +++ b/Unit Tests/Tests.cs @@ -0,0 +1,14 @@ +// 1**************************************************************************** +// Project: UnitTests +// File: Tests.cs +// Author: Latency McLaughlin +// Date: 1/22/2024 +// **************************************************************************** + +using AssemblyLoader_Unit_Tests; + +namespace Unit_Tests; + +public partial class Tests(ITestOutputHelper console) : Base(console) +{ +} \ No newline at end of file diff --git a/Unit Tests/Unit Tests.csproj b/Unit Tests/Unit Tests.csproj new file mode 100644 index 0000000..2decbd9 --- /dev/null +++ b/Unit Tests/Unit Tests.csproj @@ -0,0 +1,20 @@ + + + + Library + false + true + Unit Tests + net9.0 + + + + + + + + + + + + diff --git a/BitFields/BitField.cs b/src/BitField.cs similarity index 100% rename from BitFields/BitField.cs rename to src/BitField.cs diff --git a/src/BtFields.csproj b/src/BtFields.csproj new file mode 100644 index 0000000..a32c2bd --- /dev/null +++ b/src/BtFields.csproj @@ -0,0 +1,14 @@ + + + + Library + net452;netstandard2.0;netstandard2.1 + 1.0.4 + .NET Library For BitField & Enum Extensions + BitField BitFields C# Enum Enums Library + Update target framework to include .NET 9.0 + True + BitField.Extensions + + + \ No newline at end of file diff --git a/BitFields/EnumExtensions.cs b/src/EnumExtensions.cs similarity index 100% rename from BitFields/EnumExtensions.cs rename to src/EnumExtensions.cs diff --git a/BitFields/Flags.cs b/src/Flags.cs similarity index 100% rename from BitFields/Flags.cs rename to src/Flags.cs diff --git a/BitFields/IToString.cs b/src/IToString.cs similarity index 100% rename from BitFields/IToString.cs rename to src/IToString.cs diff --git a/src/README_BODY.md b/src/README_BODY.md new file mode 100644 index 0000000..47ca963 --- /dev/null +++ b/src/README_BODY.md @@ -0,0 +1,253 @@ +

    Sample image

    + +
    + +## Navigation + + + +
    + +

    Introduction

    + +

    This article demonstrates a simple use of bit fields as flags for Windows forms. Bit fields allow packaging of data into simple structures, and they are particularly useful when bandwidth, memory or data storage is at a premium. This might not appear to be an issue with modern day equipment or every day applications, but we can save up to 16 times more memory and storage when using bit fields instead of other value types such as boolean.

    + +

    Background

    + +

    Storage

    +

    Consider a boolean value in .NET:

    bool bVal;
    +

    Boolean value data types are stored as 16-bit (2-byte) numbers that can only be true or false. Consider an unsigned 16-bit number which ranges from 0 to 65535:

    Decimal        Hexidecimal    Binary
    +0              0x0000         0000000000000000
    +65535          0xffff         1111111111111111
    +

    When numeric data types are converted to boolean values, 0 becomes false and all other values become true. When Boolean values are converted to numeric types, false becomes 0 and true becomes -1 (using a signed number).

    +

    If we want to use a boolean value to represent a two-state value of a flag or setting in our program (true <=> on, false <=> off), then this would be stored as a 16-bit number.

    +

    Consider using a binary digit to represent the same two-state value: (1 <=> on, 0 <=> off):

    Decimal        Hexidecimal    Binary
    +0              0x0000         0000000000000000
    +1              0x0001         0000000000000001
    +

    We can use this same 16-bit number to represent 16 unique settings by inspecting each digit and determining if it is 1/on or 0/off:

    Decimal        Hexidecimal    Binary
    +1              0x0001         0000000000000001
    +2              0x0002         0000000000000010
    +4              0x0004         0000000000000100
    +8              0x0008         0000000000001000
    +16             0x0010         0000000000010000
    +32             0x0020         0000000000100000
    +64             0x0040         0000000001000000
    +128            0x0080         0000000010000000
    +256            0x0100         0000000100000000
    +512            0x0200         0000001000000000
    +1024           0x0400         0000010000000000
    +2048           0x0800         0000100000000000
    +4096           0x1000         0001000000000000
    +8192           0x2000         0010000000000000
    +16384          0x4000         0100000000000000
    +32768          0x8000         1000000000000000
    +

    With only 16 settings, this might not appear to be an issue and one would more than likely store the settings as Boolean values, however, storing a history of those settings can quickly add up, and saving space by a factor of 16 can make a difference. Ever tried loading a 100MB file into memory and then manipulating it? How about a 1.6GB file?

    + +

    Understanding bit shifting <<

    + +
    f1 = 0x01        // 0x01        1    00000001
    +f2 = f1 << 1,    // 0x02        2    00000010
    +f3 = f2 << 1,    // 0x04        4    00000100
    +f4 = f3 << 1,    // 0x08        8    00001000
    +

    Shifting to the Left or the Right.

    +

    There are two operators:

    +
      +
    • << for shifting a specified number of bits to the left (towards the "high order" bits) +
    • >> for shifting to the right.
    • +
    +

    If a shift operation causes some number of bits to go outside of an underlying data type, then those bits are discarded. Empty bit positions created by the shift operation are always filled with 0s in a left shift operation and in a positive right shift operation. If a negative number of bit places is requested in a right shift operation f2 >> -2, then the vacated bit positions are filled with 1s.

    + +

    Understanding bitwise operations

    + +

    Bitwise operations are used to manipulate the bit field, and determine if a specified flag is set. The following truth tables illustrate the truth values of some operations:

    Mask OR Flag     Mask AND NOT Flag    Mask XOR Flag        
    +0 | 0 = 0        0 & ~0 = 0           0 ^ 0 = 0                     
    +1 | 0 = 1        1 & ~0 = 1           1 ^ 0 = 1                     
    +0 | 1 = 1        0 & ~1 = 0           0 ^ 1 = 1                     
    +1 | 1 = 1        1 & ~1 = 0           1 ^ 1 = 0
    + +

    Using the code

    + +

    The BitField class/structure uses an enumeration to define the flags in the bit field. The field can store up to 64 unique flags using the 64-bit unsigned ulong value type. The flags can have any name, but be careful with the Clear flag as this has a special value that is used to clear and fill the entire bit field.

    [Flags]
    +public enum Flag : ulong {
    +  Clear  = 0x00,
    +  f1     = 0x01,
    +  f2     = f1 << 1,
    +  . . .
    +}
    +

    Each Flag enumeration is a number that in binary form has one digit set to 1 and the rest set to 0. With this enumeration, there are exactly 64 distinct values with a single 1, and 2^64 (18446744073709551616) possible combinations of these 64 flags.

    +

    Some points to make about [FlagsAttribute] == [Flags]:

    +
      +
    • An enumeration is treated as a bit field; that is, a mask comprised of a set of flags. +
    • The results from bitwise operations are also bit fields. +
    • Bit fields are generally used for lists of elements that might occur in combination, whereas enumeration constants are generally used for lists of mutually exclusive elements. Therefore, bit fields are designed to be combined to generate unnamed values, whereas enumerated constants are not.
    • +
    +

    The bit field is stored in the variable _Mask, and external access is provided through the public properties get and set.

    private ulong _Mask;    
    +public ulong Mask {
    +  get {
    +    return _Mask;
    +  }
    +  set {
    +    _Mask = value;
    +  }
    +}
    + + +

    Methods

    + +

    The SetField method sets the specified flag in the mask and turns all other flags off.

    +
      +
    • Bits that are set to 1 in the flag will be set to one in the mask. +
    • Bits that are set to 0 in the flag will be set to zero in the mask.
    • +
    private void SetField(Flag flg) {
    +  Mask = (ulong)flg;
    +}
    +

    This is particularly useful for setting all bits off using the Flag.Clear flag SetField(Flag.Clear),

    +       Mask =  Flag.Clear
    +<=>    Mask =  0000000000000000000000000000000000000000000000000000000000000000
    +

    or setting all bits on using the negation of the Flag.Clear flag SetField(~Flag.Clear).

           Mask = ~Flag.Clear
    +<=>    Mask = ~0000000000000000000000000000000000000000000000000000000000000000
    +<=>    Mask =  1111111111111111111111111111111111111111111111111111111111111111
    +

    The SetOn method sets the specified flag(s) in the mask and leaves all other flags unchanged (using the binary bitwise inclusive OR operator).

    +
      +
    • Bits that are set to 1 in the flag will be set to one in the mask. +
    • Bits that are set to 0 in the flag will be unchanged in the mask.
    • +
    public void SetOn(Flag flg) {
    +  Mask |= (ulong)flg;
    +}
    +

    Since a flag has exactly one digit with a value of 1, and the rest of the digits 0, this will leave the mask unchanged, except for the position(s) where there is a value 1:

    +

    Consider this operation on a random 16-bit Mask:

    +           1101001000011001
    +    OR     F2
    +    -------------------------
    +<=>        1101001000011001
    +    OR     0000000000000010
    +    -------------------------
    +<=>        1101001000011011
    +

    This has the same effect as placing the digit 1 into the appropriate position in the Mask to set the flag to on.

    +

    The SetOff method sets the specified flag(s) off in the mask and leaves all other flags unchanged (using the unary bitwise complement NOT, followed by the binary bitwise AND operator).

    +
      +
    • Bits that are set to 1 in the flag will be set to zero in the mask. +
    • Bits that are set to 0 in the flag will be unchanged in the mask.
    • +
    public void SetOff(Flag flg) {
    +  Mask &= ~(ulong)flg;
    +}
    +

    Since a flag has exactly one digit with a value of 1, and the rest of the digits 0, this will leave the mask unchanged, except for the position(s) where there is a value 1:

    +

    Consider this operation on a random 16-bit Mask:

    +            1101001000011001
    +    AND    ~F1
    +    --------------------------
    +<=>         1101001000011001
    +    AND    ~0000000000000001
    +    --------------------------
    +<=>         1101001000011001
    +    AND     1111111111111110
    +    --------------------------
    +<=>         1101001000011000
    +

    This has the same effect as placing the digit 0 into the appropriate position in the Mask to set the flag to off.

    +

    The SetToggle method toggles the specified flag and leaves all other bits unchanged (using the binary bitwise exclusive OR, XOR operator).

    +
      +
    • Bits that are set to 1 in the flag will be toggled in the mask. +
    • Bits that are set to 0 in the flag will be unchanged in the mask.
    • +
    public void SetToggle(Flag flg) {
    +  Mask ^= (ulong)flg;
    +}
    +

    Since a flag has exactly one digit with a value of 1, and the rest of the digits 0, this will leave the mask unchanged, except for the position where there is a value 1:

    +

    Consider this operation on a random 16-bit Mask:

    +           1101001000011001
    +    XOR    F1
    +    -------------------------
    +<=>        1101001000011001
    +    XOR    0000000000000001
    +    -------------------------
    +<=>        1101001000011000
    +

    This has the same effect as placing the opposite digit in the appropriate position in the Mask to toggle the flag. Using this flag, we don't have to remember the previous state of the flag.

    +

    The AnyOn method checks if any of the specified flag(s) are set to on in the mask. It isolates the appropriate digit(s) and returns true if any are non zero, false otherwise.

    public bool AnyOn (Flag flg) {
    +  return (Mask & (ulong)flg) != 0;
    +}
    +

    The AllOn method checks if all of the specified flag(s) are set to on in the mask. It isolates the appropriate digit(s) and returns true if they all are non zero, false otherwise.

    public bool AllOn (Flag flg) {
    +  return (Mask & (ulong)flg) == (ulong)flg;
    +}
    +

    The IsEqual method checks if all of the specified flag(s) are the same as in the mask. It isolates the appropriate digit(s) and returns true if they are all the same, false otherwise.

    public bool IsEqual (Flag flg) {
    +  return Mask == (ulong)flg;
    +}
    +

    The DecimalToFlag method converts a decimal value to a Flag FlagsAttribute value. The input can be a index between 0 and 64, and the output will be the Flag enumeration corresponding to that index. All it does is take the index, and shift a bit that many positions.

    public static Flag DecimalToFlag(decimal dec) {
    +  Flag flg = Flag.Clear;
    +  ulong tMsk = 0;
    +  byte shift;
    +  try {
    +    shift = (byte)dec;
    +    if (shift > 0 && shift <= 64)
    +      tMsk = (ulong) 0x01 << (shift - 1);
    +    flg = (Flag)tMsk;
    +  } catch (OverflowException e) {   //Byte cast operation
    +    Console.WriteLine("Exception caught in DecimalToFlag: {0}", e.ToString());
    +  }
    +  return flg;
    +}
    +

    The three methods ToStringDec, ToStringHex, ToStringBin return a string representation of the mask in decimal, hexadecimal, and binary notation respectively.

    +

    Using the BitField class/structure.

    +

    Instantiating the object is straight forward:

    BitField bitField = new BitField();
    +

    When creating the struct object using the new operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the new operator, so if you do not use new, the fields will remain unassigned and the object cannot be used until all of the fields are initialized.

    +

    This will create a new bit field and set all flags off. To set all flags on, you can call the method:

    bitField.FillField();
    +

    To set a flag, use:

    bitField.SetOff(BitField.Flag.F1);       //Flag F1 off
    +bitField.SetOn(BitField.Flag.F1);        //Flag F1 on
    +bitField.SetToggle(BitField.Flag.F1);    //Flag F1 off
    +bitField.SetToggle(BitField.Flag.F1);    //Flag F1 on
    +

    To check if a Flag is on, use:

    if (bitField.IsOn(BitField.Flag.f1)) {
    +  Console.WriteLine("Flag F1 is On");
    +}
    + +

    Points of Interest

    + +

    The mask value is a 64-bit number that can be stored, retrieved, or passed to other processes and applications that support 64-bit numbers. The BitField class/structure can then be used to retrieve and manipulate the mask. I did not find any resources that explains how bitwise operations are implemented in .NET, and if the operations are implemented efficiently. There might be ways to optimize the code but I have not found a good resource for this yet.

    +

    It is also important to note that there is some overhead in creating a class object, as classes are reference types and structures are value types. If this is an issue then it is possible to implement the bit field operations directly in your code, but that would defeat the purpose of the object-oriented model.

    +

    Another option to consider is using a structure instead of the class.

    +

    A structure can be preferable when:

    +
      +
    • You have a small amount of data less than 16-bytes, or 128-bits. +
    • You perform a large number of operations on each instance and would incur performance degradation with heap management. +
    • You have no need to inherit the structure or to specialize functionality among its instances. +
    • You do not box and unbox the structure. +
    • You are passing blittable data across a managed/unmanaged boundary.
    • +
    +

    A class is preferable when:

    +
      +
    • You need to use inheritance and polymorphism. +
    • You need to initialize one or more members at creation time. +
    • You need to supply an un-parameterized constructor. +
    • You need unlimited event handling support.
    • +
    +

    A similar bit field class and bit field structure are included in the source code and demo project. Depending on the use, it might be preferable to use one over the other. It would be interesting to time them and compare actual results to see under which circumstances and how much more efficiently the system can handle the structure.

    + +

    References

    + +

    Edward Smoljanovic, 20 Apr 2004 - Masks and flags using bit fields in .NET

    + +

    Installation

    + +This library can be installed using NuGet found [here](https://www.nuget.org/packages/BitField.Extensions/). + +

    License

    + +The source code for the site is licensed under the MIT license, which you can find in +the [MIT-LICENSE].txt file. + +All graphical assets are licensed under the +[Creative Commons Attribution 3.0 Unported License](https://creativecommons.org/licenses/by/3.0/). + +[//]: # (These are reference links used in the body of this note and get stripped out when the markdown processor does its job.) + + [GNU LESSER GENERAL PUBLIC LICENSE]: + [MSDN article]: + [MIT-License]: \ No newline at end of file diff --git a/BitFields/ToStringSwitchboard.cs b/src/ToStringSwitchboard.cs similarity index 100% rename from BitFields/ToStringSwitchboard.cs rename to src/ToStringSwitchboard.cs