1 ///
2 /// @file   pod_vector.cpp
3 /// @brief  Plain old data vector, like std::vector but does not
4 ///         default initialize memory.
5 ///
6 /// Copyright (C) 2020 Kim Walisch, <kim.walisch@gmail.com>
7 ///
8 /// This file is distributed under the BSD License. See the COPYING
9 /// file in the top level directory.
10 ///
11 
12 #include <pod_vector.hpp>
13 
14 #include <cstdlib>
15 #include <iostream>
16 #include <random>
17 #include <numeric>
18 
19 using std::size_t;
20 using namespace primecount;
21 
check(bool OK)22 void check(bool OK)
23 {
24   std::cout << "   " << (OK ? "OK" : "ERROR") << "\n";
25   if (!OK)
26     std::exit(1);
27 }
28 
main()29 int main()
30 {
31   // The pod_vector class uses std::vector internally. For
32   // performance reasons we want vector::resize() not to
33   // free memory when resizing to a smaller size. The C++
34   // standard seems to indirectly guarantee this behavior,
35   // but it is not 100% clear. So this tests verifies this
36   // behavior.
37 
38   // Allocate from 1 KiB to 128 MiB
39   for (size_t i = 10; i <= 27; i++)
40   {
41     pod_vector<char> vect;
42     vect.resize(size_t(1) << i);
43     auto capacity1 = vect.capacity();
44     vect.resize(100);
45     auto capacity2 = vect.capacity();
46 
47     std::cout << "vect.resize(100).capacity = " << capacity1;
48     check(capacity1 == capacity2);
49   }
50 
51   std::random_device rd;
52   std::mt19937 gen(rd());
53   std::uniform_int_distribution<int> dist(10000, 20000);
54 
55   int size = dist(gen);
56   pod_vector<int> vect(size);
57   std::fill_n(&vect[0], size, 123);
58 
59   // Test if resize does not default initilize
60   vect.resize(0);
61   vect.resize(size);
62   int sum = std::accumulate(&vect[0], &vect[0] + size, 0);
63   std::cout << "Vect sum after resize: " << sum;
64   check(sum == 123 * size);
65 
66   std::cout << std::endl;
67   std::cout << "All tests passed successfully!" << std::endl;
68 
69   return 0;
70 }
71