Reputation: 593
I am using async network IO, my read buffer is in Memory, I am trying to copy the Memory into a byte[] at a specific offset.
public bool Append(Memory<byte> buffer)
{
// Verify input data
if (buffer.Length <= 0 ||
buffer.Length > PacketSize - Received)
{
// Debug.Assert(false);
return false;
}
// Copy received data into packet at current offset
// TODO : Avoid heap array allocation or iteration
//Buffer.BlockCopy(buffer.ToArray(), 0, Packet, Received, buffer.Length);
//private readonly byte[] Packet;
for (int i = 0; i < buffer.Length; i ++)
{
Packet[Received + i] = buffer.Span[i];
}
Received += buffer.Length;
// If we have a header it must match
if (HasHeader() && !DoesHeaderMatch())
{
// Debug.Assert(false);
return false;
}
return true;
}
I am looking for an equivalent of Buffer.BlockCopy()
, but the memory source should be of type Memory<>
or derived Span<>
type.
I do not want to create temporary stack or heap buffers.
Any ideas?
Solution:
// Copy received data into packet at current offset
Span<byte> destination = Packet.AsSpan().Slice(Received, buffer.Length);
Span<byte> source = buffer.Span;
source.CopyTo(destination);
Received += buffer.Length;
Upvotes: 1
Views: 2653
Reputation: 74605
Hopefully I'm getting what you're saying..
So you have a buffer, Packet, and you're happy to make it a span. And it has some data in like Hello World:
byte[] buf = Encoding.ASCII.GetBytes("Hello World");
var bufSpan = buf.AsSpan();
And you have some other data as another span:
byte[] otherSpan = Encoding.ASCII.GetBytes("rr").AsSpan();
And you want to write that data into the buffer at a certain location. You have to slice the buffer first and copy the new data into the Span created by the slice
otherSpan.CopyTo(bufSpan.Slice(2)); //replace the ll with rr
Console.WriteLine(Encoding.ASCII.GetString(bufSpan.ToArray()));
prints "Herro World"
Upvotes: 3