inflate: Add helpers for using in-memory buffers

Using an in-memory buffer for the input or output data for 'inflate'
is likely to be extremely common and there's really only one way to
do it, so predefined helpers should be provided.

Change-Id: Ifd22e7b140a08e0e7dc05aec6b340dff5e2d9d0a
This commit is contained in:
Aidan MacDonald 2022-02-26 20:02:14 +00:00
parent fe4628fc30
commit ce4620413b
2 changed files with 40 additions and 0 deletions

View file

@ -43,6 +43,7 @@
#include "inflate.h"
#include <stdbool.h>
#include <string.h>
#include "adler32.h"
#include "crc32.h"
#include "system.h"
@ -757,3 +758,27 @@ int inflate(struct inflate* it, int st, inflate_reader read, void* rctx, inflate
return inflate_blocks(it, st, read, rctx, write, wctx);
}
static uint32_t inflate_buffer_rw(struct inflate_bufferctx* c,
void* dst, const void* src, uint32_t block_size)
{
size_t size_left = c->end - c->buf;
size_t copy_size = MIN((size_t)block_size, size_left);
memcpy(dst, src, copy_size);
c->buf += copy_size;
return copy_size;
}
uint32_t inflate_buffer_reader(void* block, uint32_t block_size, void* ctx)
{
struct inflate_bufferctx* c = ctx;
return inflate_buffer_rw(c, block, c->buf, block_size);
}
uint32_t inflate_buffer_writer(const void* block, uint32_t block_size, void* ctx)
{
struct inflate_bufferctx* c = ctx;
return inflate_buffer_rw(c, c->buf, block, block_size);
}

View file

@ -23,6 +23,7 @@
#define _INFLATE_H_
#include <stdint.h>
#include <stddef.h>
enum {
INFLATE_RAW,
@ -43,4 +44,18 @@ extern const uint32_t inflate_align;
// see above enum for possible options.
int inflate(struct inflate* it, int st, inflate_reader read, void* rctx, inflate_writer write, void* wctx);
struct inflate_bufferctx {
// initialize this with your input/output buffer.
// the pointer is updated as data is read or written.
void* buf;
// buffer end marker (= buf + buf_size).
void* end;
};
// reader and writer for using an in-memory buffer.
// Use 'inflate_bufferctx' as the context argument.
uint32_t inflate_buffer_reader(void* block, uint32_t block_size, void* ctx);
uint32_t inflate_buffer_writer(const void* block, uint32_t block_size, void* ctx);
#endif