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 CONSTEXPR_DCHECK(entry_ <= 44 static_cast<size_t>(std::numeric_limits<int>::max())); 45 return static_cast<int>(entry_); 46 } 47 48 bool operator==(const InternalIndex& other) const { 49 return entry_ == other.entry_; 50 } 51 52 // Iteration support. 53 InternalIndex operator*() { return *this; } 54 bool operator!=(const InternalIndex& other) const { 55 return entry_ != other.entry_; 56 } 57 InternalIndex& operator++() { 58 entry_++; 59 return *this; 60 } 61 62 class Range { 63 public: Range(size_t max)64 explicit Range(size_t max) : min_(0), max_(max) {} Range(size_t min,size_t max)65 Range(size_t min, size_t max) : min_(min), max_(max) {} 66 begin()67 InternalIndex begin() { return InternalIndex(min_); } end()68 InternalIndex end() { return InternalIndex(max_); } 69 70 private: 71 size_t min_; 72 size_t max_; 73 }; 74 75 private: 76 static const size_t kNotFound = std::numeric_limits<size_t>::max(); 77 78 size_t entry_; 79 }; 80 81 } // namespace internal 82 } // namespace v8 83 84 #endif // V8_OBJECTS_INTERNAL_INDEX_H_ 85