I have been experimenting with Span<T>
as part of ReadOnlySequence<T>
and System.IO.Pipelines.
I am currently trying to obtain a Span<T>
over a struct
without using unsafe
code and without making a copy of that struct
.
My struct is simply:
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)]
public struct Packet
{
public byte TestByte;
}
Method 1 - which works - but feels "unsafe"
//
// Method 1 - uses Unsafe to get a span over the struct
//
var packet = new Packet();
unsafe
{
var packetSpan = new Span<byte>(&packet, Marshal.SizeOf(packet));
packetSpan[0] = 0xFF; // Set the test byte
Debug.Assert(packet.TestByte == 0xFF, "Error, packetSpan did not update packet.");
// ^^^ Succeeds
packet.TestByte = 0xEE;
Debug.Assert(packetSpan[0] == 0xEE, "Error, packet did not update packetSpan.");
// ^^^ Succeeds
}
Method 2 - which doesn't work as intended as it requires a copy
//
// Method 2
//
// This doesn't work as intended because the original packet is actually
// coppied to packet2Array because it's a value type
//
// Coppies the packet to an Array of Packets
// Gets a Span<Packet> of the Array of Packets
// Casts the Span<Packet> as a Span<byte>
//
var packet2 = new Packet();
// create an array and store a copy of packet2 in it
Packet[] packet2Array = new Packet[1];
packet2Array[0] = packet2;
// Get a Span<Packet> of the packet2Array
Span<Packet> packet2SpanPacket = MemoryExtensions.AsSpan<Packet>(packet2Array);
// Cast the Span<Packet> as a Span<byte>
Span<byte> packet2Span = MemoryMarshal.Cast<Packet, byte>(packet2SpanPacket);
packet2Span[0] = 0xFF; // Set the test byte
Debug.Assert(packet2.TestByte == 0xFF, "Error, packet2Span did not update packet2");
// ^^^ fails because packet2 was coppied into the array, and thus packet2 has not changed.
Debug.Assert(packet2Array[0].TestByte == 0xFF, "Error, packet2Span did not update packet2Array[i]");
// ^^^ succeeds
packet2.TestByte = 0xEE;
Debug.Assert(packet2Span[0] == 0xEE, "Error, packet2 did not update in packet2Span");
// ^^^ fails because packet2Span is covering packet2Array which has a copy of packet2
packet2Array[0].TestByte = 0xEE;
Debug.Assert(packet2Span[0] == 0xEE, "Error, packet2 did not update in packet2Span");
// ^^^ succeeds
Further research shows that
Span<T>
can be implicitly cast from a byte[]
, eg, I could do
Span<byte> packetSpan = new Packet().ToByteArray();
But any current implementation of ToByteArray() I have is still making a copy of the Packet struct.
I can't do some something like:
Span<byte> packetSpan = (byte[])packet;
// ^^ Won't compile
unsafe
, because if you acquire aSpan
over all bytes of a struct you can potentially alter any bit in that struct in any way - that's inherently unsafe. – Anthropomorphosis