diff --git a/.circleci/config.yml b/.circleci/config.yml new file mode 100644 index 0000000..27333a9 --- /dev/null +++ b/.circleci/config.yml @@ -0,0 +1,37 @@ +version: 2.1 + +jobs: + test: + parameters: + dotnet-version: + type: string + docker: + - image: "mcr.microsoft.com/dotnet/sdk:<< parameters.dotnet-version >>" + steps: + - run: + name: Check out the GitHub commit over HTTPS + command: | + if ! command -v git >/dev/null 2>&1; then + apt-get update + apt-get install -y --no-install-recommends git + fi + + git init --quiet + git remote add origin "https://github.com/${CIRCLE_PROJECT_USERNAME}/${CIRCLE_PROJECT_REPONAME}.git" + GIT_TERMINAL_PROMPT=0 git fetch --depth=1 origin "$CIRCLE_SHA1" + git checkout --detach FETCH_HEAD + - run: + name: Build and test in Release + command: >- + dotnet test src/ColorHashSharp.Tests/ColorHashSharp.Tests.csproj + --configuration Release + -p:TargetFrameworks=net<< parameters.dotnet-version >> + -p:GeneratePackageOnBuild=false + +workflows: + dotnet-tests: + jobs: + - test: + matrix: + parameters: + dotnet-version: ["10.0", "11.0"] diff --git a/.github/workflows/ci-dotnet.yml b/.github/workflows/ci-dotnet.yml new file mode 100644 index 0000000..9a4015c --- /dev/null +++ b/.github/workflows/ci-dotnet.yml @@ -0,0 +1,68 @@ +name: CI + +on: + push: + branches: [ main, develop ] + pull_request: + branches: [ main, develop ] + +permissions: + contents: read + +concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + build: + name: Build (${{ matrix.os }}, ${{ matrix.framework }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [windows-latest, ubuntu-latest] + framework: [net10.0, net11.0] + + steps: + - name: Checkout + uses: actions/checkout@v5 + + - name: Setup .NET SDKs + uses: actions/setup-dotnet@v5 + with: + dotnet-version: | + 10.0.x + 11.0.x + + - name: Restore library + run: dotnet restore src/ColorHashSharp/ColorHashSharp.csproj + + - name: Build library + run: dotnet build src/ColorHashSharp/ColorHashSharp.csproj --configuration Release --framework ${{ matrix.framework }} --no-restore + + test: + name: Test (${{ matrix.os }}, ${{ matrix.framework }}) + needs: build + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [windows-latest, ubuntu-latest] + framework: [net10.0, net11.0] + + steps: + - name: Checkout + uses: actions/checkout@v5 + + - name: Setup .NET SDKs + uses: actions/setup-dotnet@v5 + with: + dotnet-version: | + 10.0.x + 11.0.x + + - name: Restore tests + run: dotnet restore src/ColorHashSharp.Tests/ColorHashSharp.Tests.csproj + + - name: Test + run: dotnet test src/ColorHashSharp.Tests/ColorHashSharp.Tests.csproj --configuration Release --framework ${{ matrix.framework }} --no-restore --verbosity normal diff --git a/.github/workflows/dotnet-core.yml b/.github/workflows/dotnet-core.yml deleted file mode 100644 index e510cff..0000000 --- a/.github/workflows/dotnet-core.yml +++ /dev/null @@ -1,31 +0,0 @@ -name: CI - -on: - push: - branches: [ master, develop ] - pull_request: - branches: [ master, develop ] - -jobs: - build-and-test: - runs-on: windows-latest - strategy: - matrix: - test-framework: ['net9.0'] - #test-framework: [ 'net8.0', 'net9.0', 'net48', 'net481' ] - steps: - - uses: actions/checkout@v2 - - name: Setup .NET - uses: actions/setup-dotnet@v4 - with: - dotnet-version: - 9.0.x - - name: Install dependencies - working-directory: src - run: dotnet restore - - name: Build - working-directory: src - run: dotnet build --configuration Release --no-restore - - name: Test - working-directory: src - run: dotnet test --no-restore --verbosity normal --framework ${{ matrix.test-framework }} diff --git a/README.md b/README.md index 5b6f577..09f0ca5 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,21 @@ # ColorHashSharp Generate color based on the given string. C# port of [ColorHash Javascript Library](https://github.com/zenozeng/color-hash). -[![NuGet version (ColorHashSharp)](https://img.shields.io/nuget/v/ColorHashSharp.svg?style=flat-square)](https://www.nuget.org/packages/ColorHashSharp/)   [![NuGet Downloads](https://img.shields.io/nuget/dt/ColorHashSharp.svg)](https://www.nuget.org/packages/ColorHashSharp/)   [![CodeFactor](https://www.codefactor.io/repository/github/fernandezja/colorhashsharp/badge)](https://www.codefactor.io/repository/github/fernandezja/colorhashsharp) +[![NuGet version (ColorHashSharp)](https://img.shields.io/nuget/v/ColorHashSharp.svg?style=flat-square)](https://www.nuget.org/packages/ColorHashSharp/)   [![NuGet Downloads](https://img.shields.io/nuget/dt/ColorHashSharp.svg)](https://www.nuget.org/packages/ColorHashSharp/)   +[![CodeFactor](https://www.codefactor.io/repository/github/fernandezja/colorhashsharp/badge)](https://www.codefactor.io/repository/github/fernandezja/colorhashsharp) [![Codacy Badge](https://app.codacy.com/project/badge/Grade/7b256a3706a2434e9984dfb9f0d3da93)](https://app.codacy.com/gh/fernandezja/ColorHashSharp/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_grade) -[![CI](https://github.com/fernandezja/ColorHashSharp/actions/workflows/dotnet-core.yml/badge.svg)](https://github.com/fernandezja/ColorHashSharp/actions/workflows/dotnet-core.yml)  [![Build status](https://fernandezja.visualstudio.com/ColorHashSharp/_apis/build/status/ColorHashSharp-CI)](https://fernandezja.visualstudio.com/ColorHashSharp/_build/latest?definitionId=4) + +[![CI](https://github.com/fernandezja/ColorHashSharp/actions/workflows/ci-dotnet.yml/badge.svg)](https://github.com/fernandezja/ColorHashSharp/actions/workflows/ci-dotnet.yml)  [![Build status](https://fernandezja.visualstudio.com/ColorHashSharp/_apis/build/status/ColorHashSharp-CI)](https://fernandezja.visualstudio.com/ColorHashSharp/_build/latest?definitionId=4) #### Status -|Actions |master |develop | +|Actions |main |develop | |--- |--- |--- | -|CI |[![CI](https://github.com/fernandezja/ColorHashSharp/actions/workflows/dotnet-core.yml/badge.svg?branch=master)](https://github.com/fernandezja/ColorHashSharp/actions/workflows/dotnet-core.yml) |[![CI](https://github.com/fernandezja/ColorHashSharp/actions/workflows/dotnet-core.yml/badge.svg?branch=develop)](https://github.com/fernandezja/ColorHashSharp/actions/workflows/dotnet-core.yml) | +|CI |[![CI](https://github.com/fernandezja/ColorHashSharp/actions/workflows/ci-dotnet.yml/badge.svg?branch=main)](https://github.com/fernandezja/ColorHashSharp/actions/workflows/ci-dotnet.yml) |[![CI](https://github.com/fernandezja/ColorHashSharp/actions/workflows/ci-dotnet.yml/badge.svg?branch=develop)](https://github.com/fernandezja/ColorHashSharp/actions/workflows/ci-dotnet.yml) | #### Basic @@ -27,18 +29,56 @@ var colorHash = new ColorHash(); var hsl = colorHash.Hsl("Hello World"); Debug.WriteLine($" H = {hsl.H} | S = {hsl.S} | L = {hsl.L}"); -// H = 225 | S = 0,35 | L = 0,65 +// H = 233 | S = 0.5 | L = 0.65 //RGB (return System.Drawing.Color object) var color = colorHash.Rgb("Hello World"); Debug.WriteLine($" R= {color.R} | G = {color.G} | B = {color.B}"); -// R= 135 | G = 150 | B = 197 +// R = 121 | G = 132 | B = 210 //Hex (return string) var hex = colorHash.Hex("Hello World"); Debug.WriteLine($" hex = {hex}"); -// hex = 8796C5 +// hex = #7984d2 ``` + +#### Hash selection and migration to 2.0 + +The default hash uses the first four bytes of SHA-256 over UTF-8 as an unsigned +big-endian integer, matching the hash used by JavaScript color-hash 2.0.2. +`Options.UseJavaScriptCompatibility` defaults to `true` and matches +JavaScript's HSL calculation, RGB rounding, and `#rrggbb` format. Set it to +`false` to use the port's historical color calculation and `RRGGBB` format. + +```csharp +var javaScriptBkdr = new ColorHash(new Options { HashFunction = new JavaScriptBkdrHash() }); +var historical = new ColorHash(new Options +{ + UseJavaScriptCompatibility = false, + HashFunction = new BKDRHash() +}); +``` + +`JavaScriptBkdrHash` matches the JavaScript `hash: 'bkdr'` hash. Custom hashes +still use `IHashFunction`. In compatibility mode, their unsigned results +are converted to JavaScript-style double-precision numbers for color selection. +Use the historical configuration above with the same palettes and hue ranges +to reproduce historical ColorHashSharp colors. Applications upgrading from +NuGet 1.1.0 must recompile and update +`Options.S`, `Options.L`, and protected `GetLS` usage from `ArrayList` to +`List`. + +#### Options and null inputs in 2.0 + +`ColorHash` copies the saturation and lightness palettes and the hue bounds +at construction. To apply changes to `Options`, create a new `ColorHash` +instance. A custom hash instance is used as supplied. + +`S` and `L` require at least one finite value between 0 and 1, inclusive. +An empty `HueRanges` list uses the default hue calculation. Each range +requires `0 <= Min <= Max <= 360`. Invalid settings raise `ArgumentException` +at construction. A null input string is treated as empty, including when +passed to a custom hash. diff --git a/assets/icon/ColorHashSharp-ORIGINAL-1254x1254.png b/assets/icon/ColorHashSharp-ORIGINAL-1254x1254.png new file mode 100644 index 0000000..b1c64cf Binary files /dev/null and b/assets/icon/ColorHashSharp-ORIGINAL-1254x1254.png differ diff --git a/assets/icon/ColorHashSharp-icon.png b/assets/icon/ColorHashSharp-icon.png index a998d1b..d3f90ca 100644 Binary files a/assets/icon/ColorHashSharp-icon.png and b/assets/icon/ColorHashSharp-icon.png differ diff --git a/samples/CustomHashFunction.md b/samples/CustomHashFunction.md new file mode 100644 index 0000000..92a6711 --- /dev/null +++ b/samples/CustomHashFunction.md @@ -0,0 +1,105 @@ +# Custom Hash Function Example + +This example demonstrates how to use a custom hash function with ColorHashSharp. + +## Basic Usage with Custom Hash Function + +```csharp +using Fernandezja.ColorHashSharp; +using Fernandezja.ColorHashSharp.Interfaces; + +// 1. Create a custom hash function by implementing IHashFunction +public class SimpleCharCodeHash : IHashFunction +{ + public ulong Generate(string value) + { + if (string.IsNullOrEmpty(value)) + return 0; + + ulong hash = 0; + foreach (char c in value) + { + hash += (ulong)c; + } + return hash; + } +} + +// 2. Use the custom hash function +var customHash = new SimpleCharCodeHash(); +var options = new Options +{ + HashFunction = customHash +}; + +var colorHash = new ColorHash(options); + +// Generate colors using your custom hash +var hsl = colorHash.Hsl("Hello World"); +var rgb = colorHash.Rgb("Hello World"); +var hex = colorHash.Hex("Hello World"); + +Console.WriteLine($"HSL: H={hsl.H}, S={hsl.S}, L={hsl.L}"); +Console.WriteLine($"RGB: R={rgb.R}, G={rgb.G}, B={rgb.B}"); +Console.WriteLine($"Hex: {hex}"); +``` + +## Advanced Example: MD5-based Hash Function + +```csharp +using System.Security.Cryptography; +using System.Text; + +public class MD5HashFunction : IHashFunction +{ + public ulong Generate(string value) + { + using (var md5 = MD5.Create()) + { + byte[] hashBytes = md5.ComputeHash(Encoding.UTF8.GetBytes(value)); + + // Convert first 8 bytes to ulong + ulong hash = 0; + for (int i = 0; i < 8 && i < hashBytes.Length; i++) + { + hash |= ((ulong)hashBytes[i]) << (i * 8); + } + return hash; + } + } +} + +// Use MD5-based hash +var options = new Options +{ + HashFunction = new MD5HashFunction(), + L = new List { 0.5 }, + S = new List { 0.7 } +}; + +var colorHash = new ColorHash(options); +var color = colorHash.Hex("SecureString"); +``` + +## Why Use Custom Hash Functions? + +- **Consistency across platforms**: Use a specific hash that behaves identically everywhere +- **Security considerations**: Use cryptographic hashes for sensitive data +- **Domain-specific needs**: Implement hash functions optimized for your data patterns +- **Testing**: Create predictable hash functions for unit tests + +## Default Behavior + +ColorHashSharp uses SHA-256 by default. Set `Options.HashFunction` to select +another implementation. + +```csharp +var colorHash1 = new ColorHash(); +var colorHash2 = new ColorHash(new Options()); // Also uses SHA-256 +var javaScriptBkdr = new ColorHash(new Options { HashFunction = new JavaScriptBkdrHash() }); +var historical = new ColorHash(new Options +{ + UseJavaScriptCompatibility = false, + HashFunction = new BKDRHash() +}); +``` diff --git a/src/ColorHashSharp.Benchmarks/ColorHashSharp.Benchmarks.csproj b/src/ColorHashSharp.Benchmarks/ColorHashSharp.Benchmarks.csproj index ffaa1a7..f307655 100644 --- a/src/ColorHashSharp.Benchmarks/ColorHashSharp.Benchmarks.csproj +++ b/src/ColorHashSharp.Benchmarks/ColorHashSharp.Benchmarks.csproj @@ -2,13 +2,13 @@ Exe - net8.0;net9.0 + net10.0;net11.0 enable enable - + diff --git a/src/ColorHashSharp.Tests/BKDRHashTest.cs b/src/ColorHashSharp.Tests/BKDRHashTest.cs index 6be5c5b..892da24 100644 --- a/src/ColorHashSharp.Tests/BKDRHashTest.cs +++ b/src/ColorHashSharp.Tests/BKDRHashTest.cs @@ -56,5 +56,70 @@ public void Generate_HashWithSpaces(int spacesLength, ulong hashExpected) Assert.True(result > 0); Assert.Equal(hashExpected, result); } + + [Fact(DisplayName = "GenerateVersion2_ShouldGenerateHash")] + public void GenerateVersion2_ShouldGenerateHash() + { + var hash = new BKDRHash(); + var result = hash.GenerateVersion2("test"); + + Assert.True(result > 0); + } + + [Fact(DisplayName = "GenerateVersion2_DifferentStrings_ShouldGenerateDifferentHashes")] + public void GenerateVersion2_DifferentStrings_ShouldGenerateDifferentHashes() + { + var hash = new BKDRHash(); + var result1 = hash.GenerateVersion2("test1"); + var result2 = hash.GenerateVersion2("test2"); + + Assert.NotEqual(result1, result2); + } + + [Fact(DisplayName = "GenerateVersion3_ShouldGenerateHash")] + public void GenerateVersion3_ShouldGenerateHash() + { + var hash = new BKDRHash(); + var result = hash.GenerateVersion3("test"); + + Assert.True(result > 0); + } + + [Fact(DisplayName = "Generate_EmptyString_ShouldGenerateHash")] + public void Generate_EmptyString_ShouldGenerateHash() + { + var hash = new BKDRHash(); + var result = hash.Generate(""); + + Assert.True(result > 0); + } + + [Fact(DisplayName = "Generate_SpecialCharacters_ShouldGenerateHash")] + public void Generate_SpecialCharacters_ShouldGenerateHash() + { + var hash = new BKDRHash(); + var result = hash.Generate("!@#$%^&*()"); + + Assert.True(result > 0); + } + + [Fact(DisplayName = "Generate_UnicodeCharacters_ShouldGenerateHash")] + public void Generate_UnicodeCharacters_ShouldGenerateHash() + { + var hash = new BKDRHash(); + var result = hash.Generate("你好世界"); + + Assert.True(result > 0); + } + + [Fact(DisplayName = "Generate_LongString_ShouldGenerateHash")] + public void Generate_LongString_ShouldGenerateHash() + { + var hash = new BKDRHash(); + var longString = new string('a', 10000); + var result = hash.Generate(longString); + + Assert.True(result > 0); + } } } diff --git a/src/ColorHashSharp.Tests/ColorConversionEdgeCasesTest.cs b/src/ColorHashSharp.Tests/ColorConversionEdgeCasesTest.cs new file mode 100644 index 0000000..e28b645 --- /dev/null +++ b/src/ColorHashSharp.Tests/ColorConversionEdgeCasesTest.cs @@ -0,0 +1,209 @@ +using Fernandezja.ColorHashSharp; +using Fernandezja.ColorHashSharp.Entities; +using System.Drawing; +using Xunit; + +namespace ColorHashSharp.Tests +{ + public class ColorConversionEdgeCasesTest + { + #region HSL Edge Cases + + [Theory(DisplayName = "HsLtoRgb_VariousLightnessValues")] + [InlineData(0, 1, 0.0)] // Black + [InlineData(0, 1, 0.25)] + [InlineData(0, 1, 0.5)] + [InlineData(0, 1, 0.75)] + [InlineData(0, 1, 1.0)] // White + public void HsLtoRgb_VariousLightnessValues(double h, double s, double l) + { + var result = SimpleColorTransforms.HsLtoRgb(h, s, l); + + Assert.InRange(result.R, 0, 255); + Assert.InRange(result.G, 0, 255); + Assert.InRange(result.B, 0, 255); + } + + [Theory(DisplayName = "HsLtoRgb_VariousSaturationValues")] + [InlineData(120, 0.0, 0.5)] + [InlineData(120, 0.25, 0.5)] + [InlineData(120, 0.5, 0.5)] + [InlineData(120, 0.75, 0.5)] + [InlineData(120, 1.0, 0.5)] + public void HsLtoRgb_VariousSaturationValues(double h, double s, double l) + { + var result = SimpleColorTransforms.HsLtoRgb(h, s, l); + + Assert.InRange(result.R, 0, 255); + Assert.InRange(result.G, 0, 255); + Assert.InRange(result.B, 0, 255); + } + + [Theory(DisplayName = "HsLtoRgb_EdgeHueValues")] + [InlineData(-10, 1, 0.5)] // Negative, should clamp to 0 + [InlineData(370, 1, 0.5)] // Over 360, should clamp to 360 + public void HsLtoRgb_EdgeHueValues(double h, double s, double l) + { + var result = SimpleColorTransforms.HsLtoRgb(h, s, l); + + Assert.InRange(result.R, 0, 255); + Assert.InRange(result.G, 0, 255); + Assert.InRange(result.B, 0, 255); + } + + [Fact(DisplayName = "HsLtoRgb_LowLuminance_ShouldBeDark")] + public void HsLtoRgb_LowLuminance_ShouldBeDark() + { + var result = SimpleColorTransforms.HsLtoRgb(120, 1, 0.1); + + // Low luminance should produce dark colors + Assert.True(result.R < 100 && result.G < 100 && result.B < 100); + } + + [Fact(DisplayName = "HsLtoRgb_HighLuminance_ShouldBeBright")] + public void HsLtoRgb_HighLuminance_ShouldBeBright() + { + var result = SimpleColorTransforms.HsLtoRgb(120, 1, 0.9); + + // High luminance should produce bright colors + Assert.True(result.R > 150 || result.G > 150 || result.B > 150); + } + + #endregion + + #region HSB Edge Cases + + [Theory(DisplayName = "HsBtoRgb_VariousBrightnessValues")] + [InlineData(120, 1, 0.0)] + [InlineData(120, 1, 0.25)] + [InlineData(120, 1, 0.5)] + [InlineData(120, 1, 0.75)] + [InlineData(120, 1, 1.0)] + public void HsBtoRgb_VariousBrightnessValues(double h, double s, double b) + { + var result = SimpleColorTransforms.HsBtoRgb(h, s, b); + + Assert.InRange(result.R, 0, 255); + Assert.InRange(result.G, 0, 255); + Assert.InRange(result.B, 0, 255); + } + + [Theory(DisplayName = "HsBtoRgb_AllSectorsDetailed")] + [InlineData(15)] // Sector 0 (0-60) + [InlineData(45)] // Sector 0 + [InlineData(75)] // Sector 1 (60-120) + [InlineData(105)] // Sector 1 + [InlineData(135)] // Sector 2 (120-180) + [InlineData(165)] // Sector 2 + [InlineData(195)] // Sector 3 (180-240) + [InlineData(225)] // Sector 3 + [InlineData(255)] // Sector 4 (240-300) + [InlineData(285)] // Sector 4 + [InlineData(315)] // Sector 5 (300-360) + [InlineData(345)] // Sector 5 + public void HsBtoRgb_AllSectorsDetailed(double hue) + { + var result = SimpleColorTransforms.HsBtoRgb(hue, 1, 1); + + Assert.Equal(255, result.A); + Assert.InRange(result.R, 0, 255); + Assert.InRange(result.G, 0, 255); + Assert.InRange(result.B, 0, 255); + } + + #endregion + + #region Transform Edge Cases + + [Fact(DisplayName = "TransformBrightness_ExtremeIncrease")] + public void TransformBrightness_ExtremeIncrease() + { + var color = Color.FromArgb(50, 50, 50); + var result = SimpleColorTransforms.TransformBrightness( + color, + SimpleColorTransforms.ColorTransformMode.Hsl, + 5.0); + + Assert.NotEqual(color, result); + } + + [Fact(DisplayName = "TransformSaturationAndBrightness_ExtremeValues")] + public void TransformSaturationAndBrightness_ExtremeValues() + { + var color = Color.FromArgb(100, 150, 200); + var result = SimpleColorTransforms.TransformSaturationAndBrightness( + color, + SimpleColorTransforms.ColorTransformMode.Hsb, + 5.0, + 5.0); + + Assert.NotNull(result); + } + + #endregion + + #region RgBtoHsl Special Cases + + [Fact(DisplayName = "RgBtoHsl_MaxIsRed_GreenGreaterThanBlue")] + public void RgBtoHsl_MaxIsRed_GreenGreaterThanBlue() + { + var color = Color.FromArgb(255, 100, 50); + var result = SimpleColorTransforms.RgBtoHsl(color); + + Assert.InRange(result[0], 0, 360); + } + + [Fact(DisplayName = "RgBtoHsl_MaxIsRed_GreenLessThanBlue")] + public void RgBtoHsl_MaxIsRed_GreenLessThanBlue() + { + var color = Color.FromArgb(255, 50, 100); + var result = SimpleColorTransforms.RgBtoHsl(color); + + Assert.InRange(result[0], 0, 360); + } + + [Fact(DisplayName = "RgBtoHsl_LuminanceLowSaturationNonZero")] + public void RgBtoHsl_LuminanceLowSaturationNonZero() + { + var color = Color.FromArgb(30, 20, 10); + var result = SimpleColorTransforms.RgBtoHsl(color); + + Assert.InRange(result[1], 0, 1); // Saturation + Assert.InRange(result[2], 0, 0.5); // Low luminance + } + + [Fact(DisplayName = "RgBtoHsl_LuminanceHighSaturationNonZero")] + public void RgBtoHsl_LuminanceHighSaturationNonZero() + { + var color = Color.FromArgb(255, 200, 150); + var result = SimpleColorTransforms.RgBtoHsl(color); + + Assert.InRange(result[1], 0, 1); // Saturation + Assert.InRange(result[2], 0.5, 1); // High luminance + } + + #endregion + + #region RgBtoHsb Special Cases + + [Fact(DisplayName = "RgBtoHsb_MaxIsRed_GreenGreaterThanBlue")] + public void RgBtoHsb_MaxIsRed_GreenGreaterThanBlue() + { + var color = Color.FromArgb(255, 100, 50); + var result = SimpleColorTransforms.RgBtoHsb(color); + + Assert.InRange(result[0], 0, 60); // Hue in first sector + } + + [Fact(DisplayName = "RgBtoHsb_MaxIsRed_GreenLessThanBlue")] + public void RgBtoHsb_MaxIsRed_GreenLessThanBlue() + { + var color = Color.FromArgb(255, 50, 100); + var result = SimpleColorTransforms.RgBtoHsb(color); + + Assert.InRange(result[0], 300, 360); // Hue wraps around + } + + #endregion + } +} diff --git a/src/ColorHashSharp.Tests/ColorHashOptionsTest.cs b/src/ColorHashSharp.Tests/ColorHashOptionsTest.cs new file mode 100644 index 0000000..33ca32e --- /dev/null +++ b/src/ColorHashSharp.Tests/ColorHashOptionsTest.cs @@ -0,0 +1,161 @@ +using System; +using System.Collections.Generic; +using Fernandezja.ColorHashSharp; +using Fernandezja.ColorHashSharp.Entities; +using Fernandezja.ColorHashSharp.Interfaces; +using Xunit; + +namespace ColorHashSharp.Tests +{ + public class ColorHashOptionsTest + { + [Fact] + public void Constructor_RejectsNullOptions() + { + Assert.Throws("options", () => new ColorHash(null)); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void Constructor_RejectsMissingOrEmptyPalettes(bool saturation) + { + AssertInvalidPalette(saturation, null); + AssertInvalidPalette(saturation, new List()); + } + + [Theory] + [InlineData(-0.01)] + [InlineData(1.01)] + [InlineData(double.NaN)] + [InlineData(double.NegativeInfinity)] + [InlineData(double.PositiveInfinity)] + public void Constructor_RejectsInvalidPaletteEntries(double value) + { + var palette = new List { 0.5, value }; + + AssertInvalidPalette(true, palette); + AssertInvalidPalette(false, palette); + } + + [Fact] + public void Constructor_RejectsNullHueListAndEntries() + { + var missing = Assert.Throws("options", + () => new ColorHash(new Options { HueRanges = null })); + var withNull = Assert.Throws("options", + () => new ColorHash(new Options { HueRanges = new List { new Hue(), null } })); + + Assert.Contains("HueRanges", missing.Message); + Assert.Contains("HueRanges[1]", withNull.Message); + } + + [Theory] + [InlineData(-1, 90)] + [InlineData(180, 90)] + [InlineData(0, 361)] + public void Constructor_RejectsInvalidHueBounds(int min, int max) + { + var options = new Options { HueRanges = new List { new Hue(), new Hue(min, max) } }; + + var error = Assert.Throws("options", () => new ColorHash(options)); + + Assert.Contains("HueRanges[1]", error.Message); + } + + [Theory] + [InlineData(0, 0, 0, "#000000")] + [InlineData(90, 1, 1, "#ffffff")] + [InlineData(360, 1, 0.5, "#ff0000")] + public void Constructor_AcceptsPaletteEndpointsAndFixedHues( + int hue, double saturation, double lightness, string expectedHex) + { + var options = new Options + { + S = new List { saturation }, + L = new List { lightness }, + HueRanges = new List { new Hue(hue, hue) } + }; + var generator = new ColorHash(options); + + var hsl = generator.Hsl("test"); + + Assert.Equal(((double)hue, saturation, lightness), (hsl.H, hsl.S, hsl.L)); + Assert.Equal(expectedHex, generator.Hex("test")); + } + + [Fact] + public void Constructor_CopiesPalettesAndHueBounds() + { + var range = new Hue(90, 90); + var options = new Options + { + S = new List { 0.35 }, + L = new List { 0.65 }, + HueRanges = new List { range } + }; + var original = new ColorHash(options); + + options.S[0] = 0.5; + options.L[0] = 0.35; + range.Min = 180; + range.Max = 180; + + var before = original.Hsl("test"); + var updated = new ColorHash(options).Hsl("test"); + + Assert.Equal((90.0, 0.35, 0.65), (before.H, before.S, before.L)); + Assert.Equal((180.0, 0.5, 0.35), (updated.H, updated.S, updated.L)); + + options.S.Clear(); + options.L.Clear(); + options.HueRanges.Clear(); + + var after = original.Hsl("test"); + Assert.Equal((before.H, before.S, before.L), (after.H, after.S, after.L)); + } + + [Fact] + public void NullInput_IsPassedToTheSelectedHashAsAnEmptyString() + { + var defaultGenerator = new ColorHash(); + var customHash = new RecordingHash(); + var customGenerator = new ColorHash(new Options { HashFunction = customHash }); + + Assert.Equal(defaultGenerator.Hex(string.Empty), defaultGenerator.Hex(null)); + + customGenerator.Hex(null); + Assert.Equal(string.Empty, customHash.LastInput); + + customGenerator.Hex("test"); + Assert.Equal("test", customHash.LastInput); + } + + private static void AssertInvalidPalette(bool saturation, List palette) + { + var options = new Options(); + if (saturation) + { + options.S = palette; + } + else + { + options.L = palette; + } + + var error = Assert.Throws("options", () => new ColorHash(options)); + Assert.StartsWith(saturation ? nameof(Options.S) : nameof(Options.L), error.Message); + } + + private sealed class RecordingHash : IHashFunction + { + public string LastInput { get; private set; } + + public ulong Generate(string value) + { + LastInput = value; + return 0; + } + } + } +} diff --git a/src/ColorHashSharp.Tests/ColorHashSharp.Tests.csproj b/src/ColorHashSharp.Tests/ColorHashSharp.Tests.csproj index 51e27a4..3337f98 100644 --- a/src/ColorHashSharp.Tests/ColorHashSharp.Tests.csproj +++ b/src/ColorHashSharp.Tests/ColorHashSharp.Tests.csproj @@ -1,18 +1,18 @@  - net9.0 + net10.0;net11.0 false - + all runtime; build; native; contentfiles; analyzers; buildtransitive - + - + all runtime; build; native; contentfiles; analyzers diff --git a/src/ColorHashSharp.Tests/ColorHashTest.cs b/src/ColorHashSharp.Tests/ColorHashTest.cs index 914c9d4..d42ecd2 100644 --- a/src/ColorHashSharp.Tests/ColorHashTest.cs +++ b/src/ColorHashSharp.Tests/ColorHashTest.cs @@ -1,195 +1,98 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Drawing; -using System.Text; +using System.Collections.Generic; +using System.Linq; using Fernandezja.ColorHashSharp; +using Fernandezja.ColorHashSharp.Entities; using Xunit; namespace ColorHashSharp.Tests { + // Behavioral cases from color-hash 2.0.2's color-hash.test.ts. public class ColorHashTest { - [Fact(DisplayName = "BuildToHsl_ShouldCreateAColorWithTextYodaInHSL")] - public void BuildToHsl_ShouldCreateAColorWithHSL() - { - var colorHash = new Fernandezja.ColorHashSharp.ColorHash(); - - var result = colorHash.BuildToHsl("yoda"); - - Assert.NotNull(result); - Assert.Equal(76, result.H); - Assert.Equal(0.35, result.S); - Assert.Equal(0.35, result.L); - } + private static readonly string[] Inputs = Enumerable.Range(0, 100) + .Select(index => $"00000000-0000-4000-8000-{index:D12}") + .ToArray(); - - - [Theory(DisplayName = "BuildToHsl_ShouldCreateAColorInHSL")] - [InlineData("yoda", 76, 0.35, 0.35)] - [InlineData("Yoda", 314, 0.5, 0.65)] - [InlineData("starwars", 339, 0.35, 0.5)] - [InlineData("StarWars", 135, 0.5, 0.35)] - public void BuildToHsl_ShouldCreateAColorInHSL( - string phrase, double hExpected, double sExpected, double lExpected) + [Fact] + public void Hsl_DefaultHueIsBelow359() { - var colorHash = new Fernandezja.ColorHashSharp.ColorHash(); - - var result = colorHash.BuildToHsl(phrase); + var colorHash = new ColorHash(); - Assert.NotNull(result); - Assert.Equal(hExpected, result.H); - Assert.Equal(sExpected, result.S); - Assert.Equal(lExpected, result.L); + foreach (var input in Inputs) + { + Assert.InRange(colorHash.Hsl(input).H, 0, 358); + } } - - [Theory(DisplayName = "BuildToHsl_ShouldCreateAColorInHSLWithCustomHueOption")] - [InlineData("yoda", 90, 90, 0.35, 0.35)] - [InlineData("yoda", 270, 270, 0.35, 0.35)] - public void BuildToHsl_ShouldCreateAColorInHSLWithCustomHueOption( - string phrase, int hue, - int hExpected, double sExpected, double lExpected) + [Fact] + public void Hsl_UsesFixedHue() { - var options = new Options(); - options.SetHue(hue); - - var colorHash = new Fernandezja.ColorHashSharp.ColorHash(options); - - var result = colorHash.BuildToHsl(phrase); + var colorHash = new ColorHash(new Options { HueRanges = new List { new Hue(10, 10) } }); - Assert.NotNull(result); - Assert.Equal(hExpected, result.H); - Assert.Equal(sExpected, result.S); - Assert.Equal(lExpected, result.L); - - + foreach (var input in Inputs) + { + Assert.Equal(10, colorHash.Hsl(input).H); + } } - - - [Theory(DisplayName = "BuildToHsl_ShouldCreateAColorInHexWithCustomHueOption")] - [InlineData("yoda", 90, "59783A")] - [InlineData("yoda", 210, "3A5978")] - [InlineData("yoda", 270, "593A78")] - [InlineData("yoda", 360, "783A3A")] - public void BuildToHsl_ShouldCreateAColorInHexWithCustomHueOption( - string phrase, int hue, string hexExpected) + [Fact] + public void Hsl_UsesSingleHueRange() { - var options = new Options(); - options.SetHue(hue); - - var colorHash = new Fernandezja.ColorHashSharp.ColorHash(options); - - var result = colorHash.BuildToHex(phrase); - - Assert.NotNull(result); - - Assert.Equal(hexExpected, result); - - + for (int min = 0; min < 360; min += 60) + { + for (int max = min + 1; max <= 360; max += 60) + { + var colorHash = new ColorHash(new Options { HueRanges = new List { new Hue(min, max) } }); + + foreach (var input in Inputs) + { + double hue = colorHash.Hsl(input).H; + Assert.True(hue >= min && hue < max, $"Hue {hue} is outside [{min}, {max})."); + } + } + } } - [Theory(DisplayName = "BuildToHex_ShouldCreateAColorInHex")] - [InlineData("yoda", "68783A")] - [InlineData("Yoda", "D279BE")] - [InlineData("starwars", "AC5372")] - [InlineData("StarWars", "2D8643")] - public void BuildToHex_ShouldCreateAColorInHex(string phrase, string hexExpected) + [Fact] + public void Hsl_UsesOneOfTheHueRanges() { - var colorHash = new Fernandezja.ColorHashSharp.ColorHash(); - - var result = colorHash.BuildToHex(phrase); - - Assert.NotNull(result); - Assert.Equal(hexExpected, result); - } - - [Fact(DisplayName = "BuildToColor_ShouldCreateAColorObject")] - public void BuildToColor_ShouldCreateAColorObject() - { - var colorHash = new Fernandezja.ColorHashSharp.ColorHash(); - - var result = colorHash.BuildToColor("yoda"); - - Assert.Equal(Color.FromArgb(alpha:255,red:104,green:120, blue:58), - result); + var ranges = new List { new Hue(30, 90), new Hue(180, 210), new Hue(270, 285) }; + var colorHash = new ColorHash(new Options { HueRanges = ranges }); + + foreach (var input in Inputs) + { + double hue = colorHash.Hsl(input).H; + Assert.Contains(ranges, range => hue >= range.Min && hue < range.Max); + } } - [Fact(DisplayName = "BuildToHsl_HelloWorldString")] - public void BuildToHsl_HelloWorldString() + [Fact] + public void Hsl_UsesFixedSaturationAndLightness() { - var colorHash = new Fernandezja.ColorHashSharp.ColorHash(); + var colorHash = new ColorHash(new Options + { + S = new List { 0.5 }, + L = new List { 0.5 } + }); - var result = colorHash.BuildToHsl("Hello World"); + var hsl = colorHash.Hsl(Inputs[0]); - Assert.NotNull(result); - Assert.Equal(225, result.H); - Assert.Equal(0.35, result.S); - Assert.Equal(0.65, result.L); + Assert.Equal((0.5, 0.5), (hsl.S, hsl.L)); } - [Fact(DisplayName = "Build_HelloWorldStringToHslColorAndHex")] - public void Build_HelloWorldStringToHslColorAndHex() + [Fact] + public void Hsl_UsesConfiguredSaturationAndLightnessPalettes() { - var ColorHash = new Fernandezja.ColorHashSharp.ColorHash(); + var colorHash = new ColorHash(new Options + { + S = new List { 0.9, 1 }, + L = new List { 0.9, 1 } + }); - var resultHsl = ColorHash.BuildToHsl("Hello World"); - var resultColor = ColorHash.BuildToColor("Hello World"); - var resultHex = ColorHash.BuildToHex("Hello World"); + var hsl = colorHash.Hsl(Inputs[0]); - Assert.Equal(135, resultColor.R); - Assert.Equal(150, resultColor.G); - Assert.Equal(197, resultColor.B); - - Assert.Equal(225, resultHsl.H); - Assert.Equal(0.35, resultHsl.S); - Assert.Equal(0.65, resultHsl.L); - - Assert.Equal("8796C5", resultHex); - - - } - - [Fact(DisplayName = "Hsl_ShouldCreateAColorInHSL")] - public void Hsl_ShouldCreateAColorInHSL() - { - var colorHash = new Fernandezja.ColorHashSharp.ColorHash(); - - var result = colorHash.Hsl("Hello World"); - - Assert.NotNull(result); - Assert.Equal(225, result.H); - Assert.Equal(0.35, result.S); - Assert.Equal(0.65, result.L); - } - - - - [Fact(DisplayName = "Hex_ShouldCreateAColorInHex")] - public void Hex_ShouldCreateAColorInHex() - { - var colorHash = new Fernandezja.ColorHashSharp.ColorHash(); - - var result = colorHash.BuildToHex("Hello World"); - - Assert.NotNull(result); - Assert.Equal("8796C5", result); - } - - - [Fact(DisplayName = "Rgb_ShouldCreateAColorInRgb")] - public void Rgb_ShouldCreateAColorInRgb() - { - var colorHash = new Fernandezja.ColorHashSharp.ColorHash(); - - var result = colorHash.Rgb("Hello World"); - - Assert.Equal(135, result.R); - Assert.Equal(150, result.G); - Assert.Equal(197, result.B); + Assert.Contains(hsl.S, new[] { 0.9, 1 }); + Assert.Contains(hsl.L, new[] { 0.9, 1 }); } - - } } diff --git a/src/ColorHashSharp.Tests/ColorToHexTest.cs b/src/ColorHashSharp.Tests/ColorToHexTest.cs new file mode 100644 index 0000000..1c56aa1 --- /dev/null +++ b/src/ColorHashSharp.Tests/ColorToHexTest.cs @@ -0,0 +1,96 @@ +using Fernandezja.ColorHashSharp; +using System.Drawing; +using Xunit; + +namespace ColorHashSharp.Tests +{ + public class ColorToHexTest + { + [Theory] + [InlineData(255, 64, 0, "#ff4000")] + [InlineData(1, 15, 16, "#010f10")] + public void BuildToHex_CssFormatMatchesUpstream(int red, int green, int blue, string expected) + { + var converter = new ColorToHex(); + + Assert.Equal(expected, converter.BuildToHex(Color.FromArgb(red, green, blue), cssFormat: true)); + } + + [Fact(DisplayName = "BuildToHex_RedColor_ShouldReturnFF0000")] + public void BuildToHex_RedColor_ShouldReturnFF0000() + { + var colorToHex = new ColorToHex(); + var color = Color.FromArgb(255, 0, 0); + + var result = colorToHex.BuildToHex(color); + + Assert.Equal("FF0000", result); + } + + [Fact(DisplayName = "BuildToHex_GreenColor_ShouldReturn00FF00")] + public void BuildToHex_GreenColor_ShouldReturn00FF00() + { + var colorToHex = new ColorToHex(); + var color = Color.FromArgb(0, 255, 0); + + var result = colorToHex.BuildToHex(color); + + Assert.Equal("00FF00", result); + } + + [Fact(DisplayName = "BuildToHex_BlueColor_ShouldReturn0000FF")] + public void BuildToHex_BlueColor_ShouldReturn0000FF() + { + var colorToHex = new ColorToHex(); + var color = Color.FromArgb(0, 0, 255); + + var result = colorToHex.BuildToHex(color); + + Assert.Equal("0000FF", result); + } + + [Fact(DisplayName = "BuildToHex_BlackColor_ShouldReturn000000")] + public void BuildToHex_BlackColor_ShouldReturn000000() + { + var colorToHex = new ColorToHex(); + var color = Color.FromArgb(0, 0, 0); + + var result = colorToHex.BuildToHex(color); + + Assert.Equal("000000", result); + } + + [Fact(DisplayName = "BuildToHex_WhiteColor_ShouldReturnFFFFFF")] + public void BuildToHex_WhiteColor_ShouldReturnFFFFFF() + { + var colorToHex = new ColorToHex(); + var color = Color.FromArgb(255, 255, 255); + + var result = colorToHex.BuildToHex(color); + + Assert.Equal("FFFFFF", result); + } + + [Fact(DisplayName = "BuildToHex_CustomColor_ShouldReturnCorrectHex")] + public void BuildToHex_CustomColor_ShouldReturnCorrectHex() + { + var colorToHex = new ColorToHex(); + var color = Color.FromArgb(135, 150, 197); + + var result = colorToHex.BuildToHex(color); + + Assert.Equal("8796C5", result); + } + + [Fact(DisplayName = "BuildToHex_LowValues_ShouldPadWithZeros")] + public void BuildToHex_LowValues_ShouldPadWithZeros() + { + var colorToHex = new ColorToHex(); + var color = Color.FromArgb(1, 15, 16); + + var result = colorToHex.BuildToHex(color); + + Assert.Equal("010F10", result); + } + } +} diff --git a/src/ColorHashSharp.Tests/ColorToRgbTest.cs b/src/ColorHashSharp.Tests/ColorToRgbTest.cs index 9c0f0cd..e219025 100644 --- a/src/ColorHashSharp.Tests/ColorToRgbTest.cs +++ b/src/ColorHashSharp.Tests/ColorToRgbTest.cs @@ -1,6 +1,8 @@ using Fernandezja.ColorHashSharp; +using Fernandezja.ColorHashSharp.Entities; using System; using System.Collections.Generic; +using System.Drawing; using System.Text; using Xunit; @@ -8,18 +10,115 @@ namespace ColorHashSharp.Tests { public class ColorToRgbTest { + [Theory] + [InlineData(0, 1, 0.5, 255, 0, 0)] + [InlineData(120, 1, 0.75, 128, 255, 128)] + [InlineData(240, 1, 0.25, 0, 0, 128)] + [InlineData(330, 1, 0.75, 255, 128, 191)] + public void ToRgb_JavaScriptRoundingMatchesUpstream( + double hue, double saturation, double lightness, int red, int green, int blue) + { + var result = ColorToRgb.ToRgb(hue, saturation, lightness, MidpointRounding.AwayFromZero); + + Assert.Equal(Color.FromArgb(red, green, blue), result); + } [Fact(DisplayName = "ToRgb_HslToRgb")] public void ToRgb_HslToRgb() { - //HSL from ""Hello World" 255, 0.35, 0.65 - //double hue, double saturation, double lightness var result = ColorToRgb.ToRgb(225, 0.35, 0.65); Assert.Equal(135, result.R); Assert.Equal(150, result.G); Assert.Equal(197, result.B); + } + + [Fact(DisplayName = "ToRgb_WithHslObject_ShouldConvert")] + public void ToRgb_WithHslObject_ShouldConvert() + { + var colorToRgb = new ColorToRgb(); + var hsl = new Hsl(225, 0.35, 0.65); + + var result = colorToRgb.ToRgb(hsl); + + Assert.Equal(135, result.R); + Assert.Equal(150, result.G); + Assert.Equal(197, result.B); + } + + [Fact(DisplayName = "ToRgb1_Method_ShouldConvertHslToRgb")] + public void ToRgb1_Method_ShouldConvertHslToRgb() + { + var result = ColorToRgb.ToRgb1(0, 1, 0.5); + + // ToRgb1 uses HSV algorithm, not HSL + Assert.Equal(128, result.R); + Assert.Equal(0, result.G); + Assert.Equal(0, result.B); + } + + [Fact(DisplayName = "ToRgb1_BlueColor_ShouldConvert")] + public void ToRgb1_BlueColor_ShouldConvert() + { + var result = ColorToRgb.ToRgb1(240, 1, 0.5); + + Assert.Equal(0, result.R); + Assert.Equal(0, result.G); + Assert.Equal(128, result.B); + } + + [Fact(DisplayName = "ToRgb1_GreenColor_ShouldConvert")] + public void ToRgb1_GreenColor_ShouldConvert() + { + var result = ColorToRgb.ToRgb1(120, 1, 0.5); + + Assert.Equal(0, result.R); + Assert.Equal(128, result.G); + Assert.Equal(0, result.B); + } + + [Theory(DisplayName = "ToRgb1_AllSectors_ShouldConvert")] + [InlineData(0)] // hi = 0 + [InlineData(60)] // hi = 1 + [InlineData(120)] // hi = 2 + [InlineData(180)] // hi = 3 + [InlineData(240)] // hi = 4 + [InlineData(300)] // hi = 5 + public void ToRgb1_AllSectors_ShouldConvert(double hue) + { + var result = ColorToRgb.ToRgb1(hue, 1, 0.5); + + Assert.NotNull(result); + Assert.Equal(255, result.A); + } + + [Fact(DisplayName = "ToRgb2_RedColor_ShouldConvert")] + public void ToRgb2_RedColor_ShouldConvert() + { + var result = ColorToRgb.ToRgb2(0, 1, 0.5); + + Assert.Equal(255, result.A); + Assert.Equal(255, result.R); + } + + [Fact(DisplayName = "ToRgb2_BlackColor_ShouldConvert")] + public void ToRgb2_BlackColor_ShouldConvert() + { + var result = ColorToRgb.ToRgb2(0, 0, 0); + + Assert.Equal(0, result.R); + Assert.Equal(0, result.G); + Assert.Equal(0, result.B); + } + + [Fact(DisplayName = "ToRgb2_WhiteColor_ShouldConvert")] + public void ToRgb2_WhiteColor_ShouldConvert() + { + var result = ColorToRgb.ToRgb2(0, 0, 1); + Assert.Equal(255, result.R); + Assert.Equal(255, result.G); + Assert.Equal(255, result.B); } } } diff --git a/src/ColorHashSharp.Tests/CustomHashFunctionTest.cs b/src/ColorHashSharp.Tests/CustomHashFunctionTest.cs new file mode 100644 index 0000000..8ef4d27 --- /dev/null +++ b/src/ColorHashSharp.Tests/CustomHashFunctionTest.cs @@ -0,0 +1,39 @@ +using Fernandezja.ColorHashSharp; +using Fernandezja.ColorHashSharp.Interfaces; +using Xunit; + +namespace ColorHashSharp.Tests +{ + public class CustomHashFunctionTest + { + [Theory] + [InlineData("abc", 294, 0.5, 0.5, 178, 64, 191, "#b240bf")] + [InlineData("Hello World", 334, 0.35, 0.5, 172, 83, 122, "#ac537a")] + public void CustomCharCodeHash_MatchesUpstream( + string input, double h, double s, double l, int red, int green, int blue, string hex) + { + var colorHash = new ColorHash(new Options { HashFunction = new CharCodeHash() }); + + var hsl = colorHash.Hsl(input); + var rgb = colorHash.Rgb(input); + + Assert.Equal((h, s, l), (hsl.H, hsl.S, hsl.L)); + Assert.Equal((red, green, blue), ((int)rgb.R, (int)rgb.G, (int)rgb.B)); + Assert.Equal(hex, colorHash.Hex(input)); + } + + private sealed class CharCodeHash : IHashFunction + { + public ulong Generate(string value) + { + ulong hash = 0; + foreach (char codeUnit in value) + { + hash += codeUnit; + } + + return hash; + } + } + } +} diff --git a/src/ColorHashSharp.Tests/HashContractTest.cs b/src/ColorHashSharp.Tests/HashContractTest.cs new file mode 100644 index 0000000..22deef6 --- /dev/null +++ b/src/ColorHashSharp.Tests/HashContractTest.cs @@ -0,0 +1,240 @@ +using System.Collections.Generic; +using System.Linq; +using Fernandezja.ColorHashSharp; +using Fernandezja.ColorHashSharp.Entities; +using Fernandezja.ColorHashSharp.Interfaces; +using Xunit; + +namespace ColorHashSharp.Tests +{ + public class HashContractTest + { + // Raw hash values from color-hash 2.0.2. + [Theory] + [InlineData("Hello World", 2777786068UL, 294020464607729UL)] + [InlineData("é", 1251562878UL, 30643UL)] + [InlineData("😀", 4031003188UL, 957426589UL)] + [InlineData("", 3820012610UL, 120UL)] + [InlineData("\0", 1848904604UL, 120UL)] + public void HashFunctions_MatchJavaScript(string input, ulong sha256, ulong bkdr) + { + Assert.Equal(sha256, new Sha256Hash().Generate(input)); + Assert.Equal(bkdr, new JavaScriptBkdrHash().Generate(input)); + } + + [Theory] + [InlineData("2018-06-14T17", 2080245275UL, "2018-06-15T09", 1833461466UL)] + [InlineData("myView1", 170744141UL, "myView2", 551785129UL)] + public void Sha256_MatchesUpstreamCollisionRegressionCases( + string first, ulong firstHash, string second, ulong secondHash) + { + var hash = new Sha256Hash(); + + Assert.Equal(firstHash, hash.Generate(first)); + Assert.Equal(secondHash, hash.Generate(second)); + } + + [Fact] + public void JavaScriptBkdr_MatchesUpstreamShortAndLongInputs() + { + var hash = new JavaScriptBkdrHash(); + string longInput = string.Concat(Enumerable.Repeat("Hello World.", 10000)); + + Assert.Equal(219759694UL, hash.Generate("abc")); + Assert.Equal(235617375UL, hash.Generate("hij")); + Assert.Equal(117111301690285UL, hash.Generate(longInput)); + Assert.Equal(122475178103641UL, hash.Generate(longInput.Substring(0, longInput.Length - 1))); + } + + [Fact] + public void Sha256_MatchesJavaScriptForUnpairedSurrogates() + { + var hash = new Sha256Hash(); + + Assert.Equal(824408855UL, hash.Generate("\uD800")); + Assert.Equal(3879378172UL, hash.Generate("\uDC00A")); + } + + [Fact] + public void Sha256_PreservesNullAsEmpty() + { + Assert.Equal(3820012610UL, new Sha256Hash().Generate(null)); + } + + [Theory] + [InlineData("Hello World", 233, 0.35, 0.5, 83, 93, 172, "535DAC")] + [InlineData("é", 205, 0.5, 0.65, 121, 173, 210, "79ADD2")] + [InlineData("😀", 49, 0.5, 0.65, 210, 194, 121, "D2C279")] + [InlineData("", 233, 0.65, 0.35, 31, 45, 147, "1F2D93")] + public void CompatibilityDisabled_PreservesPortColorsWithSha256( + string input, double h, double s, double l, int r, int g, int b, string hex) + { + var port = new ColorHash(new Options { UseJavaScriptCompatibility = false }); + AssertColor(port, input, (h, s, l), (r, g, b), hex); + } + + [Fact] + public void LongInput_HasStableHashesAndHistoricalColor() + { + var input = new string('a', 10000); + + Assert.Equal(668802913UL, new Sha256Hash().Generate(input)); + Assert.Equal(574486312506502UL, new JavaScriptBkdrHash().Generate(input)); + Assert.Equal(574486312470084UL, new BKDRHash().Generate(input)); + var port = new ColorHash(new Options { UseJavaScriptCompatibility = false }); + AssertColor(port, input, (273, 0.65, 0.5), (136, 45, 210), "882DD2"); + } + + [Fact] + public void CompatibilityDisabled_PreservesIntegerHueInterpolation() + { + var options = new Options + { + UseJavaScriptCompatibility = false, + HueRanges = new List { new Hue(90, 91), new Hue(210, 211) } + }; + + AssertColor(new ColorHash(options), "Hello World", (90, 0.35, 0.5), (128, 172, 83), "80AC53"); + } + + [Theory] + [InlineData("Hello World", 225, 0.35, 0.65, 135, 150, 197, "8796C5")] + [InlineData("é", 157, 0.35, 0.65, 135, 197, 173, "87C5AD")] + [InlineData("😀", 224, 0.65, 0.35, 31, 62, 147, "1F3E93")] + [InlineData("", 120, 0.35, 0.35, 58, 120, 58, "3A783A")] + public void HistoricalBkdr_PreservesPortColors( + string input, double h, double s, double l, int r, int g, int b, string hex) + { + var colorHash = new ColorHash(new Options + { + UseJavaScriptCompatibility = false, + HashFunction = new BKDRHash() + }); + + AssertColor(colorHash, input, (h, s, l), (r, g, b), hex); + } + + // Color vectors from the published color-hash 2.0.2 npm package. + [Theory] + [InlineData("Hello World", 233, 0.5, 0.65, 121, 132, 210, "#7984d2")] + [InlineData("é", 205, 0.65, 0.35, 31, 99, 147, "#1f6393")] + [InlineData("😀", 49, 0.65, 0.35, 147, 126, 31, "#937e1f")] + [InlineData("", 233, 0.35, 0.5, 83, 93, 172, "#535dac")] + public void DefaultColors_MatchUpstream( + string input, double h, double s, double l, int r, int g, int b, string hex) + { + var colorHash = new ColorHash(); + + AssertColor(colorHash, input, (h, s, l), (r, g, b), hex); + var hsl = colorHash.BuildToHsl(input); + Assert.Equal((h, s, l), (hsl.H, hsl.S, hsl.L)); + Assert.Equal(colorHash.Rgb(input), colorHash.BuildToColor(input)); + Assert.Equal(hex, colorHash.BuildToHex(input)); + Assert.Equal(hex, colorHash.Build(input)); + } + + [Fact] + public void DefaultOptions_MatchUpstream() + { + var options = new Options(); + + Assert.True(options.UseJavaScriptCompatibility); + Assert.Equal("#7984d2", new ColorHash(options).Hex("Hello World")); + } + + [Fact] + public void JavaScriptMode_MatchesUpstreamForLongInputs() + { + var input = new string('a', 10000); + var sha256 = new ColorHash(); + var bkdr = new ColorHash(new Options { HashFunction = new JavaScriptBkdrHash() }); + + AssertColor(sha256, input, (273, 0.35, 0.65), (169, 135, 197), "#a987c5"); + AssertColor(bkdr, input, (71, 0.65, 0.35), (126, 147, 31), "#7e931f"); + } + + [Fact] + public void JavaScriptMode_MatchesUpstreamBkdrForUnicode() + { + var colorHash = new ColorHash(new Options + { + HashFunction = new JavaScriptBkdrHash() + }); + + AssertColor(colorHash, "é", (128, 0.65, 0.65), (108, 224, 123), "#6ce07b"); + AssertColor(colorHash, "😀", (155, 0.5, 0.5), (64, 191, 138), "#40bf8a"); + } + + [Fact] + public void JavaScriptMode_InterpolatesHueWithFractionalDivision() + { + var colorHash = new ColorHash(new Options + { + HashFunction = new FixedHash(3), + HueRanges = new List { new Hue(0, 1), new Hue(10, 11) } + }); + + AssertColor(colorHash, "custom", (10.002063273727648, 0.5, 0.5), (191, 85, 64), "#bf5540"); + } + + [Theory] + [InlineData(0UL, 0, 0.1, 0.2, 56, 46, 46, "#382e2e")] + [InlineData(1UL, 1, 0.4, 0.5, 179, 78, 77, "#b34e4d")] + [InlineData(360UL, 1, 0.4, 0.5, 179, 78, 77, "#b34e4d")] + [InlineData(361UL, 2, 0.9, 0.5, 242, 20, 13, "#f2140d")] + [InlineData(1080UL, 3, 0.1, 0.5, 140, 116, 115, "#8c7473")] + [InlineData(1081UL, 4, 0.4, 0.7, 209, 152, 148, "#d19894")] + [InlineData(ulong.MaxValue, 303, 0.1, 0.2, 56, 46, 56, "#382e38")] + public void JavaScriptMode_RoundsUpBothPaletteDivisions( + ulong hash, double h, double s, double l, int r, int g, int b, string hex) + { + var colorHash = new ColorHash(new Options + { + HashFunction = new FixedHash(hash), + S = new List { 0.1, 0.4, 0.9 }, + L = new List { 0.2, 0.5, 0.7, 0.8 } + }); + + AssertColor(colorHash, "custom", (h, s, l), (r, g, b), hex); + } + + [Theory] + [InlineData(76.5 / 255, 77, "#4d4d4d", "4C4C4C")] + [InlineData(1.0 / 255, 1, "#010101", "010101")] + public void JavaScriptMode_UsesJavaScriptRoundingAndCssHex( + double lightness, int channel, string cssHex, string portHex) + { + var options = new Options { S = new List { 0 }, L = new List { lightness } }; + var javaScript = new ColorHash(options); + options.UseJavaScriptCompatibility = false; + var port = new ColorHash(options); + + AssertColor(javaScript, "", (233, 0, lightness), (channel, channel, channel), cssHex); + Assert.Equal(portHex, port.Hex("")); + } + + private static void AssertColor(ColorHash colorHash, string input, + (double H, double S, double L) expectedHsl, (int R, int G, int B) expectedRgb, string expectedHex) + { + var hsl = colorHash.Hsl(input); + var rgb = colorHash.Rgb(input); + + Assert.Equal(expectedHsl, (hsl.H, hsl.S, hsl.L)); + Assert.Equal(255, rgb.A); + Assert.Equal(expectedRgb, ((int)rgb.R, (int)rgb.G, (int)rgb.B)); + Assert.Equal(expectedHex, colorHash.Hex(input)); + } + + private sealed class FixedHash : IHashFunction + { + private readonly ulong _hash; + + public FixedHash(ulong hash) + { + _hash = hash; + } + + public ulong Generate(string value) => _hash; + } + } +} diff --git a/src/ColorHashSharp.Tests/HslTest.cs b/src/ColorHashSharp.Tests/HslTest.cs new file mode 100644 index 0000000..f31f893 --- /dev/null +++ b/src/ColorHashSharp.Tests/HslTest.cs @@ -0,0 +1,44 @@ +using Fernandezja.ColorHashSharp.Entities; +using Xunit; + +namespace ColorHashSharp.Tests +{ + public class HslTest + { + [Fact(DisplayName = "Hsl_DefaultConstructor_ShouldInitialize")] + public void Hsl_DefaultConstructor_ShouldInitialize() + { + var hsl = new Hsl(); + + Assert.NotNull(hsl); + Assert.Equal(0, hsl.H); + Assert.Equal(0, hsl.S); + Assert.Equal(0, hsl.L); + } + + [Fact(DisplayName = "Hsl_ParameterizedConstructor_ShouldSetValues")] + public void Hsl_ParameterizedConstructor_ShouldSetValues() + { + var hsl = new Hsl(120.5, 0.75, 0.5); + + Assert.NotNull(hsl); + Assert.Equal(120.5, hsl.H); + Assert.Equal(0.75, hsl.S); + Assert.Equal(0.5, hsl.L); + } + + [Fact(DisplayName = "Hsl_Properties_CanBeModified")] + public void Hsl_Properties_CanBeModified() + { + var hsl = new Hsl(); + + hsl.H = 240; + hsl.S = 0.8; + hsl.L = 0.6; + + Assert.Equal(240, hsl.H); + Assert.Equal(0.8, hsl.S); + Assert.Equal(0.6, hsl.L); + } + } +} diff --git a/src/ColorHashSharp.Tests/HueTest.cs b/src/ColorHashSharp.Tests/HueTest.cs new file mode 100644 index 0000000..4d7b597 --- /dev/null +++ b/src/ColorHashSharp.Tests/HueTest.cs @@ -0,0 +1,40 @@ +using Fernandezja.ColorHashSharp.Entities; +using Xunit; + +namespace ColorHashSharp.Tests +{ + public class HueTest + { + [Fact(DisplayName = "Hue_DefaultConstructor_ShouldInitialize")] + public void Hue_DefaultConstructor_ShouldInitialize() + { + var hue = new Hue(); + + Assert.NotNull(hue); + Assert.Equal(0, hue.Min); + Assert.Equal(360, hue.Max); + } + + [Fact(DisplayName = "Hue_ParameterizedConstructor_ShouldSetValues")] + public void Hue_ParameterizedConstructor_ShouldSetValues() + { + var hue = new Hue(30, 120); + + Assert.NotNull(hue); + Assert.Equal(30, hue.Min); + Assert.Equal(120, hue.Max); + } + + [Fact(DisplayName = "Hue_Properties_CanBeModified")] + public void Hue_Properties_CanBeModified() + { + var hue = new Hue(); + + hue.Min = 90; + hue.Max = 270; + + Assert.Equal(90, hue.Min); + Assert.Equal(270, hue.Max); + } + } +} diff --git a/src/ColorHashSharp.Tests/OptionsExtendedTest.cs b/src/ColorHashSharp.Tests/OptionsExtendedTest.cs new file mode 100644 index 0000000..da21ad6 --- /dev/null +++ b/src/ColorHashSharp.Tests/OptionsExtendedTest.cs @@ -0,0 +1,64 @@ +using Fernandezja.ColorHashSharp; +using System.Collections.Generic; +using Xunit; + +namespace ColorHashSharp.Tests +{ + public class OptionsExtendedTest + { + [Fact(DisplayName = "Options_DefaultConstructor_ShouldInitializeWithDefaults")] + public void Options_DefaultConstructor_ShouldInitializeWithDefaults() + { + var options = new Options(); + + Assert.NotNull(options.S); + Assert.NotNull(options.L); + Assert.NotNull(options.HueRanges); + Assert.Equal(3, options.S.Count); + Assert.Equal(3, options.L.Count); + Assert.Empty(options.HueRanges); + } + + [Fact(DisplayName = "GetLS_WithNullParam_ShouldReturnDefaults")] + public void GetLS_WithNullParam_ShouldReturnDefaults() + { + var options = new Options(); + var result = options.GetLS((List)null); + + Assert.NotNull(result); + Assert.Equal(3, result.Count); + Assert.Equal(0.35, result[0]); + Assert.Equal(0.5, result[1]); + Assert.Equal(0.65, result[2]); + } + + [Theory(DisplayName = "SetHue_DifferentValues_ShouldSetCorrectly")] + [InlineData(0)] + [InlineData(180)] + [InlineData(360)] + public void SetHue_DifferentValues_ShouldSetCorrectly(int value) + { + var options = new Options(); + options.SetHue(value); + + Assert.Single(options.HueRanges); + Assert.Equal(value, options.HueRanges[0].Min); + Assert.Equal(value, options.HueRanges[0].Max); + } + + [Fact(DisplayName = "Options_SaturationAndLightness_DefaultValues")] + public void Options_SaturationAndLightness_DefaultValues() + { + var options = new Options(); + + // Test that S and L contain the expected default values + Assert.Contains(0.35, options.S); + Assert.Contains(0.5, options.S); + Assert.Contains(0.65, options.S); + + Assert.Contains(0.35, options.L); + Assert.Contains(0.5, options.L); + Assert.Contains(0.65, options.L); + } + } +} diff --git a/src/ColorHashSharp.Tests/OptionsTest.cs b/src/ColorHashSharp.Tests/OptionsTest.cs index 66a7124..6716193 100644 --- a/src/ColorHashSharp.Tests/OptionsTest.cs +++ b/src/ColorHashSharp.Tests/OptionsTest.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Text; @@ -37,7 +36,7 @@ public void GetLS_DefaultValues() public void GetLS_ArrayValues() { var options = new Fernandezja.ColorHashSharp.Options(); - var result = options.GetLS(new ArrayList() { 0.35, 0.35, 0.35}); + var result = options.GetLS(new List() { 0.35, 0.35, 0.35}); Assert.NotNull(result); Assert.Equal(3, result.Count); Assert.Equal(0.35, result[0]); diff --git a/src/ColorHashSharp.Tests/SimpleColorTransformsTest.cs b/src/ColorHashSharp.Tests/SimpleColorTransformsTest.cs new file mode 100644 index 0000000..22faba2 --- /dev/null +++ b/src/ColorHashSharp.Tests/SimpleColorTransformsTest.cs @@ -0,0 +1,474 @@ +using Fernandezja.ColorHashSharp; +using System.Drawing; +using Xunit; + +namespace ColorHashSharp.Tests +{ + public class SimpleColorTransformsTest + { + #region RgBtoHsl Tests + + [Fact(DisplayName = "RgBtoHsl_RedColor_ShouldConvert")] + public void RgBtoHsl_RedColor_ShouldConvert() + { + var color = Color.FromArgb(255, 0, 0); + var result = SimpleColorTransforms.RgBtoHsl(color); + + Assert.Equal(3, result.Length); + Assert.Equal(0, result[0]); // H + Assert.Equal(1, result[1]); // S + Assert.Equal(0.5, result[2]); // L + } + + [Fact(DisplayName = "RgBtoHsl_GreenColor_ShouldConvert")] + public void RgBtoHsl_GreenColor_ShouldConvert() + { + var color = Color.FromArgb(0, 255, 0); + var result = SimpleColorTransforms.RgBtoHsl(color); + + Assert.Equal(120, result[0]); // H + Assert.Equal(1, result[1]); // S + Assert.Equal(0.5, result[2]); // L + } + + [Fact(DisplayName = "RgBtoHsl_BlueColor_ShouldConvert")] + public void RgBtoHsl_BlueColor_ShouldConvert() + { + var color = Color.FromArgb(0, 0, 255); + var result = SimpleColorTransforms.RgBtoHsl(color); + + Assert.Equal(240, result[0]); // H + Assert.Equal(1, result[1]); // S + Assert.Equal(0.5, result[2]); // L + } + + [Fact(DisplayName = "RgBtoHsl_BlackColor_ShouldConvert")] + public void RgBtoHsl_BlackColor_ShouldConvert() + { + var color = Color.FromArgb(0, 0, 0); + var result = SimpleColorTransforms.RgBtoHsl(color); + + Assert.Equal(0, result[0]); // H + Assert.Equal(0, result[1]); // S + Assert.Equal(0, result[2]); // L + } + + [Fact(DisplayName = "RgBtoHsl_WhiteColor_ShouldConvert")] + public void RgBtoHsl_WhiteColor_ShouldConvert() + { + var color = Color.FromArgb(255, 255, 255); + var result = SimpleColorTransforms.RgBtoHsl(color); + + Assert.Equal(0, result[0]); // H (undefined for white) + Assert.Equal(0, result[1]); // S + Assert.Equal(1, result[2]); // L + } + + [Fact(DisplayName = "RgBtoHsl_GrayColor_ShouldConvert")] + public void RgBtoHsl_GrayColor_ShouldConvert() + { + var color = Color.FromArgb(128, 128, 128); + var result = SimpleColorTransforms.RgBtoHsl(color); + + Assert.Equal(0, result[0]); // H + Assert.Equal(0, result[1]); // S + Assert.InRange(result[2], 0.49, 0.51); // L approximately 0.5 + } + + [Fact(DisplayName = "RgBtoHsl_CustomColor_ShouldConvert")] + public void RgBtoHsl_CustomColor_ShouldConvert() + { + var color = Color.FromArgb(135, 150, 197); + var result = SimpleColorTransforms.RgBtoHsl(color); + + Assert.Equal(3, result.Length); + Assert.InRange(result[0], 0, 360); // H + Assert.InRange(result[1], 0, 1); // S + Assert.InRange(result[2], 0, 1); // L + } + + #endregion + + #region HsLtoRgb Tests + + [Fact(DisplayName = "HsLtoRgb_RedColor_ShouldConvert")] + public void HsLtoRgb_RedColor_ShouldConvert() + { + var result = SimpleColorTransforms.HsLtoRgb(0, 1, 0.5); + + Assert.Equal(255, result.A); + Assert.Equal(255, result.R); + Assert.Equal(0, result.G); + Assert.Equal(0, result.B); + } + + [Fact(DisplayName = "HsLtoRgb_AchromaticGray_ShouldConvert")] + public void HsLtoRgb_AchromaticGray_ShouldConvert() + { + var result = SimpleColorTransforms.HsLtoRgb(0, 0, 0.5); + + Assert.Equal(128, result.R); + Assert.Equal(128, result.G); + Assert.Equal(128, result.B); + } + + [Fact(DisplayName = "HsLtoRgb_WithCustomAlpha_ShouldSetAlpha")] + public void HsLtoRgb_WithCustomAlpha_ShouldSetAlpha() + { + var result = SimpleColorTransforms.HsLtoRgb(120, 1, 0.5, 128); + + Assert.Equal(128, result.A); + } + + [Fact(DisplayName = "HsLtoRgb_BoundaryValues_ShouldClamp")] + public void HsLtoRgb_BoundaryValues_ShouldClamp() + { + // Test with values outside normal range + var result = SimpleColorTransforms.HsLtoRgb(400, 1.5, 1.5, 300); + + Assert.Equal(255, result.A); // Clamped to 255 + Assert.InRange(result.R, 0, 255); + Assert.InRange(result.G, 0, 255); + Assert.InRange(result.B, 0, 255); + } + + [Theory(DisplayName = "HsLtoRgb_DifferentHues_ShouldConvert")] + [InlineData(0)] + [InlineData(60)] + [InlineData(120)] + [InlineData(180)] + [InlineData(240)] + [InlineData(300)] + public void HsLtoRgb_DifferentHues_ShouldConvert(double hue) + { + var result = SimpleColorTransforms.HsLtoRgb(hue, 1, 0.5); + + Assert.Equal(255, result.A); + Assert.InRange(result.R, 0, 255); + Assert.InRange(result.G, 0, 255); + Assert.InRange(result.B, 0, 255); + } + + #endregion + + #region RgBtoHsb Tests + + [Fact(DisplayName = "RgBtoHsb_RedColor_ShouldConvert")] + public void RgBtoHsb_RedColor_ShouldConvert() + { + var color = Color.FromArgb(255, 0, 0); + var result = SimpleColorTransforms.RgBtoHsb(color); + + Assert.Equal(0, result[0]); // H + Assert.Equal(1, result[1]); // S + Assert.Equal(1, result[2]); // B + } + + [Fact(DisplayName = "RgBtoHsb_GreenColor_ShouldConvert")] + public void RgBtoHsb_GreenColor_ShouldConvert() + { + var color = Color.FromArgb(0, 255, 0); + var result = SimpleColorTransforms.RgBtoHsb(color); + + Assert.Equal(120, result[0]); // H + Assert.Equal(1, result[1]); // S + Assert.Equal(1, result[2]); // B + } + + [Fact(DisplayName = "RgBtoHsb_BlueColor_ShouldConvert")] + public void RgBtoHsb_BlueColor_ShouldConvert() + { + var color = Color.FromArgb(0, 0, 255); + var result = SimpleColorTransforms.RgBtoHsb(color); + + Assert.Equal(240, result[0]); // H + Assert.Equal(1, result[1]); // S + Assert.Equal(1, result[2]); // B + } + + [Fact(DisplayName = "RgBtoHsb_BlackColor_ShouldConvert")] + public void RgBtoHsb_BlackColor_ShouldConvert() + { + var color = Color.FromArgb(0, 0, 0); + var result = SimpleColorTransforms.RgBtoHsb(color); + + // Black color has NaN for hue when max-min=0 + Assert.True(double.IsNaN(result[0]) || result[0] == 0); // H can be NaN or 0 + Assert.Equal(0, result[1]); // S + Assert.Equal(0, result[2]); // B + } + + #endregion + + #region HsBtoRgb Tests + + [Fact(DisplayName = "HsBtoRgb_Sector0_ShouldConvert")] + public void HsBtoRgb_Sector0_ShouldConvert() + { + var result = SimpleColorTransforms.HsBtoRgb(30, 1, 1); + + Assert.Equal(255, result.A); + Assert.Equal(255, result.R); + } + + [Fact(DisplayName = "HsBtoRgb_Sector1_ShouldConvert")] + public void HsBtoRgb_Sector1_ShouldConvert() + { + var result = SimpleColorTransforms.HsBtoRgb(90, 1, 1); + + Assert.Equal(255, result.A); + Assert.Equal(255, result.G); + } + + [Fact(DisplayName = "HsBtoRgb_Sector2_ShouldConvert")] + public void HsBtoRgb_Sector2_ShouldConvert() + { + var result = SimpleColorTransforms.HsBtoRgb(150, 1, 1); + + Assert.Equal(255, result.A); + Assert.Equal(255, result.G); + } + + [Fact(DisplayName = "HsBtoRgb_Sector3_ShouldConvert")] + public void HsBtoRgb_Sector3_ShouldConvert() + { + var result = SimpleColorTransforms.HsBtoRgb(210, 1, 1); + + Assert.Equal(255, result.A); + // Due to rounding in the algorithm, B might be 250 instead of 255 + Assert.InRange(result.B, 250, 255); + } + + [Fact(DisplayName = "HsBtoRgb_Sector4_ShouldConvert")] + public void HsBtoRgb_Sector4_ShouldConvert() + { + var result = SimpleColorTransforms.HsBtoRgb(270, 1, 1); + + Assert.Equal(255, result.A); + // Due to rounding in the algorithm, B might be 250 instead of 255 + Assert.InRange(result.B, 250, 255); + } + + [Fact(DisplayName = "HsBtoRgb_Sector5_ShouldConvert")] + public void HsBtoRgb_Sector5_ShouldConvert() + { + var result = SimpleColorTransforms.HsBtoRgb(330, 1, 1); + + Assert.Equal(255, result.A); + Assert.Equal(255, result.R); + } + + [Fact(DisplayName = "HsBtoRgb_ZeroSaturation_ShouldReturnGray")] + public void HsBtoRgb_ZeroSaturation_ShouldReturnGray() + { + var result = SimpleColorTransforms.HsBtoRgb(180, 0, 0.5); + + Assert.Equal(result.R, result.G); + // Note: Due to a bug in line 303 of SimpleColorTransforms.cs (bl * 250D instead of bl * 255D), + // the B value is slightly different from R and G + Assert.InRange(result.R, 125, 130); + Assert.InRange(result.B, 122, 128); + } + + [Fact(DisplayName = "HsBtoRgb_WithCustomAlpha_ShouldSetAlpha")] + public void HsBtoRgb_WithCustomAlpha_ShouldSetAlpha() + { + var result = SimpleColorTransforms.HsBtoRgb(120, 1, 1, 128); + + Assert.Equal(128, result.A); + } + + #endregion + + #region TransformBrightness Tests + + [Fact(DisplayName = "TransformBrightness_HslMode_ShouldIncreaseBrightness")] + public void TransformBrightness_HslMode_ShouldIncreaseBrightness() + { + var color = Color.FromArgb(128, 128, 128); + var result = SimpleColorTransforms.TransformBrightness( + color, + SimpleColorTransforms.ColorTransformMode.Hsl, + 1.5); + + Assert.NotEqual(color, result); + } + + [Fact(DisplayName = "TransformBrightness_HsbMode_ShouldIncreaseBrightness")] + public void TransformBrightness_HsbMode_ShouldIncreaseBrightness() + { + var color = Color.FromArgb(128, 128, 128); + var result = SimpleColorTransforms.TransformBrightness( + color, + SimpleColorTransforms.ColorTransformMode.Hsb, + 1.5); + + Assert.NotEqual(color, result); + } + + [Fact(DisplayName = "TransformBrightness_BlackColorWithIncrease_ShouldBrighten")] + public void TransformBrightness_BlackColorWithIncrease_ShouldBrighten() + { + var color = Color.FromArgb(0, 0, 0); + var result = SimpleColorTransforms.TransformBrightness( + color, + SimpleColorTransforms.ColorTransformMode.Hsl, + 2.0); + + // Black with brightness > 1 should result in non-black + Assert.True(result.R > 0 || result.G > 0 || result.B > 0); + } + + [Fact(DisplayName = "TransformBrightness_WithCustomAlpha_ShouldSetAlpha")] + public void TransformBrightness_WithCustomAlpha_ShouldSetAlpha() + { + var color = Color.FromArgb(255, 128, 128, 128); + var result = SimpleColorTransforms.TransformBrightness( + color, + SimpleColorTransforms.ColorTransformMode.Hsl, + 1.2, + 128); + + Assert.Equal(128, result.A); + } + + [Fact(DisplayName = "TransformBrightness_DecreaseBrightness_ShouldDarken")] + public void TransformBrightness_DecreaseBrightness_ShouldDarken() + { + var color = Color.FromArgb(200, 200, 200); + var result = SimpleColorTransforms.TransformBrightness( + color, + SimpleColorTransforms.ColorTransformMode.Hsl, + 0.5); + + Assert.True(result.R < color.R || result.G < color.G || result.B < color.B); + } + + #endregion + + #region TransformSaturationAndBrightness Tests + + [Fact(DisplayName = "TransformSaturationAndBrightness_HslMode_ShouldTransform")] + public void TransformSaturationAndBrightness_HslMode_ShouldTransform() + { + var color = Color.FromArgb(128, 100, 150); + var result = SimpleColorTransforms.TransformSaturationAndBrightness( + color, + SimpleColorTransforms.ColorTransformMode.Hsl, + 1.5, + 1.2); + + Assert.NotEqual(color, result); + } + + [Fact(DisplayName = "TransformSaturationAndBrightness_HsbMode_ShouldTransform")] + public void TransformSaturationAndBrightness_HsbMode_ShouldTransform() + { + var color = Color.FromArgb(128, 100, 150); + var result = SimpleColorTransforms.TransformSaturationAndBrightness( + color, + SimpleColorTransforms.ColorTransformMode.Hsb, + 1.5, + 1.2); + + Assert.NotEqual(color, result); + } + + [Fact(DisplayName = "TransformSaturationAndBrightness_ZeroSaturationWithIncrease_ShouldIncrease")] + public void TransformSaturationAndBrightness_ZeroSaturationWithIncrease_ShouldIncrease() + { + var color = Color.FromArgb(128, 128, 128); // Gray has zero saturation + var result = SimpleColorTransforms.TransformSaturationAndBrightness( + color, + SimpleColorTransforms.ColorTransformMode.Hsl, + 2.0, + 1.0); + + Assert.NotNull(result); + } + + [Fact(DisplayName = "TransformSaturationAndBrightness_ZeroBrightnessWithIncrease_ShouldIncrease")] + public void TransformSaturationAndBrightness_ZeroBrightnessWithIncrease_ShouldIncrease() + { + var color = Color.FromArgb(0, 0, 0); // Black + var result = SimpleColorTransforms.TransformSaturationAndBrightness( + color, + SimpleColorTransforms.ColorTransformMode.Hsl, + 1.0, + 2.0); + + Assert.NotNull(result); + } + + [Fact(DisplayName = "TransformSaturationAndBrightness_WithCustomAlpha_ShouldSetAlpha")] + public void TransformSaturationAndBrightness_WithCustomAlpha_ShouldSetAlpha() + { + var color = Color.FromArgb(255, 128, 100, 150); + var result = SimpleColorTransforms.TransformSaturationAndBrightness( + color, + SimpleColorTransforms.ColorTransformMode.Hsl, + 1.2, + 1.2, + 100); + + Assert.Equal(100, result.A); + } + + #endregion + + #region AlphaCombine Tests + + [Fact(DisplayName = "AlphaCombine_TwoColors_ShouldCombine")] + public void AlphaCombine_TwoColors_ShouldCombine() + { + var color1 = Color.FromArgb(255, 255, 0, 0); // Red with full alpha + var color2 = Color.FromArgb(255, 0, 0, 255); // Blue with full alpha + + var result = SimpleColorTransforms.AlphaCombine(color1, color2, 255); + + Assert.Equal(255, result.A); + Assert.InRange(result.R, 0, 255); + Assert.InRange(result.G, 0, 255); + Assert.InRange(result.B, 0, 255); + } + + [Fact(DisplayName = "AlphaCombine_DifferentAlphas_ShouldWeightByAlpha")] + public void AlphaCombine_DifferentAlphas_ShouldWeightByAlpha() + { + var color1 = Color.FromArgb(128, 255, 0, 0); // Red with half alpha + var color2 = Color.FromArgb(255, 0, 0, 255); // Blue with full alpha + + var result = SimpleColorTransforms.AlphaCombine(color1, color2, 200); + + Assert.Equal(200, result.A); + } + + [Fact(DisplayName = "AlphaCombine_ZeroAlphas_ShouldReturnBlack")] + public void AlphaCombine_ZeroAlphas_ShouldReturnBlack() + { + var color1 = Color.FromArgb(0, 255, 0, 0); + var color2 = Color.FromArgb(0, 0, 0, 255); + + var result = SimpleColorTransforms.AlphaCombine(color1, color2, 255); + + Assert.Equal(0, result.R); + Assert.Equal(0, result.G); + Assert.Equal(0, result.B); + } + + [Fact(DisplayName = "AlphaCombine_SameColors_ShouldReturnSimilar")] + public void AlphaCombine_SameColors_ShouldReturnSimilar() + { + var color1 = Color.FromArgb(255, 100, 150, 200); + var color2 = Color.FromArgb(255, 100, 150, 200); + + var result = SimpleColorTransforms.AlphaCombine(color1, color2, 255); + + Assert.Equal(100, result.R); + Assert.Equal(150, result.G); + Assert.Equal(200, result.B); + } + + #endregion + } +} diff --git a/src/ColorHashSharp.Tests/UtilitiesTest.cs b/src/ColorHashSharp.Tests/UtilitiesTest.cs new file mode 100644 index 0000000..868f1c3 --- /dev/null +++ b/src/ColorHashSharp.Tests/UtilitiesTest.cs @@ -0,0 +1,63 @@ +using Fernandezja.ColorHashSharp; +using Xunit; + +namespace ColorHashSharp.Tests +{ + public class UtilitiesTest + { + [Fact(DisplayName = "StringToNumber_SimpleString_ShouldConvert")] + public void StringToNumber_SimpleString_ShouldConvert() + { + var utilities = new Utilities(); + var result = utilities.StringToNumber("abc"); + + Assert.NotNull(result); + Assert.NotEmpty(result); + // 'a' = 97, 'b' = 98, 'c' = 99 + Assert.Equal("979899", result); + } + + [Fact(DisplayName = "StringToNumber_SingleChar_ShouldConvert")] + public void StringToNumber_SingleChar_ShouldConvert() + { + var utilities = new Utilities(); + var result = utilities.StringToNumber("A"); + + Assert.NotNull(result); + // 'A' = 65 + Assert.Equal("65", result); + } + + [Fact(DisplayName = "StringToNumber_EmptyString_ShouldReturnEmpty")] + public void StringToNumber_EmptyString_ShouldReturnEmpty() + { + var utilities = new Utilities(); + var result = utilities.StringToNumber(""); + + Assert.NotNull(result); + Assert.Empty(result); + } + + [Fact(DisplayName = "StringToNumber_SpecialChars_ShouldConvert")] + public void StringToNumber_SpecialChars_ShouldConvert() + { + var utilities = new Utilities(); + var result = utilities.StringToNumber(" !@"); + + Assert.NotNull(result); + // ' ' = 32, '!' = 33, '@' = 64 + Assert.Equal("323364", result); + } + + [Fact(DisplayName = "StringToNumber_Numbers_ShouldConvert")] + public void StringToNumber_Numbers_ShouldConvert() + { + var utilities = new Utilities(); + var result = utilities.StringToNumber("123"); + + Assert.NotNull(result); + // '1' = 49, '2' = 50, '3' = 51 + Assert.Equal("495051", result); + } + } +} diff --git a/src/ColorHashSharp.sln b/src/ColorHashSharp.sln deleted file mode 100644 index 2f25105..0000000 --- a/src/ColorHashSharp.sln +++ /dev/null @@ -1,37 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.5.33103.201 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ColorHashSharp", "ColorHashSharp\ColorHashSharp.csproj", "{68766358-4CA1-4A57-94B9-0E1CF0F809BF}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ColorHashSharp.Tests", "ColorHashSharp.Tests\ColorHashSharp.Tests.csproj", "{2170724A-3466-4604-B243-D3B0936B44A3}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ColorHashSharp.Benchmarks", "ColorHashSharp.Benchmarks\ColorHashSharp.Benchmarks.csproj", "{2CC808B2-AF1F-4556-B601-C755129CCEB0}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {68766358-4CA1-4A57-94B9-0E1CF0F809BF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {68766358-4CA1-4A57-94B9-0E1CF0F809BF}.Debug|Any CPU.Build.0 = Debug|Any CPU - {68766358-4CA1-4A57-94B9-0E1CF0F809BF}.Release|Any CPU.ActiveCfg = Release|Any CPU - {68766358-4CA1-4A57-94B9-0E1CF0F809BF}.Release|Any CPU.Build.0 = Release|Any CPU - {2170724A-3466-4604-B243-D3B0936B44A3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2170724A-3466-4604-B243-D3B0936B44A3}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2170724A-3466-4604-B243-D3B0936B44A3}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2170724A-3466-4604-B243-D3B0936B44A3}.Release|Any CPU.Build.0 = Release|Any CPU - {2CC808B2-AF1F-4556-B601-C755129CCEB0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2CC808B2-AF1F-4556-B601-C755129CCEB0}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2CC808B2-AF1F-4556-B601-C755129CCEB0}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2CC808B2-AF1F-4556-B601-C755129CCEB0}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {627C67CF-7341-4A16-BF8A-8EF505E6F60B} - EndGlobalSection -EndGlobal diff --git a/src/ColorHashSharp.slnx b/src/ColorHashSharp.slnx new file mode 100644 index 0000000..8784211 --- /dev/null +++ b/src/ColorHashSharp.slnx @@ -0,0 +1,5 @@ + + + + + diff --git a/src/ColorHashSharp/BKDRHash.cs b/src/ColorHashSharp/BKDRHash.cs index 1b8ab2e..0d2e10f 100644 --- a/src/ColorHashSharp/BKDRHash.cs +++ b/src/ColorHashSharp/BKDRHash.cs @@ -2,10 +2,11 @@ using System.Diagnostics; using System.Numerics; using System.Text; +using Fernandezja.ColorHashSharp.Interfaces; namespace Fernandezja.ColorHashSharp { - public class BKDRHash + public class BKDRHash : IHashFunction { private const char PADDING_CHAR = 'x'; @@ -33,32 +34,19 @@ public ulong GenerateVersion2(string value) // Make hash more sensitive for short string like 'a', 'b', 'c' var valueWithPadding = $"{value}{PADDING_CHAR}"; - var valueUtf8 = ToUTF8(valueWithPadding); + // Convert to UTF8 bytes once, avoiding repeated conversions + var valueUtf8Bytes = Encoding.UTF8.GetBytes(valueWithPadding); var max = (Int64.MaxValue / (long)SEED); - for (int i = 0; i < valueUtf8.Length; i++) + for (int i = 0; i < valueUtf8Bytes.Length; i++) { if (hash > max) { - Debug.WriteLine($"hash > max"); - Debug.WriteLine($" hash = {hash}"); - Debug.WriteLine($" max = {max} >> ToUInt64(max) = {Convert.ToUInt64(max)}"); - Debug.WriteLine($" seed2 = {SEED2}"); - hash = (hash / (long)SEED2); - - Debug.WriteLine($" new hash = {hash}"); - Debug.WriteLine($" "); } - var bytes = ToUTF8Bytes(valueUtf8[i].ToString()); - - Debug.WriteLine($"{valueUtf8[i].ToString()} > {bytes[0]}"); - - hash = (hash * (long)SEED) + bytes[0]; - - Debug.WriteLine($"{valueUtf8[i].ToString()} > {bytes[0]} > hash = {hash}"); + hash = (hash * (long)SEED) + valueUtf8Bytes[i]; } return (ulong)hash; @@ -67,7 +55,7 @@ public ulong GenerateVersion2(string value) /// - /// BKDR Hash (modified version). Idem original code. + /// Historical ColorHashSharp BKDR hash over UTF-8 bytes. /// https://github.com/zenozeng/color-hash/blob/master/lib/bkdr-hash.js /// Example values nodejs https://repl.it/@Jose_AA/BKDR-Hash /// @@ -80,48 +68,25 @@ public ulong GenerateVersion3(string value) // Make hash more sensitive for short string like 'a', 'b', 'c' var valueWithPadding = $"{value}{PADDING_CHAR}"; - var valueUtf8 = ToUTF8(valueWithPadding); + // Convert to UTF8 bytes once, avoiding repeated conversions + var valueUtf8Bytes = Encoding.UTF8.GetBytes(valueWithPadding); var max = (JAVASCRIPT_MAX_SAFE_INTEGER / SEED); - for (int i = 0; i < valueUtf8.Length; i++) + for (int i = 0; i < valueUtf8Bytes.Length; i++) { if (hash > max) { - Debug.WriteLine($"hash > max"); - Debug.WriteLine($" hash = {hash}"); - Debug.WriteLine($" max = {max} >> ToUInt64(max) = {Convert.ToUInt64(max)}"); - Debug.WriteLine($" seed2 = {SEED2}"); - hash = (hash / SEED2); - - Debug.WriteLine($" new hash = {hash}"); - Debug.WriteLine($" "); } - var bytes = ToUTF8Bytes(valueUtf8[i].ToString()); - - Debug.WriteLine($"{valueUtf8[i].ToString()} > {bytes[0]}"); - - hash = (hash * SEED) + bytes[0]; - - Debug.WriteLine($"{valueUtf8[i].ToString()} > {bytes[0]} > hash = {hash}"); + hash = (hash * SEED) + valueUtf8Bytes[i]; } return hash; } - private string ToUTF8(string value) - { - var bytes = Encoding.Default.GetBytes(value); - return Encoding.UTF8.GetString(bytes); - } - private byte[] ToUTF8Bytes(string value) - { - var bytes = Encoding.UTF8.GetBytes(value); - return bytes; - } diff --git a/src/ColorHashSharp/ColorHash.cs b/src/ColorHashSharp/ColorHash.cs index 8a85060..ca962c8 100644 --- a/src/ColorHashSharp/ColorHash.cs +++ b/src/ColorHashSharp/ColorHash.cs @@ -1,8 +1,6 @@ using Fernandezja.ColorHashSharp.Entities; using System; using System.Collections.Generic; -using System.Collections; -using System.Text; using System.Drawing; using Fernandezja.ColorHashSharp.Interfaces; @@ -10,17 +8,77 @@ namespace Fernandezja.ColorHashSharp { public class ColorHash : IColorHash, IColorHashAlias { + private const int HueModulo = 359; + private const int HueResolution = 727; - private Options _options; + private readonly (int Min, int Max)[] _hueRanges; + private readonly double[] _saturation; + private readonly double[] _lightness; + private readonly bool _useJavaScriptCompatibility; + private readonly IHashFunction _hashGenerator; + private readonly ColorToHex _hexConverter; - public ColorHash() + public ColorHash() : this(new Options()) { - _options = new Options(); } + /// + /// Creates a color generator with a copy of the supplied palettes and hue ranges. + /// + /// is null. + /// A palette or hue range is invalid. public ColorHash(Options options) { - _options = options; + if (options == null) + { + throw new ArgumentNullException(nameof(options)); + } + + _saturation = CopyPalette(options.S, nameof(Options.S), nameof(options)); + _lightness = CopyPalette(options.L, nameof(Options.L), nameof(options)); + + var ranges = options.HueRanges + ?? throw new ArgumentException("HueRanges cannot be null.", nameof(options)); + _hueRanges = new (int Min, int Max)[ranges.Count]; + for (int index = 0; index < _hueRanges.Length; index++) + { + var range = ranges[index] + ?? throw new ArgumentException($"HueRanges[{index}] cannot be null.", nameof(options)); + int min = range.Min; + int max = range.Max; + if (min < 0 || max > 360 || min > max) + { + throw new ArgumentException( + $"HueRanges[{index}] must satisfy 0 <= Min <= Max <= 360.", nameof(options)); + } + + _hueRanges[index] = (min, max); + } + + _hashGenerator = options.HashFunction ?? new Sha256Hash(); + _useJavaScriptCompatibility = options.UseJavaScriptCompatibility; + _hexConverter = new ColorToHex(); + } + + private static double[] CopyPalette(List palette, string propertyName, string paramName) + { + if (palette == null || palette.Count == 0) + { + throw new ArgumentException($"{propertyName} must contain at least one value.", paramName); + } + + var values = palette.ToArray(); + for (int index = 0; index < values.Length; index++) + { + double value = values[index]; + if (double.IsNaN(value) || value < 0 || value > 1) + { + throw new ArgumentException( + $"{propertyName}[{index}] must be a finite value between 0 and 1.", paramName); + } + } + + return values; } #region IColorHash @@ -33,53 +91,65 @@ public string Build(string value) public Color BuildToColor(string value) { var hsl = BuildToHsl(value); - var color = (new ColorToRgb()).ToRgb(hsl); - return color; + var rounding = _useJavaScriptCompatibility ? MidpointRounding.AwayFromZero : MidpointRounding.ToEven; + return ColorToRgb.ToRgb(hsl.H, hsl.S, hsl.L, rounding); } public string BuildToHex(string value) { var color = BuildToColor(value); - var hex = (new ColorToHex()).BuildToHex(color); - return hex; + return _hexConverter.BuildToHex(color, _useJavaScriptCompatibility); } public Hsl BuildToHsl(string value) { - double h, s, l; - - var hashGenerator = new BKDRHash(); + var hash = _hashGenerator.Generate(value ?? string.Empty); + return _useJavaScriptCompatibility ? BuildJavaScriptHsl(hash) : BuildPortHsl(hash); + } - var hash = hashGenerator.Generate(value); + private Hsl BuildPortHsl(ulong hash) + { + double hue; - if (_options.HueRanges.Count > 0) + if (_hueRanges.Length > 0) { - var rangeIndex = hash % Convert.ToUInt64(_options.HueRanges.Count); - - //TODO: Convert int? prevent error - var hueValue = (Hue)_options.HueRanges[(int)rangeIndex]; - - var hueResolution = Convert.ToUInt64(727); - h = ((hash / Convert.ToUInt64(_options.HueRanges.Count)) % hueResolution) - * (Convert.ToUInt64(hueValue.Max) - Convert.ToUInt64(hueValue.Min)) / hueResolution + Convert.ToUInt64(hueValue.Min); - + var rangeCount = (ulong)_hueRanges.Length; + var range = _hueRanges[(int)(hash % rangeCount)]; + hue = ((hash / rangeCount) % HueResolution) + * (ulong)(range.Max - range.Min) / HueResolution + (ulong)range.Min; } else { - h = hash % 359; // note that 359 is a prime + hue = hash % HueModulo; } - hash = (hash / 360); - var sIndex = (hash % (ulong)_options.S.Count); - s = (double)_options.S[(int)sIndex]; + hash /= 360; + double saturation = _saturation[(int)(hash % (ulong)_saturation.Length)]; + + hash /= (ulong)_saturation.Length; + double lightness = _lightness[(int)(hash % (ulong)_lightness.Length)]; + + return new Hsl(hue, saturation, lightness); + } + + private Hsl BuildJavaScriptHsl(double hash) + { + double hue = hash % HueModulo; + if (_hueRanges.Length > 0) + { + int rangeCount = _hueRanges.Length; + var range = _hueRanges[(int)(hash % rangeCount)]; + hue = ((hash / rangeCount) % HueResolution) + * (range.Max - range.Min) / HueResolution + range.Min; + } - hash = (hash / (ulong)_options.S.Count); - var lIndex = (hash % (ulong)_options.L.Count); - l = (double)_options.L[(int)lIndex]; + hash = Math.Ceiling(hash / 360); + double saturation = _saturation[(int)(hash % _saturation.Length)]; - var hslResult = new Hsl(h, s, l); + hash = Math.Ceiling(hash / _saturation.Length); + double lightness = _lightness[(int)(hash % _lightness.Length)]; - return hslResult; + return new Hsl(hue, saturation, lightness); } #endregion diff --git a/src/ColorHashSharp/ColorHashSharp.csproj b/src/ColorHashSharp/ColorHashSharp.csproj index a0eeaf0..65a21d9 100644 --- a/src/ColorHashSharp/ColorHashSharp.csproj +++ b/src/ColorHashSharp/ColorHashSharp.csproj @@ -1,7 +1,7 @@  - netstandard2.0;netstandard2.1;net48;net481;net8.0;net9.0 + netstandard2.0;netstandard2.1;net48;net481;net10.0;net11.0 Fernandezja.ColorHashSharp false 1.1.0.0 diff --git a/src/ColorHashSharp/ColorHashSharp.nuspec b/src/ColorHashSharp/ColorHashSharp.nuspec index 8a5372a..6245abe 100644 --- a/src/ColorHashSharp/ColorHashSharp.nuspec +++ b/src/ColorHashSharp/ColorHashSharp.nuspec @@ -2,7 +2,7 @@ ColorHashSharp - 1.1.0 + 2.0.0 Jose A. Fernandez Jose A. Fernandez MIT @@ -20,8 +20,8 @@ - - + + \ No newline at end of file diff --git a/src/ColorHashSharp/ColorToHex.cs b/src/ColorHashSharp/ColorToHex.cs index 9a83e8b..b1c1e4d 100644 --- a/src/ColorHashSharp/ColorToHex.cs +++ b/src/ColorHashSharp/ColorToHex.cs @@ -7,11 +7,16 @@ namespace Fernandezja.ColorHashSharp { public class ColorToHex { - public string BuildToHex(Color color) { - string hex = color.R.ToString("X2") - + color.G.ToString("X2") - + color.B.ToString("X2"); - return hex; + public string BuildToHex(Color color) + { + return BuildToHex(color, cssFormat: false); + } + + internal string BuildToHex(Color color, bool cssFormat) + { + var prefix = cssFormat ? "#" : string.Empty; + var format = cssFormat ? "x2" : "X2"; + return prefix + color.R.ToString(format) + color.G.ToString(format) + color.B.ToString(format); } } } diff --git a/src/ColorHashSharp/ColorToRgb.cs b/src/ColorHashSharp/ColorToRgb.cs index aca8dc7..2c945a1 100644 --- a/src/ColorHashSharp/ColorToRgb.cs +++ b/src/ColorHashSharp/ColorToRgb.cs @@ -63,33 +63,28 @@ public static Color ToRgb1(double hue, double saturation, double lightness) /// /// public static Color ToRgb2(double hue, double saturation, double lightness) + { + return ToRgb(hue, saturation, lightness, MidpointRounding.ToEven); + } + + internal static Color ToRgb(double hue, double saturation, double lightness, MidpointRounding rounding) { var h = hue / 360; - Debug.WriteLine($"h = {h}"); var q = lightness < 0.5 ? lightness * (1 + saturation) : lightness + saturation - (lightness * saturation); - var p = 2.0 * lightness - q; - Debug.WriteLine($"q = {q}"); - Debug.WriteLine($"p = {p}"); - - var r = GetColor(h + 1 / 3.0, q, p); - var g = GetColor(h, q, p); - var b = GetColor(h - 1 / 3.0, q, p); + var r = GetColor(h + 1 / 3.0, q, p, rounding); + var g = GetColor(h, q, p, rounding); + var b = GetColor(h - 1 / 3.0, q, p, rounding); return Color.FromArgb(alpha: 255, red: r, green: g, blue: b); - - } - private static int GetColor(double color, double q, double p) { - - Debug.WriteLine($" 1 color = {color}"); - + private static int GetColor(double color, double q, double p, MidpointRounding rounding) { if (color < 0) { color++; @@ -117,13 +112,7 @@ private static int GetColor(double color, double q, double p) { color = p; } - Debug.WriteLine($" 2 color = {color}"); - - Debug.WriteLine($" ----------------------------"); - - return (int)Math.Round(color * 255); - - + return (int)Math.Round(color * 255, rounding); } diff --git a/src/ColorHashSharp/Interfaces/IHashFunction.cs b/src/ColorHashSharp/Interfaces/IHashFunction.cs new file mode 100644 index 0000000..76bce68 --- /dev/null +++ b/src/ColorHashSharp/Interfaces/IHashFunction.cs @@ -0,0 +1,17 @@ +using System; + +namespace Fernandezja.ColorHashSharp.Interfaces +{ + /// + /// Interface for custom hash functions + /// + public interface IHashFunction + { + /// + /// Generate hash from string value + /// + /// Input string + /// Hash as unsigned long + ulong Generate(string value); + } +} diff --git a/src/ColorHashSharp/JavaScriptBkdrHash.cs b/src/ColorHashSharp/JavaScriptBkdrHash.cs new file mode 100644 index 0000000..6b689bb --- /dev/null +++ b/src/ColorHashSharp/JavaScriptBkdrHash.cs @@ -0,0 +1,36 @@ +using Fernandezja.ColorHashSharp.Interfaces; + +namespace Fernandezja.ColorHashSharp +{ + /// + /// Computes the optional BKDR hash from color-hash 2.x over UTF-16 code units. + /// + public sealed class JavaScriptBkdrHash : IHashFunction + { + private const ulong Seed = 131; + private const ulong ReductionDivisor = 137; + private const ulong ReductionThreshold = 9007199254740991 / ReductionDivisor; + private const char Padding = 'x'; + + public ulong Generate(string value) + { + ulong hash = 0; + foreach (var codeUnit in value ?? string.Empty) + { + hash = Append(hash, codeUnit); + } + + return Append(hash, Padding); + } + + private static ulong Append(ulong hash, char codeUnit) + { + if (hash > ReductionThreshold) + { + hash /= ReductionDivisor; + } + + return hash * Seed + codeUnit; + } + } +} diff --git a/src/ColorHashSharp/Options.cs b/src/ColorHashSharp/Options.cs index 7306ece..037e730 100644 --- a/src/ColorHashSharp/Options.cs +++ b/src/ColorHashSharp/Options.cs @@ -1,6 +1,6 @@ using Fernandezja.ColorHashSharp.Entities; +using Fernandezja.ColorHashSharp.Interfaces; using System; -using System.Collections; using System.Collections.Generic; using System.Text; @@ -15,18 +15,29 @@ public class Options /// /// Saturation /// - public ArrayList S { get; set; } + public List S { get; set; } /// /// Lightness /// - public ArrayList L { get; set; } + public List L { get; set; } + + /// + /// Custom hash function. If null, SHA-256 is used by default. + /// + public IHashFunction HashFunction { get; set; } + + /// + /// Uses the HSL calculation, RGB rounding, and CSS hex format of color-hash 2.0.2. + /// Set to false to use the historical port's color calculation and format. + /// + public bool UseJavaScriptCompatibility { get; set; } = true; public Options() { //TODO: Get from options param - S = GetLS(new ArrayList() { 0.35, 0.5, 0.65 }); - L = GetLS(new ArrayList() { 0.35, 0.5, 0.65 }); + S = GetLS(new List() { 0.35, 0.5, 0.65 }); + L = GetLS(new List() { 0.35, 0.5, 0.65 }); HueRanges = new List(); } @@ -37,9 +48,9 @@ public Options() /// /// /// - internal protected ArrayList GetLS(double param) + internal protected List GetLS(double param) { - return new ArrayList() { param }; + return new List() { param }; } /// @@ -47,18 +58,18 @@ internal protected ArrayList GetLS(double param) /// /// /// - internal protected ArrayList GetLS(ArrayList param) + internal protected List GetLS(List param) { if (param == null) { // note that 3 is a prime - param = new ArrayList() { 0.35, 0.5, 0.65 }; + param = new List() { 0.35, 0.5, 0.65 }; } return param; } - internal protected ArrayList GetLS() + internal protected List GetLS() { return GetLS(null); } diff --git a/src/ColorHashSharp/Sha256Hash.cs b/src/ColorHashSharp/Sha256Hash.cs new file mode 100644 index 0000000..5f6910a --- /dev/null +++ b/src/ColorHashSharp/Sha256Hash.cs @@ -0,0 +1,54 @@ +using System.Security.Cryptography; +using System.Text; +using Fernandezja.ColorHashSharp.Interfaces; + +namespace Fernandezja.ColorHashSharp +{ + /// + /// Reads the first four bytes of a SHA-256 digest as an unsigned big-endian integer. + /// + public sealed class Sha256Hash : IHashFunction + { + private static readonly Encoding Utf8 = new UTF8Encoding(false, true); + + public ulong Generate(string value) + { + using (var sha256 = SHA256.Create()) + { + var digest = sha256.ComputeHash(Encode(value ?? string.Empty)); + return ((ulong)digest[0] << 24) | ((ulong)digest[1] << 16) + | ((ulong)digest[2] << 8) | digest[3]; + } + } + + private static byte[] Encode(string value) + { + try + { + return Utf8.GetBytes(value); + } + catch (EncoderFallbackException) + { + // color-hash 2.0.2 combines any surrogate with the next code unit, + // using zero for the missing code unit at the end of a string. + var normalized = new StringBuilder(value.Length); + for (int index = 0; index < value.Length; index++) + { + char codeUnit = value[index]; + if (char.IsSurrogate(codeUnit)) + { + int next = ++index < value.Length ? value[index] : 0; + int scalar = 0x10000 + (((codeUnit & 0x3FF) << 10) | (next & 0x3FF)); + normalized.Append(char.ConvertFromUtf32(scalar)); + } + else + { + normalized.Append(codeUnit); + } + } + + return Utf8.GetBytes(normalized.ToString()); + } + } + } +}