1 // Copyright 2015 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.
5 #ifndef CC_BASE_RANDOM_ACCESS_LIST_CONTAINER_H_
6 #define CC_BASE_RANDOM_ACCESS_LIST_CONTAINER_H_
10 #include "base/logging.h"
11 #include "cc/base/list_container_helper.h"
15 // RandomAccessListContainer is a container similar to ListContainer (see
16 // list_container.h), but it allows random access into its elements via
17 // operator[]. In order to have efficient support for random access, some
18 // functionality is not available for RandomAccessListContainers, such as
19 // insert/deletes in the middle of the list.
20 template <class BaseElementType
>
21 class RandomAccessListContainer
{
23 // BaseElementType is the type of raw pointers this class hands out; however,
24 // its derived classes might require different memory sizes.
25 // max_size_for_derived_class the largest memory size required for all the
26 // derived classes to use for allocation.
27 explicit RandomAccessListContainer(size_t max_size_for_derived_class
)
28 : helper_(max_size_for_derived_class
) {}
30 // This constructor reserves the requested memory up front so only a single
31 // allocation is needed. When num_of_elements_to_reserve_for is zero, use the
33 RandomAccessListContainer(size_t max_size_for_derived_class
,
34 size_t num_of_elements_to_reserve_for
)
35 : helper_(max_size_for_derived_class
, num_of_elements_to_reserve_for
) {
36 items_
.reserve(num_of_elements_to_reserve_for
);
39 ~RandomAccessListContainer() {
40 for (BaseElementType
* item
: items_
)
41 item
->~BaseElementType();
45 for (BaseElementType
* item
: items_
)
46 item
->~BaseElementType();
51 bool empty() const { return helper_
.empty(); }
52 size_t size() const { return helper_
.size(); }
53 size_t GetCapacityInBytes() const { return helper_
.GetCapacityInBytes(); }
55 template <typename DerivedElementType
>
56 DerivedElementType
* AllocateAndConstruct() {
58 new (helper_
.Allocate(sizeof(DerivedElementType
))) DerivedElementType
;
59 items_
.push_back(value
);
64 items_
.back()->~BaseElementType();
69 const BaseElementType
* operator[](size_t index
) const {
71 DCHECK_LT(index
, items_
.size());
75 BaseElementType
* operator[](size_t index
) {
77 DCHECK_LT(index
, items_
.size());
81 // Note that although BaseElementType objects can change, the pointer itself
82 // (in the vector) cannot. So this class only supports a const iterator.
83 using ConstIterator
= typename
std::vector
<BaseElementType
*>::const_iterator
;
84 ConstIterator
begin() const { return items_
.begin(); }
85 ConstIterator
end() const { return items_
.end(); }
88 ListContainerHelper helper_
;
89 std::vector
<BaseElementType
*> items_
;
94 #endif // CC_BASE_RANDOM_ACCESS_LIST_CONTAINER_H_