1 // Copyright (c) 2012 The Chromium OS Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #include <gtest/gtest.h> 6 7 #include "array.h" 8 9 namespace { 10 11 struct point { 12 int x, y; 13 }; 14 15 DECLARE_ARRAY_TYPE(double, double_array); 16 DECLARE_ARRAY_TYPE(struct point, point_array); 17 18 TEST(ArrayTest, Basic) { 19 double_array a = ARRAY_INIT; 20 21 /* create an array {1.0, 2.0} */ 22 ARRAY_APPEND(&a, 1.0); 23 double *p = ARRAY_APPEND_ZERO(&a); 24 EXPECT_EQ(0.0, *p); 25 *p = 2.0; 26 27 EXPECT_EQ(2, ARRAY_COUNT(&a)); 28 EXPECT_EQ(2, a.count); 29 EXPECT_GE(a.size, 2); 30 EXPECT_EQ(1.0, *ARRAY_ELEMENT(&a, 0)); 31 EXPECT_EQ(2.0, *ARRAY_ELEMENT(&a, 1)); 32 EXPECT_EQ(1.0, a.element[0]); 33 EXPECT_EQ(2.0, a.element[1]); 34 EXPECT_EQ(0, ARRAY_FIND(&a, 1.0)); 35 EXPECT_EQ(1, ARRAY_FIND(&a, 2.0)); 36 EXPECT_EQ(-1, ARRAY_FIND(&a, 0.0)); 37 EXPECT_EQ(0, ARRAY_INDEX(&a, ARRAY_ELEMENT(&a, 0))); 38 EXPECT_EQ(1, ARRAY_INDEX(&a, ARRAY_ELEMENT(&a, 1))); 39 40 ARRAY_FREE(&a); 41 EXPECT_EQ(0, ARRAY_COUNT(&a)); 42 EXPECT_EQ(0, a.count); 43 EXPECT_EQ(0, a.size); 44 EXPECT_EQ(NULL, a.element); 45 } 46 47 TEST(ArrayTest, StructElement) { 48 struct point p = {1, 2}; 49 struct point q = {3, 4}; 50 point_array a = ARRAY_INIT; 51 52 ARRAY_APPEND(&a, p); 53 ARRAY_APPEND(&a, q); 54 55 EXPECT_EQ(2, ARRAY_COUNT(&a)); 56 EXPECT_EQ(1, ARRAY_ELEMENT(&a, 0)->x); 57 EXPECT_EQ(2, ARRAY_ELEMENT(&a, 0)->y); 58 EXPECT_EQ(3, a.element[1].x); 59 EXPECT_EQ(4, a.element[1].y); 60 ARRAY_ELEMENT(&a, 1)->y = 5; 61 EXPECT_EQ(5, a.element[1].y); 62 63 ARRAY_FREE(&a); 64 EXPECT_EQ(0, ARRAY_COUNT(&a)); 65 EXPECT_EQ(0, a.size); 66 EXPECT_EQ(NULL, a.element); 67 } 68 69 TEST(ArrayTest, AppendZeroStruct) { 70 point_array a = ARRAY_INIT; 71 struct point *p, *q; 72 73 p = ARRAY_APPEND_ZERO(&a); 74 EXPECT_EQ(0, p->x); 75 EXPECT_EQ(0, p->y); 76 EXPECT_EQ(1, a.count); 77 78 q = ARRAY_APPEND_ZERO(&a); 79 EXPECT_EQ(0, q->x); 80 EXPECT_EQ(0, q->y); 81 EXPECT_EQ(2, a.count); 82 83 ARRAY_FREE(&a); 84 } 85 86 TEST(ArrayTest, ForLoop) { 87 int i; 88 double *p; 89 double_array a = ARRAY_INIT; 90 91 for (i = 0; i < 100; i++) { 92 ARRAY_APPEND(&a, i * 2); 93 } 94 95 int expectedIndex = 0; 96 double expectedValue = 0; 97 FOR_ARRAY_ELEMENT(&a, i, p) { 98 EXPECT_EQ(expectedIndex, i); 99 EXPECT_EQ(expectedValue, *p); 100 expectedIndex++; 101 expectedValue += 2; 102 } 103 EXPECT_EQ(expectedIndex, 100); 104 105 ARRAY_FREE(&a); 106 EXPECT_EQ(0, a.count); 107 EXPECT_EQ(0, a.size); 108 EXPECT_EQ(NULL, a.element); 109 } 110 111 } // namespace 112 113 int main(int argc, char **argv) { 114 ::testing::InitGoogleTest(&argc, argv); 115 return RUN_ALL_TESTS(); 116 } 117