summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
author Alex Light <allight@google.com> 2019-09-11 14:45:31 -0700
committer Treehugger Robot <treehugger-gerrit@google.com> 2019-09-12 17:29:44 +0000
commitd6fa4f24eae85b97c13728b846c430a8464839ee (patch)
tree0e392007f44abbedba3aa8452c74fe5391dc9260
parent4fb71cc45b056b862680e2fecff55f855bd57795 (diff)
Add some helper functions/constructors to ArraySlice
The ArraySlice has some nice functions for dealing with arrays. Add helper constructors to make an ArraySlice out of the commonly used LengthPrefixedArray and their pointers. Also add some convenience things such as getting the offset of an element and tightening the Contains check to ensure that the input is properly aligned. Test: ./test.py --host Bug: 140891089 Change-Id: If8350c5716db943d86cae32ed7b17aa8f036c978
-rw-r--r--libartbase/base/array_slice.h21
1 files changed, 20 insertions, 1 deletions
diff --git a/libartbase/base/array_slice.h b/libartbase/base/array_slice.h
index fb3da6b476..4679146ca1 100644
--- a/libartbase/base/array_slice.h
+++ b/libartbase/base/array_slice.h
@@ -20,6 +20,7 @@
#include "bit_utils.h"
#include "casts.h"
#include "iteration_range.h"
+#include "length_prefixed_array.h"
#include "stride_iterator.h"
namespace art {
@@ -55,6 +56,14 @@ class ArraySlice {
DCHECK(array_ != nullptr || length == 0);
}
+ ArraySlice(LengthPrefixedArray<T>* lpa,
+ size_t element_size = sizeof(T),
+ size_t alignment = alignof(T))
+ : ArraySlice(
+ lpa != nullptr && lpa->size() != 0 ? &lpa->At(0, element_size, alignment) : nullptr,
+ lpa != nullptr ? lpa->size() : 0,
+ element_size) {}
+
// Iterators.
iterator begin() { return iterator(&AtUnchecked(0), element_size_); }
const_iterator begin() const { return const_iterator(&AtUnchecked(0), element_size_); }
@@ -130,7 +139,17 @@ class ArraySlice {
}
bool Contains(const T* element) const {
- return &AtUnchecked(0) <= element && element < &AtUnchecked(size_);
+ return &AtUnchecked(0) <= element && element < &AtUnchecked(size_) &&
+ ((reinterpret_cast<uintptr_t>(element) -
+ reinterpret_cast<uintptr_t>(&AtUnchecked(0))) % element_size_) == 0;
+ }
+
+ size_t OffsetOf(const T* element) const {
+ DCHECK(Contains(element));
+ // Since it's possible element_size_ != sizeof(T) we cannot just use pointer arithmatic
+ uintptr_t base_ptr = reinterpret_cast<uintptr_t>(&AtUnchecked(0));
+ uintptr_t obj_ptr = reinterpret_cast<uintptr_t>(element);
+ return (obj_ptr - base_ptr) / element_size_;
}
private: