Skip to content

Instantly share code, notes, and snippets.

@buybackoff
Created February 22, 2019 13:00
Show Gist options
  • Save buybackoff/ded4fcceeacf42a377cd17a81c7c1c1f to your computer and use it in GitHub Desktop.
Save buybackoff/ded4fcceeacf42a377cd17a81c7c1c1f to your computer and use it in GitHub Desktop.
Fixed-size struct without unsafe keyword, using "safe" S.R.CS.Unsafe
[StructLayout(LayoutKind.Sequential, Size = Size)]
public struct Test
{
public const int Size = 32;
public byte this[int idx] => Unsafe.AddByteOffset(ref Unsafe.As<Test, byte>(ref Unsafe.AsRef(in this)), (IntPtr)idx);
public override string ToString()
{
Span<byte> bytes = stackalloc byte[Size];
for (int i = 0; i < Size; i++)
{
var b = this[i];
if (b == 0)
{
bytes = bytes.Slice(0, i);
break;
}
bytes[i] = b;
}
// coule be UTF16, ASCII, etc
// also see https://github.com/Spreads/Spreads/blob/master/src/Spreads.Core/DataTypes/Symbol.cs
return Encoding.UTF8.GetString(bytes);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment