packet::serialize

Function try_reuse_buffer

Source
pub fn try_reuse_buffer<B: GrowBufferMut + ShrinkBuffer>(
    buffer: B,
    prefix: usize,
    suffix: usize,
    max_copy_bytes: usize,
) -> Result<B, B>
Expand description

Attempts to reuse a buffer for the purposes of implementing BufferProvider::reuse_or_realloc.

try_reuse_buffer attempts to reuse an existing buffer to satisfy the given prefix and suffix constraints. If it succeeds, it returns Ok containing a buffer with the same body as the input, and with at least prefix prefix bytes and at least suffix suffix bytes. Otherwise, it returns Err containing the original, unmodified input buffer.

Concretely, try_reuse_buffer has the following behavior:

  • If the prefix and suffix constraints are already met, it returns Ok with the input unmodified
  • If the prefix and suffix constraints are not yet met, then…
    • If there is enough capacity to meet the constraints and the body is not larger than max_copy_bytes, the body will be moved within the buffer in order to meet the constraints, and it will be returned
    • Otherwise, if there is not enough capacity or the body is larger than max_copy_bytes, it returns Err with the input unmodified

max_copy_bytes is meant to be an estimate of how many bytes can be copied before allocating a new buffer will be cheaper than copying.