简体   繁体   English

如何复制 Memory<byte> 到 byte[] 中的特定偏移量</byte>

[英]How to copy Memory<byte> to a specific offset in byte[]

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.我正在使用异步网络 IO,我的读取缓冲区位于Memory中,我正在尝试将Memory复制到特定偏移量的字节 []中。

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.我正在寻找等效的Buffer.BlockCopy() ,但 memory 源应该是Memory<>类型或派生Span<>类型。 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;

Hopefully I'm getting what you're saying..希望我能明白你在说什么。。

So you have a buffer, Packet, and you're happy to make it a span.所以你有一个缓冲区,Packet,你很高兴把它变成一个跨度。 And it has some data in like Hello World:它有一些数据,比如 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您必须先对缓冲区进行切片并将新数据复制到切片创建的 Span 中

otherSpan.CopyTo(bufSpan.Slice(2)); //replace the ll with rr 

Console.WriteLine(Encoding.ASCII.GetString(bufSpan.ToArray())); prints "Herro World"打印“英雄世界”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM