vaseboot/VasEBoot-core/kern/buffer.c

121 lines
2.8 KiB
C

/*
* VAS_EBOOT -- GRand Unified Bootloader
* Copyright (C) 2021 Free Software Foundation, Inc.
*
* VAS_EBOOT is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* VAS_EBOOT is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with VAS_EBOOT. If not, see <http://www.gnu.org/licenses/>.
*/
#include <VasEBoot/buffer.h>
#include <VasEBoot/err.h>
#include <VasEBoot/misc.h>
#include <VasEBoot/mm.h>
#include <VasEBoot/safemath.h>
#include <VasEBoot/types.h>
VasEBoot_buffer_t
VasEBoot_buffer_new (VasEBoot_size_t sz)
{
struct VasEBoot_buffer *ret;
ret = (struct VasEBoot_buffer *) VasEBoot_malloc (sizeof (*ret));
if (ret == NULL)
return NULL;
ret->data = (VasEBoot_uint8_t *) VasEBoot_malloc (sz);
if (ret->data == NULL)
{
VasEBoot_free (ret);
return NULL;
}
ret->sz = sz;
ret->pos = 0;
ret->used = 0;
return ret;
}
void
VasEBoot_buffer_free (VasEBoot_buffer_t buf)
{
if (buf != NULL)
{
VasEBoot_free (buf->data);
VasEBoot_free (buf);
}
}
VasEBoot_err_t
VasEBoot_buffer_ensure_space (VasEBoot_buffer_t buf, VasEBoot_size_t req)
{
VasEBoot_uint8_t *d;
VasEBoot_size_t newsz = 1;
/* Is the current buffer size adequate? */
if (buf->sz >= req)
return VAS_EBOOT_ERR_NONE;
/* Find the smallest power-of-2 size that satisfies the request. */
while (newsz < req)
{
if (newsz == 0)
return VasEBoot_error (VAS_EBOOT_ERR_OUT_OF_RANGE,
N_("requested buffer size is too large"));
newsz <<= 1;
}
d = (VasEBoot_uint8_t *) VasEBoot_realloc (buf->data, newsz);
if (d == NULL)
return VasEBoot_errno;
buf->data = d;
buf->sz = newsz;
return VAS_EBOOT_ERR_NONE;
}
void *
VasEBoot_buffer_take_data (VasEBoot_buffer_t buf)
{
void *data = buf->data;
buf->data = NULL;
buf->sz = buf->pos = buf->used = 0;
return data;
}
void
VasEBoot_buffer_reset (VasEBoot_buffer_t buf)
{
buf->pos = buf->used = 0;
}
VasEBoot_err_t
VasEBoot_buffer_advance_read_pos (VasEBoot_buffer_t buf, VasEBoot_size_t n)
{
VasEBoot_size_t newpos;
if (VasEBoot_add (buf->pos, n, &newpos))
return VasEBoot_error (VAS_EBOOT_ERR_OUT_OF_RANGE, N_("overflow is detected"));
if (newpos > buf->used)
return VasEBoot_error (VAS_EBOOT_ERR_OUT_OF_RANGE,
N_("new read is position beyond the end of the written data"));
buf->pos = newpos;
return VAS_EBOOT_ERR_NONE;
}