forked from Lephenixnoir/hex-editor
45 lines
1.6 KiB
C
45 lines
1.6 KiB
C
// buffer: A resizable buffer
|
|
//
|
|
// This utility provides an interface for a RAM buffer that can grow and
|
|
// shrink, allocates its size in multiples of a reasonably-large block size,
|
|
// and avoids reallocation when possible.
|
|
|
|
#pragma once
|
|
#include <stdbool.h>
|
|
#include <sys/types.h>
|
|
|
|
// Buffer type //
|
|
|
|
typedef struct {
|
|
/* Pointer to memory. The buffer is of size `mem_size`. The first
|
|
`data_size` bytes hold the buffer data; the rest has undefined value. */
|
|
void *mem;
|
|
size_t mem_size;
|
|
size_t data_size;
|
|
/* Allocation parameter: block size */
|
|
int block_size;
|
|
} buffer_t;
|
|
|
|
// Buffer API //
|
|
|
|
/* Create a new buffer of size `initial_size`. Memory is allocated in blocks of
|
|
size `block_size`, to avoid reallocating all the time. The buffer memory is
|
|
not initialized. */
|
|
buffer_t *buffer_create(size_t initial_size, int block_size);
|
|
|
|
/* Resize the buffer's data to a given size. This can cause the mem array to
|
|
expand or shrink depending on the block size. When expanding, the data is
|
|
kept unchanged. When shrinking, data beyond the new size is lost. */
|
|
bool buffer_resize(buffer_t *b, size_t new_mem_size);
|
|
|
|
/* Write into the buffer. For simple writes, the `mem` attribute can be used
|
|
directly. This function allows a segment of the buffer to be replaced by a
|
|
segment of different size, resulting in data movement and possibly a
|
|
reallocation. */
|
|
bool buffer_write(buffer_t *b,
|
|
void *data, size_t data_size, /* Source */
|
|
off_t offset, size_t segment_size); /* Destination */
|
|
|
|
/* Free a buffer, including `b` itself. */
|
|
void buffer_free(buffer_t *b);
|