Function sequoia_openpgp_ffi::io::pgp_writer_alloc_with_capacity[][src]

#[no_mangle]
pub extern "C" fn pgp_writer_alloc_with_capacity(
    buf: *mut *mut c_void,
    len: *mut size_t,
    capacity: size_t
) -> *mut Writer
Expand description

Creates an allocating writer reserving space upfront.

C Declaration

pgp_writer_t
pgp_writer_alloc_with_capacity (void **buf,
                                size_t *len,
                                size_t capacity);

Variant of pgp_writer_alloc that makes sure that the buffer can be filled up to capacity without causing a reallocation by allocating space upfront.

Errors

Returns NULL if the initial allocation failed.

Examples

#include <assert.h>
#include <stdlib.h>
#include <string.h>

#include <sequoia/openpgp.h>

/* Prepare a buffer.  */
void *buf = NULL;
size_t len = 0;

/* The allocating writer reallocates the buffer so that it grows
   if more data is written to it.  However, if we allocate enough
   space upfront, we can completely avoid the possibly costly
   reallocations.  Demonstrate that.  */
pgp_writer_t sink = pgp_writer_alloc_with_capacity (&buf, &len, 29 * 4096);
void *initial_allocation = buf;
for (int i = 0; i < 4096; i++)
    pgp_writer_write (NULL, sink,
                      (uint8_t *) "This is a string of length 29", 29);
pgp_writer_free (sink);
assert (len == 29 * 4096);
assert (memcmp (buf, "This is a string of length 29This", 29 + 4) == 0);
assert (buf == initial_allocation);
free (buf);