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
diff --git a/libartbase/base/array_slice.h b/libartbase/base/array_slice.h
index fb3da6b..4679146 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 @@
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 @@
}
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: