/* Tests for struct alloc_buffer.
Copyright (C) 2017-2022 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<https://www.gnu.org/licenses/>. */
#include <arpa/inet.h>
#include <alloc_buffer.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <support/check.h>
#include <support/support.h>
#include <support/test-driver.h>
/* Return true if PTR is sufficiently aligned for TYPE. */
#define IS_ALIGNED(ptr, type) \
((((uintptr_t) ptr) & (__alloc_buffer_assert_align (__alignof (type)) - 1)) \
== 0)
/* Structure with non-power-of-two size. */
struct twelve
{
uint32_t buffer[3] __attribute__ ((aligned (4)));
};
_Static_assert (sizeof (struct twelve) == 12, "struct twelve");
_Static_assert (__alignof__ (struct twelve) == 4, "struct twelve");
/* Check for success obtaining empty arrays. Does not assume the
buffer is empty. */
static void
test_empty_array (struct alloc_buffer refbuf)
{
bool refbuf_failed = alloc_buffer_has_failed (&refbuf);
if (test_verbose)
printf ("info: %s: current=0x%llx end=0x%llx refbuf_failed=%d\n",
__func__, (unsigned long long) refbuf.__alloc_buffer_current,
(unsigned long long) refbuf.__alloc_buffer_end, refbuf_failed);
{
struct alloc_buffer buf = refbuf;
TEST_VERIFY ((alloc_buffer_alloc_bytes (&buf, 0) == NULL)
== refbuf_failed);
TEST_VERIFY (alloc_buffer_has_failed (&buf) == refbuf_failed);
}
{
struct alloc_buffer buf = refbuf;
TEST_VERIFY ((alloc_buffer_alloc_array (&buf, char, 0) == NULL)
== refbuf_failed);
TEST_VERIFY (alloc_buffer_has_failed (&buf) == refbuf_failed);
}
/* The following tests can fail due to the need for aligning the
returned pointer. */
{
struct alloc_buffer buf = refbuf;
bool expect_failure = refbuf_failed
|| !IS_ALIGNED (alloc_buffer_next (&buf, void), double);
double *ptr = alloc_buffer_alloc_array (&buf, double, 0);
TEST_VERIFY (IS_ALIGNED (ptr, double));
TEST_VERIFY ((ptr == NULL) == expect_failure);
TEST_VERIFY (alloc_buffer_has_failed (&buf) == expect_failure);
}
{
struct alloc_buffer buf = refbuf;
bool expect_failure = refbuf_failed
|| !IS_ALIGNED (alloc_buffer_next (&buf, void), struct twelve);
struct twelve *ptr = alloc_buffer_alloc_array (&buf, struct twelve, 0);
TEST_VERIFY (IS_ALIGNED (ptr, struct twelve));
TEST_VERIFY ((ptr == NULL) == expect_failure);
TEST_VERIFY (alloc_buffer_has_failed (