| 1 |
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- |
| 2 |
* vim: set ts=8 sts=2 et sw=2 tw=80: |
| 3 |
* This Source Code Form is subject to the terms of the Mozilla Public |
| 4 |
* License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 6 |
|
| 7 |
#ifndef jit_FixedList_h |
| 8 |
#define jit_FixedList_h |
| 9 |
|
| 10 |
#include "mozilla/Assertions.h" |
| 11 |
#include "mozilla/Likely.h" |
| 12 |
|
| 13 |
#include <stddef.h> |
| 14 |
|
| 15 |
#include "jit/JitAllocPolicy.h" |
| 16 |
#include "js/Utility.h" |
| 17 |
|
| 18 |
namespace js { |
| 19 |
namespace jit { |
| 20 |
|
| 21 |
// List of a fixed length, but the length is unknown until runtime. |
| 22 |
template <typename T> |
| 23 |
class FixedList { |
| 24 |
T* list_; |
| 25 |
size_t length_; |
| 26 |
|
| 27 |
private: |
| 28 |
FixedList(const FixedList&); // no copy definition. |
| 29 |
void operator=(const FixedList*); // no assignment definition. |
| 30 |
|
| 31 |
public: |
| 32 |
FixedList() : list_(nullptr), length_(0) {} |
| 33 |
|
| 34 |
// Dynamic memory allocation requires the ability to report failure. |
| 35 |
[[nodiscard]] bool init(TempAllocator& alloc, size_t length) { |
| 36 |
if (length == 0) { |
| 37 |
return true; |
| 38 |
} |
| 39 |
|
| 40 |
list_ = alloc.allocateArray<T>(length); |
| 41 |
if (!list_) { |
| 42 |
return false; |
| 43 |
} |
| 44 |
|
| 45 |
length_ = length; |
| 46 |
return true; |
| 47 |
} |
| 48 |
|
| 49 |
size_t empty() const { return length_ == 0; } |
| 50 |
|
| 51 |
size_t length() const { return length_; } |
| 52 |
|
| 53 |
void shrink(size_t num) { |
| 54 |
MOZ_ASSERT(num < length_); |
| 55 |
length_ -= num; |
| 56 |
} |
| 57 |
|
| 58 |
[[nodiscard]] bool growBy(TempAllocator& alloc, size_t num) { |
| 59 |
size_t newlength = length_ + num; |
| 60 |
if (newlength < length_) { |
| 61 |
return false; |
| 62 |
} |
| 63 |
size_t bytes; |
| 64 |
if (MOZ_UNLIKELY(!CalculateAllocSize<T>(newlength, &bytes))) { |
| 65 |
return false; |
| 66 |
} |
| 67 |
T* list = (T*)alloc.allocate(bytes); |
| 68 |
if (MOZ_UNLIKELY(!list)) { |
| 69 |
return false; |
| 70 |
} |
| 71 |
|
| 72 |
for (size_t i = 0; i < length_; i++) { |
| 73 |
list[i] = list_[i]; |
| 74 |
} |
| 75 |
|
| 76 |
length_ += num; |
| 77 |
list_ = list; |
| 78 |
return true; |
| 79 |
} |
| 80 |
|
| 81 |
T& operator[](size_t index) { |
| 82 |
MOZ_ASSERT(index < length_); |
| 83 |
return list_[index]; |
| 84 |
} |
| 85 |
const T& operator[](size_t index) const { |
| 86 |
MOZ_ASSERT(index < length_); |
| 87 |
return list_[index]; |
| 88 |
} |
| 89 |
|
| 90 |
T* data() { return list_; } |
| 91 |
|
| 92 |
T* begin() { return list_; } |
| 93 |
T* end() { return list_ + length_; } |
| 94 |
}; |
| 95 |
|
| 96 |
} // namespace jit |
| 97 |
} // namespace js |
| 98 |
|
| 99 |
#endif /* jit_FixedList_h */ |