blob: 82176e376de3b619a2ad25e3969b7849e019e43e [file] [log] [blame]
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
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
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16
17#ifndef ART_RUNTIME_LENGTH_PREFIXED_ARRAY_H_
18#define ART_RUNTIME_LENGTH_PREFIXED_ARRAY_H_
19
20#include <stddef.h> // for offsetof()
21
22#include "linear_alloc.h"
23#include "stride_iterator.h"
24#include "base/iteration_range.h"
25
26namespace art {
27
28template<typename T>
29class LengthPrefixedArray {
30 public:
31 explicit LengthPrefixedArray(uint64_t length) : length_(length) {}
32
33 T& At(size_t index, size_t element_size = sizeof(T)) {
34 DCHECK_LT(index, length_);
35 return *reinterpret_cast<T*>(&data_[0] + index * element_size);
36 }
37
38 StrideIterator<T> Begin(size_t element_size = sizeof(T)) {
39 return StrideIterator<T>(reinterpret_cast<T*>(&data_[0]), element_size);
40 }
41
42 StrideIterator<T> End(size_t element_size = sizeof(T)) {
43 return StrideIterator<T>(reinterpret_cast<T*>(&data_[0] + element_size * length_),
44 element_size);
45 }
46
47 static size_t OffsetOfElement(size_t index, size_t element_size = sizeof(T)) {
48 return offsetof(LengthPrefixedArray<T>, data_) + index * element_size;
49 }
50
51 static size_t ComputeSize(size_t num_elements, size_t element_size = sizeof(T)) {
52 return sizeof(LengthPrefixedArray<T>) + num_elements * element_size;
53 }
54
55 uint64_t Length() const {
56 return length_;
57 }
58
59 private:
60 uint64_t length_; // 64 bits for padding reasons.
61 uint8_t data_[0];
62};
63
64// Returns empty iteration range if the array is null.
65template<typename T>
66IterationRange<StrideIterator<T>> MakeIterationRangeFromLengthPrefixedArray(
67 LengthPrefixedArray<T>* arr, size_t element_size) {
68 return arr != nullptr ?
69 MakeIterationRange(arr->Begin(element_size), arr->End(element_size)) :
70 MakeEmptyIterationRange(StrideIterator<T>(nullptr, 0));
71}
72
73} // namespace art
74
75#endif // ART_RUNTIME_LENGTH_PREFIXED_ARRAY_H_