JasonBock / SpackleNet

Spackle is a project that contains a number of helper methods I've used to supplement the core classes in .NET.
MIT License
14 stars 1 forks source link

Add Method to do Custom `BigInteger` Formatting #33

Open JasonBock opened 3 years ago

JasonBock commented 3 years ago

The idea is, could I format a BigInteger such that I don't get the entire value from ToString()? If it's a large number, I'd just want to see 14231...95810.

I posted the question to Discord and I got an interesting response. See if I can get this to work.

In case the link disappears, here's the code for the idea (came from "FiniteReality"):

const int CharsBeforeDots = 5;
const string Dots = "...";
const int CharsAfterDots = 5;

char[] tempBuffer = ArrayPool<char>.Rent(1024);
if (!bigInt.TryFormat(tempBuffer, out var length))
    // some even larger handling stuff
    throw new Exception("oh no");
var s = string.Create(CharsBeforeDots + Dots.Length + CharsAfterDots, (tempBuffer, length), static (buffer, state)
{
    var original = state.tempBuffer.AsSpan(0, state.length);
    if (original.Length <= (CharsBeforeDots + Dots.Length + CharsAfterDots))
    {
        original.CopyTo(buffer);
        return;
    }

    original[0..CharsBeforeDots].CopyTo(buffer);
    Dots.AsSpan().CopyTo(buffer[CharsBeforeDots..]);
    original[^CharsAfterDots..].CopyTo(buffer[^CharsAfterDots..]);
});