Created
April 10, 2023 09:43
-
-
Save ufcpp/6c7d153497be7fd1bc1d5bce1fd17fa1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Buffers.Text; | |
using System.Diagnostics.CodeAnalysis; | |
using System.Runtime.InteropServices; | |
var x = 0x12345678; | |
Console.WriteLine($"{x.Hex()}"); | |
public static class Format | |
{ | |
public static AsciiBuffer8 Hex(this int x) | |
{ | |
AsciiBuffer8 buffer = default; | |
Utf8Formatter.TryFormat(x, buffer.AsSpan(), out _, new('x', 8)); | |
return buffer; | |
} | |
} | |
/// <summary> | |
/// 8-character ASCII buffer. | |
/// </summary> | |
public struct AsciiBuffer8 : ISpanFormattable | |
{ | |
private ulong _buffer; | |
[UnscopedRef] | |
public Span<byte> AsSpan() => MemoryMarshal.AsBytes(new Span<ulong>(ref _buffer)); | |
public readonly string ToString(string? format, IFormatProvider? formatProvider) | |
=> string.Create(8, this, Format); | |
public readonly bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider? provider) | |
{ | |
if (destination.Length < 8) | |
{ | |
charsWritten = 0; | |
return false; | |
} | |
Format(destination, this); | |
charsWritten = 8; | |
return true; | |
} | |
private static void Format(Span<char> destination, AsciiBuffer8 buffer) | |
{ | |
var span = buffer.AsSpan(); | |
for (int i = 0; i < span.Length; ++i) | |
destination[i] = (char)span[i]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment