| 1 |
/* SPDX-License-Identifier: LGPL-2.1-or-later */ |
| 2 |
|
| 3 |
#include <fcntl.h> |
| 4 |
#include <stdlib.h> |
| 5 |
#include <unistd.h> |
| 6 |
|
| 7 |
#include "fd-util.h" |
| 8 |
#include "io-util.h" |
| 9 |
#include "tests.h" |
| 10 |
|
| 11 |
static void test_sparse_write_one(int fd, const char *buffer, size_t n) { |
| 12 |
char check[n]; |
| 13 |
|
| 14 |
ASSERT_OK_EQ_ERRNO(lseek(fd, 0, SEEK_SET), 0); |
| 15 |
ASSERT_OK_ERRNO(ftruncate(fd, 0)); |
| 16 |
ASSERT_OK_EQ(sparse_write(fd, buffer, n, 4), (ssize_t) n); |
| 17 |
|
| 18 |
ASSERT_OK_EQ_ERRNO(lseek(fd, 0, SEEK_CUR), (off_t) n); |
| 19 |
ASSERT_OK_ERRNO(ftruncate(fd, n)); |
| 20 |
|
| 21 |
ASSERT_OK_EQ_ERRNO(lseek(fd, 0, SEEK_SET), 0); |
| 22 |
ASSERT_OK_EQ_ERRNO(read(fd, check, n), (ssize_t) n); |
| 23 |
|
| 24 |
ASSERT_EQ(memcmp(buffer, check, n), 0); |
| 25 |
} |
| 26 |
|
| 27 |
TEST(sparse_write) { |
| 28 |
const char test_a[] = "test"; |
| 29 |
const char test_b[] = "\0\0\0\0test\0\0\0\0"; |
| 30 |
const char test_c[] = "\0\0test\0\0\0\0"; |
| 31 |
const char test_d[] = "\0\0test\0\0\0test\0\0\0\0test\0\0\0\0\0test\0\0\0test\0\0\0\0test\0\0\0\0\0\0\0\0"; |
| 32 |
const char test_e[] = "test\0\0\0\0test"; |
| 33 |
_cleanup_close_ int fd = -EBADF; |
| 34 |
char fn[] = "/tmp/sparseXXXXXX"; |
| 35 |
|
| 36 |
ASSERT_OK_ERRNO(fd = mkostemp(fn, O_CLOEXEC)); |
| 37 |
(void) unlink(fn); |
| 38 |
|
| 39 |
test_sparse_write_one(fd, test_a, sizeof(test_a)); |
| 40 |
test_sparse_write_one(fd, test_b, sizeof(test_b)); |
| 41 |
test_sparse_write_one(fd, test_c, sizeof(test_c)); |
| 42 |
test_sparse_write_one(fd, test_d, sizeof(test_d)); |
| 43 |
test_sparse_write_one(fd, test_e, sizeof(test_e)); |
| 44 |
} |
| 45 |
|
| 46 |
DEFINE_TEST_MAIN(LOG_INFO); |