1 // Copyright 2019 the V8 project 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 #ifndef V8_OBJECTS_INTERNAL_INDEX_H_ 6 #define V8_OBJECTS_INTERNAL_INDEX_H_ 7 8 #include <stdint.h> 9 10 #include <limits> 11 12 #include "src/base/logging.h" 13 14 namespace v8 { 15 namespace internal { 16 17 // Simple wrapper around an entry (which is notably different from "index" for 18 // dictionary backing stores). Most code should treat this as an opaque 19 // wrapper: get it via GetEntryForIndex, pass it on to consumers. 20 class InternalIndex { 21 public: InternalIndex(size_t raw)22 explicit constexpr InternalIndex(size_t raw) : entry_(raw) {} NotFound()23 static InternalIndex NotFound() { return InternalIndex(kNotFound); } 24 adjust_down(size_t subtract)25 V8_WARN_UNUSED_RESULT InternalIndex adjust_down(size_t subtract) const { 26 DCHECK_GE(entry_, subtract); 27 return InternalIndex(entry_ - subtract); 28 } adjust_up(size_t add)29 V8_WARN_UNUSED_RESULT InternalIndex adjust_up(size_t add) const { 30 DCHECK_LT(entry_, std::numeric_limits<size_t>::max() - add); 31 return InternalIndex(entry_ + add); 32 } 33 is_found()34 bool is_found() const { return entry_ != kNotFound; } is_not_found()35 bool is_not_found() const { return entry_ == kNotFound; } 36 raw_value()37 size_t raw_value() const { return entry_; } as_uint32()38 uint32_t as_uint32() const { 39 DCHECK_LE(entry_, std::numeric_limits<uint32_t>::max()); 40 return static_cast<uint32_t>(entry_); 41 } as_int()42 constexpr int as_int() const { 43 DCHECK_GE(std::numeric_limits<int>::max(), entry_); 44 return static_cast<int>(entry_); 45 } 46 47 bool operator==(const InternalIndex& other) const { 48 return entry_ == other.entry_; 49 } 50 51 // Iteration support. 52 InternalIndex operator*() { return *this; } 53 bool operator!=(const InternalIndex& other) const { 54 return entry_ != other.entry_; 55 } 56 InternalIndex& operator++() { 57 entry_++; 58 return *this; 59 } 60 61 bool operator<(const InternalIndex& other) const { 62 return entry_ < other.entry_; 63 } 64 65 class Range { 66 public: Range(size_t max)67 explicit Range(size_t max) : min_(0), max_(max) {} Range(size_t min,size_t max)68 Range(size_t min, size_t max) : min_(min), max_(max) {} 69 begin()70 InternalIndex begin() { return InternalIndex(min_); } end()71 InternalIndex end() { return InternalIndex(max_); } 72 73 private: 74 size_t min_; 75 size_t max_; 76 }; 77 78 private: 79 static const size_t kNotFound = std::numeric_limits<size_t>::max(); 80 81 size_t entry_; 82 }; 83 84 } // namespace internal 85 } // namespace v8 86 87 #endif // V8_OBJECTS_INTERNAL_INDEX_H_ 88