Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/DividingCoder.cs

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alternatively, an approach like in this fix could be used.

Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public abstract class DividingCoder<TAlphabet>(TAlphabet alphabet)
: IBaseCoder, INonAllocatingBaseCoder
where TAlphabet: CodingAlphabet
{
readonly int reductionFactor = Convert.ToInt32(1000 * Math.Log2(alphabet.Length) / 8);
readonly int reductionFactor = Convert.ToInt32(10_000 * Math.Log2(alphabet.Length) / 8);
readonly char zeroChar = alphabet.Value[0];

/// <summary>
Expand All @@ -40,7 +40,7 @@ public virtual int GetSafeByteCountForDecoding(ReadOnlySpan<char> text)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
int getSafeByteCountForDecoding(int textLen, int zeroPrefixLen)
{
return zeroPrefixLen + ((textLen - zeroPrefixLen) * reductionFactor / 1000) + 1;
return zeroPrefixLen + ((textLen - zeroPrefixLen) * reductionFactor / 10_000) + 1;
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
Expand All @@ -62,7 +62,7 @@ public virtual int GetSafeCharCountForEncoding(ReadOnlySpan<byte> bytes)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
int getSafeCharCountForEncoding(int bytesLen, int zeroPrefixLen)
{
return zeroPrefixLen + ((bytesLen - zeroPrefixLen) * 1000 / reductionFactor) + 1;
return zeroPrefixLen + ((bytesLen - zeroPrefixLen) * 10_000 / reductionFactor) + 1;
}

/// <summary>
Expand Down
17 changes: 16 additions & 1 deletion test/Base62/DefaultTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,5 +61,20 @@ public void TryDecode_ReturnsCorrectValues(string decoded, string encoded)
Assert.That(result, Is.True);
Assert.That(Encoding.UTF8.GetString(output[..bytesWritten]), Is.EqualTo(decoded));
}


[Test]
public void Roundtrip_DoesNotTruncateHighByte()
{
// https://github.com/ssg/SimpleBase/issues/79

// 2762 is the smallest length where (textLen * 744 / 1000) + 1 underestimates
// the required output buffer by 1, dropping the most-significant byte.
var bytes = new byte[2762];
Array.Fill(bytes, (byte)0xFF);

var encoded = Base62.Default.Encode(bytes);
var decoded = Base62.Default.Decode(encoded);

Assert.That(decoded, Is.EqualTo(bytes));
}
}