1#ifndef AWS_COMMON_ZERO_INL
2#define AWS_COMMON_ZERO_INL
3
4/*
5 * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License").
8 * You may not use this file except in compliance with the License.
9 * A copy of the License is located at
10 *
11 * http://aws.amazon.com/apache2.0
12 *
13 * or in the "license" file accompanying this file. This file is distributed
14 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
15 * express or implied. See the License for the specific language governing
16 * permissions and limitations under the License.
17 */
18
19#include <aws/common/stdbool.h>
20#include <aws/common/stdint.h>
21#include <aws/common/zero.h>
22#include <string.h>
23
24AWS_EXTERN_C_BEGIN
25/**
26 * Returns whether each byte is zero.
27 */
28AWS_STATIC_IMPL
29bool aws_is_mem_zeroed(const void *buf, size_t bufsize) {
30 /* Optimization idea: vectorized instructions to check more than 64 bits at a time. */
31
32 /* Check 64 bits at a time */
33 const uint64_t *buf_u64 = (const uint64_t *)buf;
34 const size_t num_u64_checks = bufsize / 8;
35 size_t i;
36 for (i = 0; i < num_u64_checks; ++i) {
37 if (buf_u64[i]) {
38 return false;
39 }
40 }
41
42 /* Update buf to where u64 checks left off */
43 buf = buf_u64 + num_u64_checks;
44 bufsize = bufsize % 8;
45
46 /* Check 8 bits at a time */
47 const uint8_t *buf_u8 = (const uint8_t *)buf;
48 for (i = 0; i < bufsize; ++i) {
49 if (buf_u8[i]) {
50 return false;
51 }
52 }
53
54 return true;
55}
56
57AWS_EXTERN_C_END
58
59#endif /* AWS_COMMON_ZERO_INL */
60