DarkRift icon indicating copy to clipboard operation
DarkRift copied to clipboard

Add a more granular `DarkRiftWriter.CopyTo()` overload

Open noncom opened this issue 4 years ago • 0 comments

Quick Description

Please add an overload of DarkRiftWriter.CopyTo() that would accept full parametrization for all the bounds of the copy operation, for example CopyTo(byte[] destination, int sourceOffset, int destOffset, int length) or something like this.

Explanation

When writing a message it is sometimes required to get a certain segment of the written byte buffer. The simplest case would be when you write some data into the writer that starts at offset N and lasts for M bytes, and then you need to take that data, compute its MD5, and write it back to some position in the writer.

The act of getting that segment of written bytes currently requries additional unnecessary copying of the whole buffer and potentially either more further copying for getting that segment out of it, or complication/rewrite of the array-processing algorithms, where the data goes.

About the feature request

  • What the feature is: a proposal for an empowering method overload

  • How it would work: something similar to the similar overloads of https://docs.microsoft.com/en-us/dotnet/api/system.array.copy?view=net-5.0#System_Array_Copy_System_Array_System_Int32_System_Array_System_Int32_System_Int32

  • How it would benefit users: lessen the overhead by avoiding unnecessary array copying and simplify code/algorithms

  • A quick example code snippet:

    DarkRiftWriter w = ...;
    w.Write(messageHeader);
    var md5Position = w.Position;
    w.Write(md5PlaceholderWhichIs20BytesLong);
    var dataStartPosition = w.Position;
    w.Write(...all the data, serializables and such...);
    var md5Bytes = MD5.ComputeHash(w.GetBytes(dataStartPosition, w.Length - dataStartPosition));
    w.Rewrite(md5Position, md5Bytes);
    // success!
    ```
    
    
  • where GetBytes() is an extension method based on CopyTo(), something like this:

    public static byte[] GetBytes(this DarkRiftWriter w, int offset, int length) {
        var bytes = new byte[length];
        w.CopyTo(bytes, offset, 0, length);
        return bytes;
    }
    

noncom avatar Oct 27 '21 12:10 noncom