def coalesce_buffers(
    buffers: list[bytes],
    target_buffer_size: int = 64 * 1024,
    small_buffer_size: int = 2048,
) -> list[bytes]:
    """Given a list of buffers, coalesce them into a new list of buffers that
    minimizes both copying and tiny writes.

    Parameters
    ----------
    buffers : list of bytes_like
    target_buffer_size : int, optional
        The target intermediate buffer size from concatenating small buffers
        together. Coalesced buffers will be no larger than approximately this size.
    small_buffer_size : int, optional
        Buffers <= this size are considered "small" and may be copied.
    """
    # Nothing to do
    if len(buffers) == 1:
        return buffers

    out_buffers: list[bytes] = []
    concat: list[bytes] = []  # A list of buffers to concatenate
    csize = 0  # The total size of the concatenated buffers

    def flush():
        nonlocal csize
        if concat:
            if len(concat) == 1:
                out_buffers.append(concat[0])
            else:
                out_buffers.append(b"".join(concat))
            concat.clear()
            csize = 0

    for b in buffers:
        size = len(b)
        if size <= small_buffer_size:
            concat.append(b)
            csize += size
            if csize >= target_buffer_size:
                flush()
        else:
            flush()
            out_buffers.append(b)
    flush()

    return out_buffers