Source code

Revision control

Other Tools

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 ds_FixedLengthVector_h
8
#define ds_FixedLengthVector_h
9
10
#include "mozilla/Assertions.h" // MOZ_ASSERT
11
#include "mozilla/Attributes.h" // MOZ_MUST_USE
12
#include "mozilla/OperatorNewExtensions.h" // mozilla::KnownNotNull
13
14
#include <stddef.h> // size_t
15
16
#include "js/Utility.h" // js_free
17
#include "vm/JSContext.h" // JSContext
18
19
namespace js {
20
21
// A dynamically-allocated fixed-length vector with bounds checking assertions.
22
template <typename T>
23
class FixedLengthVector {
24
// The pointer to the storage.
25
T* data_ = nullptr;
26
27
// The size of the storage.
28
size_t length_ = 0;
29
30
public:
31
FixedLengthVector() {}
32
33
FixedLengthVector(FixedLengthVector&) = delete;
34
FixedLengthVector(FixedLengthVector&&) = default;
35
36
~FixedLengthVector() {
37
if (initialized()) {
38
js_free(data_);
39
}
40
}
41
42
size_t length() const { return length_; }
43
44
bool initialized() const { return !!data_; }
45
46
// Allocate the storage with the given size, wihtout calling constructor.
47
//
48
// If the allocation fails, this returns false and sets the
49
// pending exception on the given context.
50
MOZ_MUST_USE bool allocateUninitialized(JSContext* cx, size_t length) {
51
MOZ_ASSERT(!initialized());
52
53
length_ = length;
54
data_ = cx->pod_malloc<T>(length);
55
if (MOZ_UNLIKELY(!data_)) {
56
return false;
57
}
58
59
return true;
60
}
61
62
// Allocate the storage with the given size and call default constructor.
63
//
64
// If the allocation fails, this returns false and sets the
65
// pending exception on the given context.
66
MOZ_MUST_USE bool allocate(JSContext* cx, size_t length) {
67
if (!allocateUninitialized(cx, length)) {
68
return false;
69
}
70
71
for (size_t i = 0; i < length; i++) {
72
new (mozilla::KnownNotNull, &data_[i]) T();
73
}
74
return true;
75
}
76
77
T* begin() {
78
MOZ_ASSERT(initialized());
79
return data_;
80
}
81
82
const T* begin() const {
83
MOZ_ASSERT(initialized());
84
return data_;
85
}
86
87
T* end() {
88
MOZ_ASSERT(initialized());
89
return data_ + length_;
90
}
91
92
const T* end() const {
93
MOZ_ASSERT(initialized());
94
return data_ + length_;
95
}
96
97
T& operator[](size_t index) {
98
MOZ_ASSERT(initialized());
99
MOZ_ASSERT(index < length_);
100
return begin()[index];
101
}
102
103
const T& operator[](size_t index) const {
104
MOZ_ASSERT(initialized());
105
MOZ_ASSERT(index < length_);
106
return begin()[index];
107
}
108
};
109
110
} // namespace js
111
112
#endif // ds_FixedLengthVector_h