1 // Copyright 2017 The Chromium 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 "base/containers/vector_buffer.h"
6 
7 #include "base/test/copy_only_int.h"
8 #include "base/test/move_only_int.h"
9 #include "testing/gtest/include/gtest/gtest.h"
10 
11 namespace base {
12 namespace internal {
13 
TEST(VectorBuffer,DeletePOD)14 TEST(VectorBuffer, DeletePOD) {
15   constexpr int size = 10;
16   VectorBuffer<int> buffer(size);
17   for (int i = 0; i < size; i++)
18     buffer.begin()[i] = i + 1;
19 
20   buffer.DestructRange(buffer.begin(), buffer.end());
21 
22   // Delete should do nothing.
23   for (int i = 0; i < size; i++)
24     EXPECT_EQ(i + 1, buffer.begin()[i]);
25 }
26 
TEST(VectorBuffer,DeleteMoveOnly)27 TEST(VectorBuffer, DeleteMoveOnly) {
28   constexpr int size = 10;
29   VectorBuffer<MoveOnlyInt> buffer(size);
30   for (int i = 0; i < size; i++)
31     new (buffer.begin() + i) MoveOnlyInt(i + 1);
32 
33   buffer.DestructRange(buffer.begin(), buffer.end());
34 
35   // Delete should have reset all of the values to 0.
36   for (int i = 0; i < size; i++)
37     EXPECT_EQ(0, buffer.begin()[i].data());
38 }
39 
TEST(VectorBuffer,PODMove)40 TEST(VectorBuffer, PODMove) {
41   constexpr int size = 10;
42   VectorBuffer<int> dest(size);
43 
44   VectorBuffer<int> original(size);
45   for (int i = 0; i < size; i++)
46     original.begin()[i] = i + 1;
47 
48   original.MoveRange(original.begin(), original.end(), dest.begin());
49   for (int i = 0; i < size; i++)
50     EXPECT_EQ(i + 1, dest.begin()[i]);
51 }
52 
TEST(VectorBuffer,MovableMove)53 TEST(VectorBuffer, MovableMove) {
54   constexpr int size = 10;
55   VectorBuffer<MoveOnlyInt> dest(size);
56 
57   VectorBuffer<MoveOnlyInt> original(size);
58   for (int i = 0; i < size; i++)
59     new (original.begin() + i) MoveOnlyInt(i + 1);
60 
61   original.MoveRange(original.begin(), original.end(), dest.begin());
62 
63   // Moving from a MoveOnlyInt resets to 0.
64   for (int i = 0; i < size; i++) {
65     EXPECT_EQ(0, original.begin()[i].data());
66     EXPECT_EQ(i + 1, dest.begin()[i].data());
67   }
68 }
69 
TEST(VectorBuffer,CopyToMove)70 TEST(VectorBuffer, CopyToMove) {
71   constexpr int size = 10;
72   VectorBuffer<CopyOnlyInt> dest(size);
73 
74   VectorBuffer<CopyOnlyInt> original(size);
75   for (int i = 0; i < size; i++)
76     new (original.begin() + i) CopyOnlyInt(i + 1);
77 
78   original.MoveRange(original.begin(), original.end(), dest.begin());
79 
80   // The original should have been destructed, which should reset the value to
81   // 0. Technically this dereferences the destructed object.
82   for (int i = 0; i < size; i++) {
83     EXPECT_EQ(0, original.begin()[i].data());
84     EXPECT_EQ(i + 1, dest.begin()[i].data());
85   }
86 }
87 
88 }  // namespace internal
89 }  // namespace base
90