Coverage Report

Created: 2026-11-11 06:15

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/trafficserver/lib/swoc/include/swoc/Vectray.h
Line
Count
Source
1
// SPDX-License-Identifier: Apache-2.0
2
// Copyright Apache Software Foundation 2019
3
/** @file
4
5
    Container that acts like a vector but has static storage to avoid memory allocation for
6
    some specified number of elements.
7
*/
8
9
#pragma once
10
11
#include <array>
12
#include <vector>
13
#include <variant>
14
#include <new>
15
#include <cstddef>
16
17
#include <swoc/MemSpan.h>
18
#include <swoc/swoc_meta.h>
19
20
namespace swoc { inline namespace SWOC_VERSION_NS {
21
22
/** Vectray provides a combination of static and dynamic storage modeled as an array.
23
 *
24
 * @tparam T Type of elements in the array.
25
 * @tparam N Number of statically allocated elements.
26
 * @tparam A Allocator.
27
 *
28
 * The goal is to provide static storage for the common case, avoiding memory allocation, while
29
 * still handling exceptional cases that need more storage. A common case is for @a N == 1 where
30
 * there is almost always a single value, but it is possible to have multiple values. @c Vectray
31
 * makes the single value case require no allocation while transparently handling the multiple
32
 * value case.
33
 *
34
 * The interface is designed to mimic that of @c std::vector.
35
 */
36
template <typename T, size_t N, class A = std::allocator<T>> class Vectray {
37
  using self_type   = Vectray;           ///< Self reference type.
38
  using vector_type = std::vector<T, A>; ///< Internal dynamic storage type.
39
40
public:                                                              // STL compliance types.
41
  using value_type      = T;                                         ///< Element type for container.
42
  using reference       = std::remove_reference<T> &;                ///< Reference to element.
43
  using const_reference = std::remove_reference<T> const &;          ///< Reference to constant element.
44
  using pointer         = std::remove_reference<T> *;                ///< Pointer to element.
45
  using const_pointer   = std::remove_reference<T> const *;          ///< Pointer to constant element.
46
  using allocator_type  = A;                                         ///< Dynamic storage allocator.
47
  using size_type       = typename vector_type::size_type;           ///< Type for element count.
48
  using difference_type = typename vector_type::difference_type;     ///< Iterator difference.
49
  using iterator        = typename swoc::MemSpan<T>::iterator;       ///< Element iteration.
50
  using const_iterator  = typename swoc::MemSpan<const T>::iterator; ///< Constant element iteration.
51
  // Need to add reverse iterators - @c reverse_iterator and @c const_reverse_iterator
52
53
  /// Internal (fixed) storage.
54
  struct FixedStore {
55
    std::array<std::byte, sizeof(T) * N> _raw; ///< Raw memory for element storage.
56
    size_t _count = 0;                         ///< Number of valid elements.
57
    allocator_type _a;                         ///< Allocator instance - used for construction.
58
59
0
    FixedStore() = default; ///< Default construct - empty.
60
61
    /** Construct with specific allocator @a a.
62
     *
63
     * @param a Allocator.
64
     */
65
    explicit FixedStore(allocator_type const &a) : _a(a) {}
66
67
    ~FixedStore();
68
69
    /// @return A span containing the valid elements.
70
    MemSpan<T> span();
71
72
    /// @return A pointer to the data.
73
    T *data();
74
75
    /// @return A pointer to the data.
76
    T const *data() const;
77
  };
78
79
  using DynamicStore = vector_type; ///< Dynamic (heap) storage.
80
81
  /// Element access.
82
  using span = swoc::MemSpan<T>;
83
  /// Constant element access.
84
  using const_span = swoc::MemSpan<T const>;
85
86
public:
87
  /// Default constructor, construct an empty container.
88
  Vectray();
89
  /// Destructor - destructs all contained elements.
90
  /// @internal The internal store takes care of the details.
91
0
  ~Vectray() = default;
92
93
  /// Construct empty instance with allocator.
94
  constexpr explicit Vectray(allocator_type const &a) : _store(std::in_place_type_t<FixedStore>{}, a) {}
95
96
  /** Construct with @a n default constructed elements.
97
   *
98
   * @param n Number of elements.
99
   * @param alloc Allocator (optional - default constructed if not a parameter).
100
   */
101
  explicit Vectray(size_type n, allocator_type const &alloc = allocator_type{});
102
103
  /// Move constructor for difference static sized instance.
104
  template <size_t M> Vectray(Vectray<T, M, A> &&that);
105
106
  /// Move constructor.
107
  Vectray(self_type &&that, allocator_type const &a);
108
109
  /// @return The number of elements in the container.
110
  size_type size() const;
111
112
  /// @return A pointer to the data.
113
  T *data();
114
115
  /// @return A pointer to the data.
116
  T const *data() const;
117
118
  /// @return @c true if no valid elements, @c false if at least one valid element.
119
  bool empty() const;
120
121
  /// Implicitly convert to a @c MemSpan.
122
  operator span() { return this->items(); }
123
  /// Implicitly convert to a @c MemSpan.
124
  operator const_span() const { return this->items(); }
125
126
  /** Index operator.
127
   *
128
   * @param idx Index of element.
129
   * @return A reference to the element.
130
   */
131
  T &operator[](size_type idx);
132
133
  /** Index operator (const).
134
   *
135
   * @param idx Index of element.
136
   * @return A @c const reference to the element.
137
   */
138
  T const &operator[](size_type idx) const;
139
140
  /// @return A reference to the first element.
141
  T const &
142
  front() const {
143
    return (*this)[0];
144
  }
145
146
  /// @return A reference to the first element.
147
  T &
148
  front() {
149
    return (*this)[0];
150
  }
151
152
  /// @return A reference to the last element.
153
  T const &
154
  back() const {
155
    return (*this)[this->size() - 1];
156
  }
157
158
  /// @return A reference to the last element.
159
  T &
160
  back() {
161
    return (*this)[this->size() - 1];
162
  }
163
  /** Append an element by copy.
164
   *
165
   * @param t Element to add.
166
   * @return @a this.
167
   */
168
  self_type &push_back(T const &t);
169
170
  /** Append an element by move.
171
   *
172
   * @param t Element to add.
173
   * @return @a this.
174
   */
175
  self_type &push_back(T &&t);
176
177
  /** Append an element by direct construction.
178
   *
179
   * @tparam Args Constructor parameter types.
180
   * @param args Constructor arguments.
181
   * @return @a this
182
   */
183
  template <typename... Args> self_type &emplace_back(Args &&...args);
184
185
  /** Remove an element from the end of the current elements.
186
   *
187
   * @return @a this.
188
   */
189
  self_type &pop_back();
190
191
  /// Iterator for first element.
192
  const_iterator begin() const;
193
194
  /// Iterator past last element.
195
  const_iterator end() const;
196
197
  /// Iterator for last element.
198
  iterator begin();
199
200
  /// Iterator past last element.
201
  iterator end();
202
203
  /// Force at internal storage to hold at least @a n items.
204
  void reserve(size_type n);
205
206
protected:
207
  /// Content storage.
208
  /// @note This is constructed as fixed but can change to dynamic. It can never change back.
209
  std::variant<FixedStore, DynamicStore> _store;
210
211
  static constexpr auto FIXED   = 0; ///< Variant index for fixed storage.
212
  static constexpr auto DYNAMIC = 1; ///< Variant index for dynamic storage.
213
214
  /// Get the span of the valid items.
215
  span items();
216
  /// Get the span of the valid items.
217
  const_span items() const;
218
219
  /// Default size to reserve in the vector when switching to dynamic.
220
  static constexpr size_type BASE_DYNAMIC_SIZE = (7 * N) / 5;
221
222
  /** Transfer from fixed storage to dynamic storage.
223
   *
224
   * @param rN Numer of elements of storage to reserve in the vector.
225
   *
226
   * @note Must be called at most once for any instance.
227
   */
228
  void transfer(size_type rN = BASE_DYNAMIC_SIZE);
229
};
230
231
// --- Implementation ---
232
233
0
template <typename T, size_t N, typename A> Vectray<T, N, A>::Vectray() {}
234
235
template <typename T, size_t N, class A> Vectray<T, N, A>::Vectray(Vectray::size_type n, allocator_type const &) : Vectray() {
236
  this->reserve(n);
237
  while (n-- > 0) {
238
    this->emplace_back();
239
  }
240
}
241
242
template <typename T, size_t N, class A> template <size_t M> Vectray<T, N, A>::Vectray(Vectray<T, M, A> &&that) {
243
  // If @a that is already a vector, always move that here.
244
  if (DYNAMIC == that._store.index()) {
245
    _store = std::move(std::get<DYNAMIC>(that._store));
246
  } else {
247
    auto span = std::get<FIXED>(that._store).span();
248
    if (span.size() > N) {
249
    } else {
250
      for (auto &&item : span) {
251
        this->template emplace_back<T, N, A>(std::move(item));
252
      }
253
    }
254
  }
255
}
256
257
0
template <typename T, size_t N, class A> Vectray<T, N, A>::FixedStore::~FixedStore() {
258
0
  for (auto &item : this->span()) {
259
0
    std::destroy_at(std::addressof(item));
260
0
  }
261
0
}
262
263
template <typename T, size_t N, class A>
264
MemSpan<T>
265
0
Vectray<T, N, A>::FixedStore::span() {
266
0
  return {this->data(), _count};
267
0
}
268
269
template <typename T, size_t N, class A>
270
T *
271
0
Vectray<T, N, A>::FixedStore::data() {
272
0
  return reinterpret_cast<T *>(_raw.data());
273
0
}
274
275
template <typename T, size_t N, class A>
276
T const *
277
Vectray<T, N, A>::FixedStore::data() const {
278
  return reinterpret_cast<T *>(_raw.data());
279
}
280
281
template <typename T, size_t N, typename A>
282
T &
283
0
Vectray<T, N, A>::operator[](size_type idx) {
284
0
  return this->items()[idx];
285
0
}
286
287
template <typename T, size_t N, typename A>
288
T const &
289
Vectray<T, N, A>::operator[](size_type idx) const {
290
  return this->items()[idx];
291
}
292
293
template <typename T, size_t N, typename A>
294
auto
295
0
Vectray<T, N, A>::push_back(const T &t) -> self_type & {
296
0
  std::visit(swoc::meta::vary{[&](FixedStore &fs) -> void {
297
0
                                if (fs._count < N) {
298
0
                                  new (reinterpret_cast<T *>(fs._raw.data()) + fs._count++) T(t); // A::traits ?
299
0
                                } else {
300
0
                                  this->transfer();
301
0
                                  std::get<DYNAMIC>(_store).push_back(t);
302
0
                                }
303
0
                              },
304
0
                              [&](DynamicStore &ds) -> void { ds.push_back(t); }},
305
0
             _store);
306
0
  return *this;
307
0
}
308
309
template <typename T, size_t N, typename A>
310
auto
311
Vectray<T, N, A>::push_back(T &&t) -> self_type & {
312
  std::visit(swoc::meta::vary{[&](FixedStore &fs) -> void {
313
                                if (fs._count < N) {
314
                                  new (reinterpret_cast<T *>(fs._raw.data()) + fs._count++) T(std::move(t)); // A::traits ?
315
                                } else {
316
                                  this->transfer();
317
                                  std::get<DYNAMIC>(_store).push_back(std::move(t));
318
                                }
319
                              },
320
                              [&](DynamicStore &ds) -> void { ds.push_back(std::move(t)); }},
321
             _store);
322
  return *this;
323
}
324
325
template <typename T, size_t N, class A>
326
template <typename... Args>
327
typename Vectray<T, N, A>::self_type &
328
Vectray<T, N, A>::emplace_back(Args &&...args) {
329
  if (_store.index() == FIXED) {
330
    auto &fs{std::get<FIXED>(_store)};
331
    if (fs._count < N) {
332
      new (reinterpret_cast<T *>(fs._raw.data()) + fs._count++) T(std::forward<Args>(args)...); // A::traits ?
333
      return *this;
334
    }
335
    this->transfer(); // transfer to dynamic and fall through to add item.
336
  }
337
  std::get<DYNAMIC>(_store).emplace_back(std::forward<Args>(args)...);
338
  return *this;
339
}
340
341
template <typename T, size_t N, class A>
342
auto
343
Vectray<T, N, A>::pop_back() -> self_type & {
344
  std::visit(swoc::meta::vary{[&](FixedStore &fs) -> void { std::destroy_at(fs.span()[--fs._count]); },
345
                              [&](DynamicStore &ds) -> void { ds.pop_back(); }},
346
             _store);
347
  return *this;
348
}
349
350
template <typename T, size_t N, typename A>
351
auto
352
0
Vectray<T, N, A>::size() const -> size_type {
353
0
  return std::visit(
354
0
    swoc::meta::vary{[](FixedStore const &fs) { return fs._count; }, [](DynamicStore const &ds) { return ds.size(); }}, _store);
355
0
}
356
357
template <typename T, size_t N, typename A>
358
bool
359
0
Vectray<T, N, A>::empty() const {
360
0
  return std::visit(
361
0
    swoc::meta::vary{[](FixedStore const &fs) { return fs._count == 0; }, [](DynamicStore const &ds) { return ds.empty(); }},
362
0
    _store);
363
0
}
364
365
// --- iterators
366
template <typename T, size_t N, typename A>
367
auto
368
Vectray<T, N, A>::begin() const -> const_iterator {
369
  return this->items().begin();
370
}
371
372
template <typename T, size_t N, typename A>
373
auto
374
Vectray<T, N, A>::end() const -> const_iterator {
375
  return this->items().end();
376
}
377
378
template <typename T, size_t N, typename A>
379
auto
380
Vectray<T, N, A>::begin() -> iterator {
381
  return this->items().begin();
382
}
383
384
template <typename T, size_t N, typename A>
385
auto
386
Vectray<T, N, A>::end() -> iterator {
387
  return this->items().end();
388
}
389
// --- iterators
390
391
template <typename T, size_t N, class A>
392
void
393
0
Vectray<T, N, A>::transfer(size_type rN) {
394
0
  DynamicStore tmp{std::get<FIXED>(_store)._a};
395
0
  tmp.reserve(rN);
396
397
0
  for (auto &&item : this->items()) {
398
0
    tmp.emplace_back(std::move(item)); // move if supported, copy if not.
399
0
  }
400
  // Fixed elements destroyed here, by variant.
401
0
  _store = std::move(tmp);
402
0
}
403
404
template <typename T, size_t N, class A>
405
auto
406
Vectray<T, N, A>::items() const -> const_span {
407
  return std::visit(swoc::meta::vary{[](FixedStore const &fs) { fs.span(); },
408
                                     [](DynamicStore const &ds) { return const_span(ds.data(), ds.size()); }},
409
                    _store);
410
}
411
412
template <typename T, size_t N, class A>
413
T *
414
Vectray<T, N, A>::data() {
415
  return std::visit(swoc::meta::vary{[](FixedStore const &fs) { fs.data(); }, [](DynamicStore const &ds) { return ds.data(); }},
416
                    _store);
417
}
418
419
template <typename T, size_t N, class A>
420
T const *
421
Vectray<T, N, A>::data() const {
422
  return std::visit(swoc::meta::vary{[](FixedStore const &fs) { fs.data(); }, [](DynamicStore const &ds) { return ds.data(); }},
423
                    _store);
424
}
425
426
template <typename T, size_t N, class A>
427
auto
428
0
Vectray<T, N, A>::items() -> span {
429
0
  return std::visit(
430
0
    swoc::meta::vary{[](FixedStore &fs) { return fs.span(); }, [](DynamicStore &ds) { return span(ds.data(), ds.size()); }},
431
0
    _store);
432
0
}
433
434
template <typename T, size_t N, class A>
435
void
436
Vectray<T, N, A>::reserve(Vectray::size_type n) {
437
  if (DYNAMIC == _store.index()) {
438
    std::get<DYNAMIC>(_store).reserve(n);
439
  } else if (n > N) {
440
    this->transfer(n);
441
  }
442
}
443
444
}} // namespace swoc::SWOC_VERSION_NS