2 * Copyright 2018 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 //#define LOG_NDEBUG 0
18 #define LOG_TAG "audio_utils_string_tests"
20 #include <audio_utils/string.h>
21 #include <gtest/gtest.h>
23 // fills the string buffer with a increasing ramp of values from start.
24 template <size_t size>
25 void fill(char (&s)[size], int start) {
26 for (size_t i = 0; i < size - 1; ++i) {
32 // checks that the fill counts from start, as expected to actual chars,
33 // whereupon the rest is expected to be zeroes.
34 template <size_t size>
35 void check(char (&s)[size], int start, size_t actual) {
36 size_t lim = std::min(actual, size);
40 for (; i < lim - 1; ++i) {
41 EXPECT_EQ(start, s[i]);
45 for (; i < size; ++i) {
50 TEST(audio_utils_string, check_zero_fill) {
51 // we use string arrays whose size is known by compiler, not vectors
52 constexpr size_t STRING_SIZE = 50;
54 char dst[STRING_SIZE];
55 char dst_mirror[STRING_SIZE + 10]; // verifier that we don't overwrite
57 char over[sizeof(dst) + 5];
58 char under[sizeof(dst) - 5];
60 // fill with a value ramp
61 constexpr int DST_START = 1;
62 constexpr int OVER_START = 2;
63 constexpr int UNDER_START = 3;
64 fill(dst_mirror, DST_START);
65 fill(over, OVER_START);
66 fill(under, UNDER_START);
68 // union should overlay dst and dst_mirror.
69 dst[sizeof(dst) - 1] = 0;
70 check(dst, DST_START, sizeof(dst));
71 EXPECT_EQ(sizeof(dst) + DST_START, dst_mirror[sizeof(dst)]);
73 // make sure we truncate when copying a larger string.
74 audio_utils_strlcpy_zerofill(dst, over);
75 check(dst, OVER_START, sizeof(dst));
77 // check we didn't overwrite
78 EXPECT_EQ(sizeof(dst) + DST_START, dst_mirror[sizeof(dst)]);
80 // make sure we fill remaining buffer with zeros.
81 audio_utils_strlcpy_zerofill(dst, under);
82 check(dst, UNDER_START, sizeof(under));
84 // check we didn't overwrite
85 EXPECT_EQ(sizeof(dst) + DST_START, dst_mirror[sizeof(dst)]);