aboutsummaryrefslogtreecommitdiff
path: root/lib/util/is_memory_zero.c
blob: 3974ee2a76fcaba0e01e1948647e60ef4bc5f24c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/* SPDX-License-Identifier: LGPL-3.0-or-later */
/*
 * is_memory_zero.c
 *
 * Copyright (C) 2021 David Oberhollenzer <goliath@infraroot.at>
 */
#include "config.h"
#include "util.h"

#include <stdint.h>

#define U64THRESHOLD (128)

static bool test_u8(const unsigned char *blob, size_t size)
{
	while (size--) {
		if (*(blob++) != 0)
			return false;
	}

	return true;
}

bool is_memory_zero(const void *blob, size_t size)
{
	const sqfs_u64 *u64ptr;
	size_t diff;

	if (size < U64THRESHOLD)
		return test_u8(blob, size);

	diff = (uintptr_t)blob % sizeof(sqfs_u64);

	if (diff != 0) {
		diff = sizeof(sqfs_u64) - diff;

		if (!test_u8(blob, diff))
			return false;

		blob = (const char *)blob + diff;
		size -= diff;
	}

	u64ptr = blob;

	while (size >= sizeof(sqfs_u64)) {
		if (*(u64ptr++) != 0)
			return false;

		size -= sizeof(sqfs_u64);
	}

	return test_u8((const unsigned char *)u64ptr, size);
}