Kr1ptal/ethers-kt

Support pre-sizing the `RlpEncoder` buffer

Closed this issue ยท 1 comments

Module

RLP

๐Ÿ“ Description

Add support for pre-sizing the buffer to avoid re-allocating during encoding. One way to do this is to add rlpSize(): Int function to RlpEncodable interface, which returns -1 by default. Subclasses can then override this function and provide actual size of the encoded type. This size is then used in toRlp() function to create a pre-sized encoder. In RlpEncoder#toByteArray() we can then return the internal ByteBuffer buffer (buffer.array()) directly since it will be correctly sized already.

In rlpEncode functions we would also need to provide sizing information when calling encodeList/startList functions to avoid copying when encoding length of size.

Alternative implementation could be to make RlpEncoder and interface and adding a new type which would just collect type sizes on first rlpEncode call, and use that information to correctly size the actual encoder buffer. This option needs a bit more exploration to better understand if it would be feasible.

The overall goal is to keep implementing the RLP encoding for types as simple as possible, while improving performance by avoiding redundant array copying and resizing.

Another, less complex alternative: just override RlpEncodable#toRlp function where pre-sizing is desired.