From 2fec0dc16351495a9a9a9dfc0a048aa040e211da Mon Sep 17 00:00:00 2001 From: Edward Thomson Date: Sun, 2 Aug 2020 13:43:40 +0100 Subject: [PATCH] alphabet: handle large ratio of alphabet to seps When using a custom alphabet, there may be a large ratio of alphabet characters to separator characters. When the ratio is larger than 3.5, the alphabet and separators are adjusted. However, if we use integer arithmetic, we may not do the adjustment when the ratio is > 3.5 but < 4. Use floating point arithmetic to do this comparison. Include a test where the ratio of alphabet characters to separator characters is 3.714. --- src/Hashids.net/Hashids.cs | 4 ++-- test/Hashids.net.test/Hashids_test.cs | 7 +++++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/Hashids.net/Hashids.cs b/src/Hashids.net/Hashids.cs index 180fc3f..1606d89 100644 --- a/src/Hashids.net/Hashids.cs +++ b/src/Hashids.net/Hashids.cs @@ -224,9 +224,9 @@ private void SetupSeps() seps = ConsistentShuffle(seps, salt); - if (seps.Length == 0 || (alphabet.Length / seps.Length) > SEP_DIV) + if (seps.Length == 0 || ((float)alphabet.Length / seps.Length) > SEP_DIV) { - var sepsLength = (int)Math.Ceiling(alphabet.Length / SEP_DIV); + var sepsLength = (int)Math.Ceiling((float)alphabet.Length / SEP_DIV); if (sepsLength == 1) sepsLength = 2; diff --git a/test/Hashids.net.test/Hashids_test.cs b/test/Hashids.net.test/Hashids_test.cs index eda8b46..f5d9bdc 100644 --- a/test/Hashids.net.test/Hashids_test.cs +++ b/test/Hashids.net.test/Hashids_test.cs @@ -112,6 +112,13 @@ void it_can_encode_with_a_custom_alphabet() h.Encode(1, 2, 3, 4, 5).Should().Be("6nhmFDikA0"); } + [Fact] + void it_can_encode_with_a_custom_alphabet_and_few_seps() + { + var h = new Hashids(salt, 0, "ABCDEFGHIJKMNOPQRSTUVWXYZ23456789"); + h.Encode(1, 2, 3, 4, 5).Should().Be("44HYIRU3TO"); + } + [Fact] void it_does_not_produce_repeating_patterns_for_identical_numbers() {