fix: Adds ISpanFormattable to Geometry structs (#1231)

* Adds ISpanFormattable to geometry structs and makes ToString() near-zero-allocation.
* Adds IEquatable, and Parsable to Rectangle3D to get it in-line with the other structs.

Closes #1067
This commit is contained in:
Kamron Batman 2022-11-06 17:37:30 -08:00 committed by GitHub
parent c75bde55da
commit d7d914df6c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
12 changed files with 721 additions and 195 deletions

View file

@ -21,7 +21,7 @@ namespace Server;
[Parsable]
public struct Point3D
: IPoint3D, IComparable<Point3D>, IComparable<IPoint3D>, IEquatable<object>, IEquatable<Point3D>,
IEquatable<IPoint3D>
IEquatable<IPoint3D>, ISpanFormattable
{
internal int m_X;
internal int m_Y;
@ -70,8 +70,6 @@ public struct Point3D
m_Z = z;
}
public override string ToString() => $"({m_X}, {m_Y}, {m_Z})";
public bool Equals(Point3D other) => m_X == other.m_X && m_Y == other.m_Y && m_Z == other.m_Z;
public bool Equals(IPoint3D other) =>
@ -164,4 +162,25 @@ public struct Point3D
return m_Z.CompareTo(other.Z);
}
public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider provider)
=> destination.TryWrite(provider, $"({m_X}, {m_Y}, {m_Z})", out charsWritten);
public override string ToString()
{
// Maximum number of characters that are needed to represent this:
// 6 characters for (, , )
// Up to 11 characters to represent each integer
const int maxLength = 6 + 11 * 3;
Span<char> span = stackalloc char[maxLength];
TryFormat(span, out var charsWritten, null, null);
return span[..charsWritten].ToString();
}
public string ToString(string format, IFormatProvider formatProvider)
{
// format and formatProvider are not doing anything right now, so use the
// default ToString implementation.
return ToString();
}
}