1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
|
/* Copyright (C) 2023 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* 0 A.D. is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef INCLUDED_PS_STATICVECTOR
#define INCLUDED_PS_STATICVECTOR
#include <algorithm>
#include <array>
#include <cstdint>
#include <fmt/format.h>
#include <initializer_list>
#include <limits>
#include <memory>
#include <new>
#include <stdexcept>
namespace PS
{
struct CapacityExceededException : public std::length_error
{
using std::length_error::length_error;
};
template<size_t N>
constexpr auto MakeSmallestCapableUnsigned()
{
if constexpr (N <= std::numeric_limits<uint_fast8_t>::max())
return static_cast<uint_fast8_t>(0);
else if constexpr (N <= std::numeric_limits<uint_fast16_t>::max())
return static_cast<uint_fast16_t>(0);
else if constexpr (N <= std::numeric_limits<uint_fast32_t>::max())
return static_cast<uint_fast32_t>(0);
else if constexpr (N <= std::numeric_limits<uint_fast64_t>::max())
return static_cast<uint_fast64_t>(0);
else
{
static_assert(N <= std::numeric_limits<uintmax_t>::max());
return static_cast<uintmax_t>(0);
}
}
template<size_t N>
constexpr auto MakeSmallestCapableSigned()
{
// TODO C++20: Use std::cmp_*
if constexpr (N <= static_cast<uintmax_t>(std::numeric_limits<int_fast8_t>::max()) &&
-static_cast<intmax_t>(N) >= std::numeric_limits<int_fast8_t>::min())
return static_cast<int_fast8_t>(0);
else if constexpr (N <= static_cast<uintmax_t>(std::numeric_limits<int_fast16_t>::max()) &&
-static_cast<intmax_t>(N) >= std::numeric_limits<int_fast16_t>::min())
return static_cast<int_fast16_t>(0);
else if constexpr (N <= static_cast<uintmax_t>(std::numeric_limits<int_fast32_t>::max()) &&
-static_cast<intmax_t>(N) >= std::numeric_limits<int_fast32_t>::min())
return static_cast<int_fast32_t>(0);
else if constexpr (N <= static_cast<uintmax_t>(std::numeric_limits<int_fast64_t>::max()) &&
-static_cast<intmax_t>(N) >= std::numeric_limits<int_fast64_t>::min())
return static_cast<int_fast64_t>(0);
else
{
static_assert(N <= static_cast<uintmax_t>(std::numeric_limits<intmax_t>::max()) &&
-static_cast<intmax_t>(N) >= std::numeric_limits<intmax_t>::min());
return static_cast<intmax_t>(0);
}
}
/**
* A conntainer close to std::vector but the elements are stored in place:
* There is a fixed capacity and there is no dynamic memory allocation.
* Note: moving a StaticVector will be slower than moving a std::vector in
* case of sizeof(StaticVector) > sizeof(std::vector).
*/
template<typename T, size_t N>
class StaticVector
{
public:
static_assert(std::is_nothrow_destructible_v<T>);
using value_type = T;
using size_type = decltype(MakeSmallestCapableUnsigned<N>());
using difference_type = decltype(MakeSmallestCapableSigned<N>());
using reference = value_type&;
using const_reference = const value_type&;
using pointer = value_type*;
using const_pointer = const value_type*;
using iterator = pointer;
using const_iterator = const_pointer;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
StaticVector() = default;
StaticVector(const StaticVector& other) noexcept(std::is_nothrow_copy_constructible_v<T>)
: m_Size{other.size()}
{
std::uninitialized_copy(other.begin(), other.end(), begin());
}
template<size_t OtherN>
explicit StaticVector(const StaticVector<T, OtherN>& other) noexcept(
std::is_nothrow_copy_constructible_v<T>)
: m_Size{other.size()}
{
static_assert(OtherN < N);
std::uninitialized_copy(other.begin(), other.end(), begin());
}
StaticVector& operator=(const StaticVector& other) noexcept(std::is_nothrow_copy_constructible_v<T>
&& std::is_nothrow_copy_assignable_v<T>)
{
const size_type initializedCopies{std::min(other.size(), size())};
std::copy_n(other.begin(), initializedCopies, begin());
std::uninitialized_copy(other.begin() + initializedCopies, other.end(),
begin() + initializedCopies);
std::destroy(begin() + initializedCopies, end());
m_Size = other.size();
return *this;
}
template<size_t OtherN>
StaticVector& operator=(const StaticVector<T, OtherN>& other) noexcept(
std::is_nothrow_copy_constructible_v<T> && std::is_nothrow_copy_assignable_v<T>)
{
static_assert(OtherN < N);
const size_type initializedCopies{std::min(other.size(), size())};
std::copy_n(other.begin(), initializedCopies, begin());
std::uninitialized_copy(other.begin() + initializedCopies, other.end(),
begin() + initializedCopies);
std::destroy(begin() + initializedCopies, end());
m_Size = other.size();
return *this;
}
StaticVector(StaticVector&& other) noexcept(std::is_nothrow_move_constructible_v<T>)
: m_Size{other.size()}
{
std::uninitialized_move(other.begin(), other.end(), begin());
}
template<size_t OtherN>
explicit StaticVector(StaticVector<T, OtherN>&& other)
noexcept(std::is_nothrow_move_constructible_v<T>)
: m_Size{other.size()}
{
static_assert(OtherN < N);
std::uninitialized_move(other.begin(), other.end(), begin());
}
StaticVector& operator=(StaticVector&& other) noexcept(std::is_nothrow_move_constructible_v<T> &&
std::is_nothrow_move_assignable_v<T>)
{
const size_type initializedMoves{std::min(other.size(), size())};
std::move(other.begin(), other.begin() + initializedMoves, begin());
std::uninitialized_move(other.begin() + initializedMoves, other.end(),
begin() + initializedMoves);
std::destroy(begin() + initializedMoves, end());
m_Size = other.size();
return *this;
}
template<size_t OtherN>
StaticVector& operator=(StaticVector<T, OtherN>&& other) noexcept(
std::is_nothrow_move_constructible_v<T> && std::is_nothrow_move_assignable_v<T>)
{
static_assert(OtherN < N);
const size_type initializedMoves{std::min(other.size(), size())};
std::move(other.begin(), other.begin() + initializedMoves, begin());
std::uninitialized_move(other.begin() + initializedMoves, other.end(),
begin() + initializedMoves);
std::destroy(begin() + initializedMoves, end());
m_Size = other.size();
return *this;
}
~StaticVector()
{
clear();
}
StaticVector(const size_type count, const T& value)
: m_Size{count}
{
if (count > N)
throw CapacityExceededException{fmt::format(
"Tried to construct a StaticVector with a size of {} but the capacity is only {}",
count, N)};
std::uninitialized_fill(begin(), end(), value);
}
StaticVector(const size_type count)
: m_Size{count}
{
if (count > N)
throw CapacityExceededException{fmt::format(
"Tried to construct a StaticVector with a size of {} but the capacity is only {}",
count, N)};
std::uninitialized_default_construct(begin(), end());
}
StaticVector(const std::initializer_list<T> init)
: m_Size{static_cast<size_type>(init.size())} // Will be tested below.
{
if (init.size() > N)
throw CapacityExceededException{fmt::format(
"Tried to construct a StaticVector with a size of {} but the capacity is only {}",
init.size(), N)};
std::uninitialized_copy(init.begin(), init.end(), begin());
}
StaticVector& operator=(const std::initializer_list<T> init)
{
if (init.size() > N)
throw CapacityExceededException{fmt::format(
"Tried to construct a StaticVector with a size of {} but the capacity is only {}",
init.size(), N)};
clear();
std::uninitialized_copy(init.begin(), init.end(), begin());
m_Size = init.size();
}
reference at(const size_type index)
{
if (index >= m_Size)
throw std::out_of_range{fmt::format("Called at({}) but there are only {} elements.",
index, size())};
return (*this)[index];
}
const_reference at(const size_type index) const
{
if (index >= size())
throw std::out_of_range{fmt::format("Called at({}) but there are only {} elements.",
index, size())};
return (*this)[index];
}
reference operator[](const size_type index) noexcept
{
ASSERT(index < size());
return *(begin() + index);
}
const_reference operator[](const size_type index) const noexcept
{
ASSERT(index < size());
return *(begin() + index);
}
reference front() noexcept
{
ASSERT(!empty());
return *begin();
}
const_reference front() const noexcept
{
ASSERT(!empty());
return *begin();
}
reference back() noexcept
{
ASSERT(!empty());
return *std::prev(end());
}
const_reference back() const noexcept
{
ASSERT(!empty());
return *std::prev(end());
}
pointer data() noexcept
{
return std::launder(reinterpret_cast<pointer>(m_Data.data()));
}
const_pointer data() const noexcept
{
return std::launder(reinterpret_cast<const_pointer>(m_Data.data()));
}
iterator begin() noexcept
{
return data();
}
const_iterator begin() const noexcept
{
return cbegin();
}
const_iterator cbegin() const noexcept
{
return data();
}
iterator end() noexcept
{
return begin() + size();
}
const_iterator end() const noexcept
{
return cend();
}
const_iterator cend() const noexcept
{
return cbegin() + size();
}
reverse_iterator rbegin() noexcept
{
return std::make_reverse_iterator(end());
}
const_reverse_iterator rbegin() const noexcept
{
return crbegin();
}
const_reverse_iterator crbegin() const noexcept
{
return std::make_reverse_iterator(end());
}
reverse_iterator rend() noexcept
{
return std::make_reverse_iterator(begin());
}
const_reverse_iterator rend() const noexcept
{
return crend();
}
const_reverse_iterator crend() const noexcept
{
return std::make_reverse_iterator(cbegin());
}
bool empty() const noexcept
{
return size() == 0;
}
bool full() const noexcept
{
return size() == N;
}
size_type size() const noexcept
{
return m_Size;
}
constexpr size_type capacity() const noexcept
{
return N;
}
void clear() noexcept
{
std::destroy(begin(), end());
m_Size = 0;
}
/**
* Inserts an element at location. The elements which were in the range
* [ location, end() ) get moved no the next position.
*
* Exceptions:
* If an exception is thrown when inserting an element at the end this
* function has no effect (strong exception guarantee).
* Otherwise the program is in a valid state (Basic exception guarantee).
*/
iterator insert(const const_iterator location, const T& value)
{
if (full())
throw CapacityExceededException{"Called insert but the StaticVector is already full"};
if (location == end())
return std::addressof(emplace_back(value));
new(end()) T{std::move(back())};
++m_Size;
const iterator mutableLocation{MutableIter(location)};
std::move_backward(mutableLocation, std::prev(end(), 2), std::prev(end(), 1));
*mutableLocation = value;
return mutableLocation;
}
/**
* Same as above but the new element is move-constructed.
*
* If an exception is thrown when inserting an element at the end this
* function has no effect (strong exception guarantee).
* If an exception is thrown the program is in a valid state
* (Basic exception guarantee).
*/
iterator insert(const const_iterator location, T&& value)
{
if (full())
throw CapacityExceededException{"Called insert but the StaticVector is already full"};
if (location == end())
return std::addressof(emplace_back(std::move(value)));
const iterator mutableLocation{MakeMutableIterator(location)};
new(end()) T{std::move(back())};
++m_Size;
std::move_backward(mutableLocation, end() - 2, end() -1);
*mutableLocation = std::move(value);
return mutableLocation;
}
/**
* If an exception is thrown this function has no effect
* (strong exception guarantee).
*/
void push_back(const T& value)
{
emplace_back(value);
}
/**
* If an exception is thrown this function has no effect
* (strong exception guarantee).
*/
void push_back(T&& value)
{
emplace_back(std::move(value));
}
/**
* If an exception is thrown this function has no effect
* (strong exception guarantee).
*/
template<typename... Args>
reference emplace_back(Args&&... args)
{
if (full())
throw CapacityExceededException{
"Called emplace_back but the StaticVector is already full"};
const iterator location{begin() + size()};
new(location) T{std::forward<Args>(args)...};
++m_Size;
return *location;
}
void pop_back() noexcept
{
ASSERT(!empty());
std::destroy_at(std::addressof(back()));
--m_Size;
}
/**
* Constructs or destructs elements to adjust to newSize. After this call
* the StaticVector contains newSize elements. Unlike std::vector the
* capacity does not get changed. If newSize is bigger then the capacity
* a CapacityExceededException is thrown.
*
* If newSize is smaller than size() (shrinking) no exception is thrown
* (Nothrow exception guarantee).
* If an exception is thrown this function has no effect.
* (strong exception guarantee)
*/
void resize(const size_type newSize)
{
if (newSize > N)
throw CapacityExceededException{fmt::format(
"Can not resize StaticVector to {} the capacity is {}", newSize, N)};
if (newSize > size())
std::uninitialized_default_construct(end(), begin() + newSize);
else
std::destroy(begin() + newSize, end());
m_Size = newSize;
}
/**
* Same as above but uses value to copy-construct the new elements.
*
* If newSize is smaller than size() (shrinking) no exception is thrown
* (Nothrow exception guarantee).
* If an exception is thrown this function has no effect.
* (strong exception guarantee)
*/
void resize(const size_type newSize, const T& value)
{
if (newSize > N)
throw CapacityExceededException{fmt::format(
"Can't resize the StaticVector to {} the capacity is {}", newSize, N)};
if (newSize > size())
std::uninitialized_fill(end(), begin() + newSize, value);
else
std::destroy(begin() + newSize, end());
m_Size = newSize;
}
template<size_t OtherN>
friend bool operator==(const StaticVector<T, N>& lhs, const StaticVector<T, OtherN>& rhs)
{
return std::equal(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());
}
template<size_t OtherN>
friend bool operator!=(const StaticVector<T, N>& lhs, const StaticVector<T, OtherN>& rhs)
{
return !(lhs == rhs);
}
private:
iterator MakeMutableIterator(const const_iterator iter) noexcept
{
return begin() + (iter - begin());
}
using EagerInitialized = std::array<T, N>;
alignas(EagerInitialized) std::array<std::byte, sizeof(T) * N> m_Data;
size_type m_Size{0};
};
} // namespace PS
#endif // INCLUDED_PS_STATICVECTOR
|