inlined_vector.h 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  1. // Copyright 2019 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //
  15. // -----------------------------------------------------------------------------
  16. // File: inlined_vector.h
  17. // -----------------------------------------------------------------------------
  18. //
  19. // This header file contains the declaration and definition of an "inlined
  20. // vector" which behaves in an equivalent fashion to a `std::vector`, except
  21. // that storage for small sequences of the vector are provided inline without
  22. // requiring any heap allocation.
  23. //
  24. // An `absl::InlinedVector<T, N>` specifies the default capacity `N` as one of
  25. // its template parameters. Instances where `size() <= N` hold contained
  26. // elements in inline space. Typically `N` is very small so that sequences that
  27. // are expected to be short do not require allocations.
  28. //
  29. // An `absl::InlinedVector` does not usually require a specific allocator. If
  30. // the inlined vector grows beyond its initial constraints, it will need to
  31. // allocate (as any normal `std::vector` would). This is usually performed with
  32. // the default allocator (defined as `std::allocator<T>`). Optionally, a custom
  33. // allocator type may be specified as `A` in `absl::InlinedVector<T, N, A>`.
  34. #ifndef ABSL_CONTAINER_INLINED_VECTOR_H_
  35. #define ABSL_CONTAINER_INLINED_VECTOR_H_
  36. #include <algorithm>
  37. #include <cstddef>
  38. #include <cstdlib>
  39. #include <cstring>
  40. #include <initializer_list>
  41. #include <iterator>
  42. #include <memory>
  43. #include <type_traits>
  44. #include <utility>
  45. #include "absl/algorithm/algorithm.h"
  46. #include "absl/base/attributes.h"
  47. #include "absl/base/internal/throw_delegate.h"
  48. #include "absl/base/macros.h"
  49. #include "absl/base/optimization.h"
  50. #include "absl/base/port.h"
  51. #include "absl/container/internal/inlined_vector.h"
  52. #include "absl/memory/memory.h"
  53. #include "absl/meta/type_traits.h"
  54. namespace absl {
  55. ABSL_NAMESPACE_BEGIN
  56. // -----------------------------------------------------------------------------
  57. // InlinedVector
  58. // -----------------------------------------------------------------------------
  59. //
  60. // An `absl::InlinedVector` is designed to be a drop-in replacement for
  61. // `std::vector` for use cases where the vector's size is sufficiently small
  62. // that it can be inlined. If the inlined vector does grow beyond its estimated
  63. // capacity, it will trigger an initial allocation on the heap, and will behave
  64. // as a `std::vector`. The API of the `absl::InlinedVector` within this file is
  65. // designed to cover the same API footprint as covered by `std::vector`.
  66. template <typename T, size_t N, typename A = std::allocator<T>>
  67. class ABSL_ATTRIBUTE_WARN_UNUSED InlinedVector {
  68. static_assert(N > 0, "`absl::InlinedVector` requires an inlined capacity.");
  69. using Storage = inlined_vector_internal::Storage<T, N, A>;
  70. template <typename TheA>
  71. using AllocatorTraits = inlined_vector_internal::AllocatorTraits<TheA>;
  72. template <typename TheA>
  73. using MoveIterator = inlined_vector_internal::MoveIterator<TheA>;
  74. template <typename TheA>
  75. using IsMoveAssignOk = inlined_vector_internal::IsMoveAssignOk<TheA>;
  76. template <typename TheA, typename Iterator>
  77. using IteratorValueAdapter =
  78. inlined_vector_internal::IteratorValueAdapter<TheA, Iterator>;
  79. template <typename TheA>
  80. using CopyValueAdapter = inlined_vector_internal::CopyValueAdapter<TheA>;
  81. template <typename TheA>
  82. using DefaultValueAdapter =
  83. inlined_vector_internal::DefaultValueAdapter<TheA>;
  84. template <typename Iterator>
  85. using EnableIfAtLeastForwardIterator = absl::enable_if_t<
  86. inlined_vector_internal::IsAtLeastForwardIterator<Iterator>::value, int>;
  87. template <typename Iterator>
  88. using DisableIfAtLeastForwardIterator = absl::enable_if_t<
  89. !inlined_vector_internal::IsAtLeastForwardIterator<Iterator>::value, int>;
  90. using MemcpyPolicy = typename Storage::MemcpyPolicy;
  91. using ElementwiseAssignPolicy = typename Storage::ElementwiseAssignPolicy;
  92. using ElementwiseConstructPolicy =
  93. typename Storage::ElementwiseConstructPolicy;
  94. using MoveAssignmentPolicy = typename Storage::MoveAssignmentPolicy;
  95. public:
  96. using allocator_type = A;
  97. using value_type = inlined_vector_internal::ValueType<A>;
  98. using pointer = inlined_vector_internal::Pointer<A>;
  99. using const_pointer = inlined_vector_internal::ConstPointer<A>;
  100. using size_type = inlined_vector_internal::SizeType<A>;
  101. using difference_type = inlined_vector_internal::DifferenceType<A>;
  102. using reference = inlined_vector_internal::Reference<A>;
  103. using const_reference = inlined_vector_internal::ConstReference<A>;
  104. using iterator = inlined_vector_internal::Iterator<A>;
  105. using const_iterator = inlined_vector_internal::ConstIterator<A>;
  106. using reverse_iterator = inlined_vector_internal::ReverseIterator<A>;
  107. using const_reverse_iterator =
  108. inlined_vector_internal::ConstReverseIterator<A>;
  109. // ---------------------------------------------------------------------------
  110. // InlinedVector Constructors and Destructor
  111. // ---------------------------------------------------------------------------
  112. // Creates an empty inlined vector with a value-initialized allocator.
  113. InlinedVector() noexcept(noexcept(allocator_type())) : storage_() {}
  114. // Creates an empty inlined vector with a copy of `allocator`.
  115. explicit InlinedVector(const allocator_type& allocator) noexcept
  116. : storage_(allocator) {}
  117. // Creates an inlined vector with `n` copies of `value_type()`.
  118. explicit InlinedVector(size_type n,
  119. const allocator_type& allocator = allocator_type())
  120. : storage_(allocator) {
  121. storage_.Initialize(DefaultValueAdapter<A>(), n);
  122. }
  123. // Creates an inlined vector with `n` copies of `v`.
  124. InlinedVector(size_type n, const_reference v,
  125. const allocator_type& allocator = allocator_type())
  126. : storage_(allocator) {
  127. storage_.Initialize(CopyValueAdapter<A>(std::addressof(v)), n);
  128. }
  129. // Creates an inlined vector with copies of the elements of `list`.
  130. InlinedVector(std::initializer_list<value_type> list,
  131. const allocator_type& allocator = allocator_type())
  132. : InlinedVector(list.begin(), list.end(), allocator) {}
  133. // Creates an inlined vector with elements constructed from the provided
  134. // forward iterator range [`first`, `last`).
  135. //
  136. // NOTE: the `enable_if` prevents ambiguous interpretation between a call to
  137. // this constructor with two integral arguments and a call to the above
  138. // `InlinedVector(size_type, const_reference)` constructor.
  139. template <typename ForwardIterator,
  140. EnableIfAtLeastForwardIterator<ForwardIterator> = 0>
  141. InlinedVector(ForwardIterator first, ForwardIterator last,
  142. const allocator_type& allocator = allocator_type())
  143. : storage_(allocator) {
  144. storage_.Initialize(IteratorValueAdapter<A, ForwardIterator>(first),
  145. static_cast<size_t>(std::distance(first, last)));
  146. }
  147. // Creates an inlined vector with elements constructed from the provided input
  148. // iterator range [`first`, `last`).
  149. template <typename InputIterator,
  150. DisableIfAtLeastForwardIterator<InputIterator> = 0>
  151. InlinedVector(InputIterator first, InputIterator last,
  152. const allocator_type& allocator = allocator_type())
  153. : storage_(allocator) {
  154. std::copy(first, last, std::back_inserter(*this));
  155. }
  156. // Creates an inlined vector by copying the contents of `other` using
  157. // `other`'s allocator.
  158. InlinedVector(const InlinedVector& other)
  159. : InlinedVector(other, other.storage_.GetAllocator()) {}
  160. // Creates an inlined vector by copying the contents of `other` using the
  161. // provided `allocator`.
  162. InlinedVector(const InlinedVector& other, const allocator_type& allocator)
  163. : storage_(allocator) {
  164. // Fast path: if the other vector is empty, there's nothing for us to do.
  165. if (other.empty()) {
  166. return;
  167. }
  168. // Fast path: if the value type is trivially copy constructible, we know the
  169. // allocator doesn't do anything fancy, and there is nothing on the heap
  170. // then we know it is legal for us to simply memcpy the other vector's
  171. // inlined bytes to form our copy of its elements.
  172. if (absl::is_trivially_copy_constructible<value_type>::value &&
  173. std::is_same<A, std::allocator<value_type>>::value &&
  174. !other.storage_.GetIsAllocated()) {
  175. storage_.MemcpyFrom(other.storage_);
  176. return;
  177. }
  178. storage_.InitFrom(other.storage_);
  179. }
  180. // Creates an inlined vector by moving in the contents of `other` without
  181. // allocating. If `other` contains allocated memory, the newly-created inlined
  182. // vector will take ownership of that memory. However, if `other` does not
  183. // contain allocated memory, the newly-created inlined vector will perform
  184. // element-wise move construction of the contents of `other`.
  185. //
  186. // NOTE: since no allocation is performed for the inlined vector in either
  187. // case, the `noexcept(...)` specification depends on whether moving the
  188. // underlying objects can throw. It is assumed assumed that...
  189. // a) move constructors should only throw due to allocation failure.
  190. // b) if `value_type`'s move constructor allocates, it uses the same
  191. // allocation function as the inlined vector's allocator.
  192. // Thus, the move constructor is non-throwing if the allocator is non-throwing
  193. // or `value_type`'s move constructor is specified as `noexcept`.
  194. InlinedVector(InlinedVector&& other) noexcept(
  195. absl::allocator_is_nothrow<allocator_type>::value ||
  196. std::is_nothrow_move_constructible<value_type>::value)
  197. : storage_(other.storage_.GetAllocator()) {
  198. // Fast path: if the value type can be trivially relocated (i.e. moved from
  199. // and destroyed), and we know the allocator doesn't do anything fancy, then
  200. // it's safe for us to simply adopt the contents of the storage for `other`
  201. // and remove its own reference to them. It's as if we had individually
  202. // move-constructed each value and then destroyed the original.
  203. if (absl::is_trivially_relocatable<value_type>::value &&
  204. std::is_same<A, std::allocator<value_type>>::value) {
  205. storage_.MemcpyFrom(other.storage_);
  206. other.storage_.SetInlinedSize(0);
  207. return;
  208. }
  209. // Fast path: if the other vector is on the heap, we can simply take over
  210. // its allocation.
  211. if (other.storage_.GetIsAllocated()) {
  212. storage_.SetAllocation({other.storage_.GetAllocatedData(),
  213. other.storage_.GetAllocatedCapacity()});
  214. storage_.SetAllocatedSize(other.storage_.GetSize());
  215. other.storage_.SetInlinedSize(0);
  216. return;
  217. }
  218. // Otherwise we must move each element individually.
  219. IteratorValueAdapter<A, MoveIterator<A>> other_values(
  220. MoveIterator<A>(other.storage_.GetInlinedData()));
  221. inlined_vector_internal::ConstructElements<A>(
  222. storage_.GetAllocator(), storage_.GetInlinedData(), other_values,
  223. other.storage_.GetSize());
  224. storage_.SetInlinedSize(other.storage_.GetSize());
  225. }
  226. // Creates an inlined vector by moving in the contents of `other` with a copy
  227. // of `allocator`.
  228. //
  229. // NOTE: if `other`'s allocator is not equal to `allocator`, even if `other`
  230. // contains allocated memory, this move constructor will still allocate. Since
  231. // allocation is performed, this constructor can only be `noexcept` if the
  232. // specified allocator is also `noexcept`.
  233. InlinedVector(
  234. InlinedVector&& other,
  235. const allocator_type&
  236. allocator) noexcept(absl::allocator_is_nothrow<allocator_type>::value)
  237. : storage_(allocator) {
  238. // Fast path: if the value type can be trivially relocated (i.e. moved from
  239. // and destroyed), and we know the allocator doesn't do anything fancy, then
  240. // it's safe for us to simply adopt the contents of the storage for `other`
  241. // and remove its own reference to them. It's as if we had individually
  242. // move-constructed each value and then destroyed the original.
  243. if (absl::is_trivially_relocatable<value_type>::value &&
  244. std::is_same<A, std::allocator<value_type>>::value) {
  245. storage_.MemcpyFrom(other.storage_);
  246. other.storage_.SetInlinedSize(0);
  247. return;
  248. }
  249. // Fast path: if the other vector is on the heap and shared the same
  250. // allocator, we can simply take over its allocation.
  251. if ((storage_.GetAllocator() == other.storage_.GetAllocator()) &&
  252. other.storage_.GetIsAllocated()) {
  253. storage_.SetAllocation({other.storage_.GetAllocatedData(),
  254. other.storage_.GetAllocatedCapacity()});
  255. storage_.SetAllocatedSize(other.storage_.GetSize());
  256. other.storage_.SetInlinedSize(0);
  257. return;
  258. }
  259. // Otherwise we must move each element individually.
  260. storage_.Initialize(
  261. IteratorValueAdapter<A, MoveIterator<A>>(MoveIterator<A>(other.data())),
  262. other.size());
  263. }
  264. ~InlinedVector() {}
  265. // ---------------------------------------------------------------------------
  266. // InlinedVector Member Accessors
  267. // ---------------------------------------------------------------------------
  268. // `InlinedVector::empty()`
  269. //
  270. // Returns whether the inlined vector contains no elements.
  271. bool empty() const noexcept { return !size(); }
  272. // `InlinedVector::size()`
  273. //
  274. // Returns the number of elements in the inlined vector.
  275. size_type size() const noexcept { return storage_.GetSize(); }
  276. // `InlinedVector::max_size()`
  277. //
  278. // Returns the maximum number of elements the inlined vector can hold.
  279. size_type max_size() const noexcept {
  280. // One bit of the size storage is used to indicate whether the inlined
  281. // vector contains allocated memory. As a result, the maximum size that the
  282. // inlined vector can express is the minimum of the limit of how many
  283. // objects we can allocate and std::numeric_limits<size_type>::max() / 2.
  284. return (std::min)(AllocatorTraits<A>::max_size(storage_.GetAllocator()),
  285. (std::numeric_limits<size_type>::max)() / 2);
  286. }
  287. // `InlinedVector::capacity()`
  288. //
  289. // Returns the number of elements that could be stored in the inlined vector
  290. // without requiring a reallocation.
  291. //
  292. // NOTE: for most inlined vectors, `capacity()` should be equal to the
  293. // template parameter `N`. For inlined vectors which exceed this capacity,
  294. // they will no longer be inlined and `capacity()` will equal the capactity of
  295. // the allocated memory.
  296. size_type capacity() const noexcept {
  297. return storage_.GetIsAllocated() ? storage_.GetAllocatedCapacity()
  298. : storage_.GetInlinedCapacity();
  299. }
  300. // `InlinedVector::data()`
  301. //
  302. // Returns a `pointer` to the elements of the inlined vector. This pointer
  303. // can be used to access and modify the contained elements.
  304. //
  305. // NOTE: only elements within [`data()`, `data() + size()`) are valid.
  306. pointer data() noexcept ABSL_ATTRIBUTE_LIFETIME_BOUND {
  307. return storage_.GetIsAllocated() ? storage_.GetAllocatedData()
  308. : storage_.GetInlinedData();
  309. }
  310. // Overload of `InlinedVector::data()` that returns a `const_pointer` to the
  311. // elements of the inlined vector. This pointer can be used to access but not
  312. // modify the contained elements.
  313. //
  314. // NOTE: only elements within [`data()`, `data() + size()`) are valid.
  315. const_pointer data() const noexcept ABSL_ATTRIBUTE_LIFETIME_BOUND {
  316. return storage_.GetIsAllocated() ? storage_.GetAllocatedData()
  317. : storage_.GetInlinedData();
  318. }
  319. // `InlinedVector::operator[](...)`
  320. //
  321. // Returns a `reference` to the `i`th element of the inlined vector.
  322. reference operator[](size_type i) ABSL_ATTRIBUTE_LIFETIME_BOUND {
  323. ABSL_HARDENING_ASSERT(i < size());
  324. return data()[i];
  325. }
  326. // Overload of `InlinedVector::operator[](...)` that returns a
  327. // `const_reference` to the `i`th element of the inlined vector.
  328. const_reference operator[](size_type i) const ABSL_ATTRIBUTE_LIFETIME_BOUND {
  329. ABSL_HARDENING_ASSERT(i < size());
  330. return data()[i];
  331. }
  332. // `InlinedVector::at(...)`
  333. //
  334. // Returns a `reference` to the `i`th element of the inlined vector.
  335. //
  336. // NOTE: if `i` is not within the required range of `InlinedVector::at(...)`,
  337. // in both debug and non-debug builds, `std::out_of_range` will be thrown.
  338. reference at(size_type i) ABSL_ATTRIBUTE_LIFETIME_BOUND {
  339. if (ABSL_PREDICT_FALSE(i >= size())) {
  340. base_internal::ThrowStdOutOfRange(
  341. "`InlinedVector::at(size_type)` failed bounds check");
  342. }
  343. return data()[i];
  344. }
  345. // Overload of `InlinedVector::at(...)` that returns a `const_reference` to
  346. // the `i`th element of the inlined vector.
  347. //
  348. // NOTE: if `i` is not within the required range of `InlinedVector::at(...)`,
  349. // in both debug and non-debug builds, `std::out_of_range` will be thrown.
  350. const_reference at(size_type i) const ABSL_ATTRIBUTE_LIFETIME_BOUND {
  351. if (ABSL_PREDICT_FALSE(i >= size())) {
  352. base_internal::ThrowStdOutOfRange(
  353. "`InlinedVector::at(size_type) const` failed bounds check");
  354. }
  355. return data()[i];
  356. }
  357. // `InlinedVector::front()`
  358. //
  359. // Returns a `reference` to the first element of the inlined vector.
  360. reference front() ABSL_ATTRIBUTE_LIFETIME_BOUND {
  361. ABSL_HARDENING_ASSERT(!empty());
  362. return data()[0];
  363. }
  364. // Overload of `InlinedVector::front()` that returns a `const_reference` to
  365. // the first element of the inlined vector.
  366. const_reference front() const ABSL_ATTRIBUTE_LIFETIME_BOUND {
  367. ABSL_HARDENING_ASSERT(!empty());
  368. return data()[0];
  369. }
  370. // `InlinedVector::back()`
  371. //
  372. // Returns a `reference` to the last element of the inlined vector.
  373. reference back() ABSL_ATTRIBUTE_LIFETIME_BOUND {
  374. ABSL_HARDENING_ASSERT(!empty());
  375. return data()[size() - 1];
  376. }
  377. // Overload of `InlinedVector::back()` that returns a `const_reference` to the
  378. // last element of the inlined vector.
  379. const_reference back() const ABSL_ATTRIBUTE_LIFETIME_BOUND {
  380. ABSL_HARDENING_ASSERT(!empty());
  381. return data()[size() - 1];
  382. }
  383. // `InlinedVector::begin()`
  384. //
  385. // Returns an `iterator` to the beginning of the inlined vector.
  386. iterator begin() noexcept ABSL_ATTRIBUTE_LIFETIME_BOUND { return data(); }
  387. // Overload of `InlinedVector::begin()` that returns a `const_iterator` to
  388. // the beginning of the inlined vector.
  389. const_iterator begin() const noexcept ABSL_ATTRIBUTE_LIFETIME_BOUND {
  390. return data();
  391. }
  392. // `InlinedVector::end()`
  393. //
  394. // Returns an `iterator` to the end of the inlined vector.
  395. iterator end() noexcept ABSL_ATTRIBUTE_LIFETIME_BOUND {
  396. return data() + size();
  397. }
  398. // Overload of `InlinedVector::end()` that returns a `const_iterator` to the
  399. // end of the inlined vector.
  400. const_iterator end() const noexcept ABSL_ATTRIBUTE_LIFETIME_BOUND {
  401. return data() + size();
  402. }
  403. // `InlinedVector::cbegin()`
  404. //
  405. // Returns a `const_iterator` to the beginning of the inlined vector.
  406. const_iterator cbegin() const noexcept ABSL_ATTRIBUTE_LIFETIME_BOUND {
  407. return begin();
  408. }
  409. // `InlinedVector::cend()`
  410. //
  411. // Returns a `const_iterator` to the end of the inlined vector.
  412. const_iterator cend() const noexcept ABSL_ATTRIBUTE_LIFETIME_BOUND {
  413. return end();
  414. }
  415. // `InlinedVector::rbegin()`
  416. //
  417. // Returns a `reverse_iterator` from the end of the inlined vector.
  418. reverse_iterator rbegin() noexcept ABSL_ATTRIBUTE_LIFETIME_BOUND {
  419. return reverse_iterator(end());
  420. }
  421. // Overload of `InlinedVector::rbegin()` that returns a
  422. // `const_reverse_iterator` from the end of the inlined vector.
  423. const_reverse_iterator rbegin() const noexcept ABSL_ATTRIBUTE_LIFETIME_BOUND {
  424. return const_reverse_iterator(end());
  425. }
  426. // `InlinedVector::rend()`
  427. //
  428. // Returns a `reverse_iterator` from the beginning of the inlined vector.
  429. reverse_iterator rend() noexcept ABSL_ATTRIBUTE_LIFETIME_BOUND {
  430. return reverse_iterator(begin());
  431. }
  432. // Overload of `InlinedVector::rend()` that returns a `const_reverse_iterator`
  433. // from the beginning of the inlined vector.
  434. const_reverse_iterator rend() const noexcept ABSL_ATTRIBUTE_LIFETIME_BOUND {
  435. return const_reverse_iterator(begin());
  436. }
  437. // `InlinedVector::crbegin()`
  438. //
  439. // Returns a `const_reverse_iterator` from the end of the inlined vector.
  440. const_reverse_iterator crbegin() const noexcept
  441. ABSL_ATTRIBUTE_LIFETIME_BOUND {
  442. return rbegin();
  443. }
  444. // `InlinedVector::crend()`
  445. //
  446. // Returns a `const_reverse_iterator` from the beginning of the inlined
  447. // vector.
  448. const_reverse_iterator crend() const noexcept ABSL_ATTRIBUTE_LIFETIME_BOUND {
  449. return rend();
  450. }
  451. // `InlinedVector::get_allocator()`
  452. //
  453. // Returns a copy of the inlined vector's allocator.
  454. allocator_type get_allocator() const { return storage_.GetAllocator(); }
  455. // ---------------------------------------------------------------------------
  456. // InlinedVector Member Mutators
  457. // ---------------------------------------------------------------------------
  458. // `InlinedVector::operator=(...)`
  459. //
  460. // Replaces the elements of the inlined vector with copies of the elements of
  461. // `list`.
  462. InlinedVector& operator=(std::initializer_list<value_type> list) {
  463. assign(list.begin(), list.end());
  464. return *this;
  465. }
  466. // Overload of `InlinedVector::operator=(...)` that replaces the elements of
  467. // the inlined vector with copies of the elements of `other`.
  468. InlinedVector& operator=(const InlinedVector& other) {
  469. if (ABSL_PREDICT_TRUE(this != std::addressof(other))) {
  470. const_pointer other_data = other.data();
  471. assign(other_data, other_data + other.size());
  472. }
  473. return *this;
  474. }
  475. // Overload of `InlinedVector::operator=(...)` that moves the elements of
  476. // `other` into the inlined vector.
  477. //
  478. // NOTE: as a result of calling this overload, `other` is left in a valid but
  479. // unspecified state.
  480. InlinedVector& operator=(InlinedVector&& other) {
  481. if (ABSL_PREDICT_TRUE(this != std::addressof(other))) {
  482. MoveAssignment(MoveAssignmentPolicy{}, std::move(other));
  483. }
  484. return *this;
  485. }
  486. // `InlinedVector::assign(...)`
  487. //
  488. // Replaces the contents of the inlined vector with `n` copies of `v`.
  489. void assign(size_type n, const_reference v) {
  490. storage_.Assign(CopyValueAdapter<A>(std::addressof(v)), n);
  491. }
  492. // Overload of `InlinedVector::assign(...)` that replaces the contents of the
  493. // inlined vector with copies of the elements of `list`.
  494. void assign(std::initializer_list<value_type> list) {
  495. assign(list.begin(), list.end());
  496. }
  497. // Overload of `InlinedVector::assign(...)` to replace the contents of the
  498. // inlined vector with the range [`first`, `last`).
  499. //
  500. // NOTE: this overload is for iterators that are "forward" category or better.
  501. template <typename ForwardIterator,
  502. EnableIfAtLeastForwardIterator<ForwardIterator> = 0>
  503. void assign(ForwardIterator first, ForwardIterator last) {
  504. storage_.Assign(IteratorValueAdapter<A, ForwardIterator>(first),
  505. static_cast<size_t>(std::distance(first, last)));
  506. }
  507. // Overload of `InlinedVector::assign(...)` to replace the contents of the
  508. // inlined vector with the range [`first`, `last`).
  509. //
  510. // NOTE: this overload is for iterators that are "input" category.
  511. template <typename InputIterator,
  512. DisableIfAtLeastForwardIterator<InputIterator> = 0>
  513. void assign(InputIterator first, InputIterator last) {
  514. size_type i = 0;
  515. for (; i < size() && first != last; ++i, static_cast<void>(++first)) {
  516. data()[i] = *first;
  517. }
  518. erase(data() + i, data() + size());
  519. std::copy(first, last, std::back_inserter(*this));
  520. }
  521. // `InlinedVector::resize(...)`
  522. //
  523. // Resizes the inlined vector to contain `n` elements.
  524. //
  525. // NOTE: If `n` is smaller than `size()`, extra elements are destroyed. If `n`
  526. // is larger than `size()`, new elements are value-initialized.
  527. void resize(size_type n) {
  528. ABSL_HARDENING_ASSERT(n <= max_size());
  529. storage_.Resize(DefaultValueAdapter<A>(), n);
  530. }
  531. // Overload of `InlinedVector::resize(...)` that resizes the inlined vector to
  532. // contain `n` elements.
  533. //
  534. // NOTE: if `n` is smaller than `size()`, extra elements are destroyed. If `n`
  535. // is larger than `size()`, new elements are copied-constructed from `v`.
  536. void resize(size_type n, const_reference v) {
  537. ABSL_HARDENING_ASSERT(n <= max_size());
  538. storage_.Resize(CopyValueAdapter<A>(std::addressof(v)), n);
  539. }
  540. // `InlinedVector::insert(...)`
  541. //
  542. // Inserts a copy of `v` at `pos`, returning an `iterator` to the newly
  543. // inserted element.
  544. iterator insert(const_iterator pos,
  545. const_reference v) ABSL_ATTRIBUTE_LIFETIME_BOUND {
  546. return emplace(pos, v);
  547. }
  548. // Overload of `InlinedVector::insert(...)` that inserts `v` at `pos` using
  549. // move semantics, returning an `iterator` to the newly inserted element.
  550. iterator insert(const_iterator pos,
  551. value_type&& v) ABSL_ATTRIBUTE_LIFETIME_BOUND {
  552. return emplace(pos, std::move(v));
  553. }
  554. // Overload of `InlinedVector::insert(...)` that inserts `n` contiguous copies
  555. // of `v` starting at `pos`, returning an `iterator` pointing to the first of
  556. // the newly inserted elements.
  557. iterator insert(const_iterator pos, size_type n,
  558. const_reference v) ABSL_ATTRIBUTE_LIFETIME_BOUND {
  559. ABSL_HARDENING_ASSERT(pos >= begin());
  560. ABSL_HARDENING_ASSERT(pos <= end());
  561. if (ABSL_PREDICT_TRUE(n != 0)) {
  562. value_type dealias = v;
  563. // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=102329#c2
  564. // It appears that GCC thinks that since `pos` is a const pointer and may
  565. // point to uninitialized memory at this point, a warning should be
  566. // issued. But `pos` is actually only used to compute an array index to
  567. // write to.
  568. #if !defined(__clang__) && defined(__GNUC__)
  569. #pragma GCC diagnostic push
  570. #pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
  571. #endif
  572. return storage_.Insert(pos, CopyValueAdapter<A>(std::addressof(dealias)),
  573. n);
  574. #if !defined(__clang__) && defined(__GNUC__)
  575. #pragma GCC diagnostic pop
  576. #endif
  577. } else {
  578. return const_cast<iterator>(pos);
  579. }
  580. }
  581. // Overload of `InlinedVector::insert(...)` that inserts copies of the
  582. // elements of `list` starting at `pos`, returning an `iterator` pointing to
  583. // the first of the newly inserted elements.
  584. iterator insert(const_iterator pos, std::initializer_list<value_type> list)
  585. ABSL_ATTRIBUTE_LIFETIME_BOUND {
  586. return insert(pos, list.begin(), list.end());
  587. }
  588. // Overload of `InlinedVector::insert(...)` that inserts the range [`first`,
  589. // `last`) starting at `pos`, returning an `iterator` pointing to the first
  590. // of the newly inserted elements.
  591. //
  592. // NOTE: this overload is for iterators that are "forward" category or better.
  593. template <typename ForwardIterator,
  594. EnableIfAtLeastForwardIterator<ForwardIterator> = 0>
  595. iterator insert(const_iterator pos, ForwardIterator first,
  596. ForwardIterator last) ABSL_ATTRIBUTE_LIFETIME_BOUND {
  597. ABSL_HARDENING_ASSERT(pos >= begin());
  598. ABSL_HARDENING_ASSERT(pos <= end());
  599. if (ABSL_PREDICT_TRUE(first != last)) {
  600. return storage_.Insert(
  601. pos, IteratorValueAdapter<A, ForwardIterator>(first),
  602. static_cast<size_type>(std::distance(first, last)));
  603. } else {
  604. return const_cast<iterator>(pos);
  605. }
  606. }
  607. // Overload of `InlinedVector::insert(...)` that inserts the range [`first`,
  608. // `last`) starting at `pos`, returning an `iterator` pointing to the first
  609. // of the newly inserted elements.
  610. //
  611. // NOTE: this overload is for iterators that are "input" category.
  612. template <typename InputIterator,
  613. DisableIfAtLeastForwardIterator<InputIterator> = 0>
  614. iterator insert(const_iterator pos, InputIterator first,
  615. InputIterator last) ABSL_ATTRIBUTE_LIFETIME_BOUND {
  616. ABSL_HARDENING_ASSERT(pos >= begin());
  617. ABSL_HARDENING_ASSERT(pos <= end());
  618. size_type index = static_cast<size_type>(std::distance(cbegin(), pos));
  619. for (size_type i = index; first != last; ++i, static_cast<void>(++first)) {
  620. insert(data() + i, *first);
  621. }
  622. return iterator(data() + index);
  623. }
  624. // `InlinedVector::emplace(...)`
  625. //
  626. // Constructs and inserts an element using `args...` in the inlined vector at
  627. // `pos`, returning an `iterator` pointing to the newly emplaced element.
  628. template <typename... Args>
  629. iterator emplace(const_iterator pos,
  630. Args&&... args) ABSL_ATTRIBUTE_LIFETIME_BOUND {
  631. ABSL_HARDENING_ASSERT(pos >= begin());
  632. ABSL_HARDENING_ASSERT(pos <= end());
  633. value_type dealias(std::forward<Args>(args)...);
  634. // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=102329#c2
  635. // It appears that GCC thinks that since `pos` is a const pointer and may
  636. // point to uninitialized memory at this point, a warning should be
  637. // issued. But `pos` is actually only used to compute an array index to
  638. // write to.
  639. #if !defined(__clang__) && defined(__GNUC__)
  640. #pragma GCC diagnostic push
  641. #pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
  642. #endif
  643. return storage_.Insert(pos,
  644. IteratorValueAdapter<A, MoveIterator<A>>(
  645. MoveIterator<A>(std::addressof(dealias))),
  646. 1);
  647. #if !defined(__clang__) && defined(__GNUC__)
  648. #pragma GCC diagnostic pop
  649. #endif
  650. }
  651. // `InlinedVector::emplace_back(...)`
  652. //
  653. // Constructs and inserts an element using `args...` in the inlined vector at
  654. // `end()`, returning a `reference` to the newly emplaced element.
  655. template <typename... Args>
  656. reference emplace_back(Args&&... args) ABSL_ATTRIBUTE_LIFETIME_BOUND {
  657. return storage_.EmplaceBack(std::forward<Args>(args)...);
  658. }
  659. // `InlinedVector::push_back(...)`
  660. //
  661. // Inserts a copy of `v` in the inlined vector at `end()`.
  662. void push_back(const_reference v) { static_cast<void>(emplace_back(v)); }
  663. // Overload of `InlinedVector::push_back(...)` for inserting `v` at `end()`
  664. // using move semantics.
  665. void push_back(value_type&& v) {
  666. static_cast<void>(emplace_back(std::move(v)));
  667. }
  668. // `InlinedVector::pop_back()`
  669. //
  670. // Destroys the element at `back()`, reducing the size by `1`.
  671. void pop_back() noexcept {
  672. ABSL_HARDENING_ASSERT(!empty());
  673. AllocatorTraits<A>::destroy(storage_.GetAllocator(), data() + (size() - 1));
  674. storage_.SubtractSize(1);
  675. }
  676. // `InlinedVector::erase(...)`
  677. //
  678. // Erases the element at `pos`, returning an `iterator` pointing to where the
  679. // erased element was located.
  680. //
  681. // NOTE: may return `end()`, which is not dereferenceable.
  682. iterator erase(const_iterator pos) ABSL_ATTRIBUTE_LIFETIME_BOUND {
  683. ABSL_HARDENING_ASSERT(pos >= begin());
  684. ABSL_HARDENING_ASSERT(pos < end());
  685. // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=102329#c2
  686. // It appears that GCC thinks that since `pos` is a const pointer and may
  687. // point to uninitialized memory at this point, a warning should be
  688. // issued. But `pos` is actually only used to compute an array index to
  689. // write to.
  690. #if !defined(__clang__) && defined(__GNUC__)
  691. #pragma GCC diagnostic push
  692. #pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
  693. #pragma GCC diagnostic ignored "-Wuninitialized"
  694. #endif
  695. return storage_.Erase(pos, pos + 1);
  696. #if !defined(__clang__) && defined(__GNUC__)
  697. #pragma GCC diagnostic pop
  698. #endif
  699. }
  700. // Overload of `InlinedVector::erase(...)` that erases every element in the
  701. // range [`from`, `to`), returning an `iterator` pointing to where the first
  702. // erased element was located.
  703. //
  704. // NOTE: may return `end()`, which is not dereferenceable.
  705. iterator erase(const_iterator from,
  706. const_iterator to) ABSL_ATTRIBUTE_LIFETIME_BOUND {
  707. ABSL_HARDENING_ASSERT(from >= begin());
  708. ABSL_HARDENING_ASSERT(from <= to);
  709. ABSL_HARDENING_ASSERT(to <= end());
  710. if (ABSL_PREDICT_TRUE(from != to)) {
  711. return storage_.Erase(from, to);
  712. } else {
  713. return const_cast<iterator>(from);
  714. }
  715. }
  716. // `InlinedVector::clear()`
  717. //
  718. // Destroys all elements in the inlined vector, setting the size to `0` and
  719. // deallocating any held memory.
  720. void clear() noexcept {
  721. inlined_vector_internal::DestroyAdapter<A>::DestroyElements(
  722. storage_.GetAllocator(), data(), size());
  723. storage_.DeallocateIfAllocated();
  724. storage_.SetInlinedSize(0);
  725. }
  726. // `InlinedVector::reserve(...)`
  727. //
  728. // Ensures that there is enough room for at least `n` elements.
  729. void reserve(size_type n) { storage_.Reserve(n); }
  730. // `InlinedVector::shrink_to_fit()`
  731. //
  732. // Attempts to reduce memory usage by moving elements to (or keeping elements
  733. // in) the smallest available buffer sufficient for containing `size()`
  734. // elements.
  735. //
  736. // If `size()` is sufficiently small, the elements will be moved into (or kept
  737. // in) the inlined space.
  738. void shrink_to_fit() {
  739. if (storage_.GetIsAllocated()) {
  740. storage_.ShrinkToFit();
  741. }
  742. }
  743. // `InlinedVector::swap(...)`
  744. //
  745. // Swaps the contents of the inlined vector with `other`.
  746. void swap(InlinedVector& other) {
  747. if (ABSL_PREDICT_TRUE(this != std::addressof(other))) {
  748. storage_.Swap(std::addressof(other.storage_));
  749. }
  750. }
  751. private:
  752. template <typename H, typename TheT, size_t TheN, typename TheA>
  753. friend H AbslHashValue(H h, const absl::InlinedVector<TheT, TheN, TheA>& a);
  754. void MoveAssignment(MemcpyPolicy, InlinedVector&& other) {
  755. // Assumption check: we shouldn't be told to use memcpy to implement move
  756. // assignment unless we have trivially destructible elements and an
  757. // allocator that does nothing fancy.
  758. static_assert(absl::is_trivially_destructible<value_type>::value, "");
  759. static_assert(std::is_same<A, std::allocator<value_type>>::value, "");
  760. // Throw away our existing heap allocation, if any. There is no need to
  761. // destroy the existing elements one by one because we know they are
  762. // trivially destructible.
  763. storage_.DeallocateIfAllocated();
  764. // Adopt the other vector's inline elements or heap allocation.
  765. storage_.MemcpyFrom(other.storage_);
  766. other.storage_.SetInlinedSize(0);
  767. }
  768. // Destroy our existing elements, if any, and adopt the heap-allocated
  769. // elements of the other vector.
  770. //
  771. // REQUIRES: other.storage_.GetIsAllocated()
  772. void DestroyExistingAndAdopt(InlinedVector&& other) {
  773. ABSL_HARDENING_ASSERT(other.storage_.GetIsAllocated());
  774. inlined_vector_internal::DestroyAdapter<A>::DestroyElements(
  775. storage_.GetAllocator(), data(), size());
  776. storage_.DeallocateIfAllocated();
  777. storage_.MemcpyFrom(other.storage_);
  778. other.storage_.SetInlinedSize(0);
  779. }
  780. void MoveAssignment(ElementwiseAssignPolicy, InlinedVector&& other) {
  781. // Fast path: if the other vector is on the heap then we don't worry about
  782. // actually move-assigning each element. Instead we only throw away our own
  783. // existing elements and adopt the heap allocation of the other vector.
  784. if (other.storage_.GetIsAllocated()) {
  785. DestroyExistingAndAdopt(std::move(other));
  786. return;
  787. }
  788. storage_.Assign(IteratorValueAdapter<A, MoveIterator<A>>(
  789. MoveIterator<A>(other.storage_.GetInlinedData())),
  790. other.size());
  791. }
  792. void MoveAssignment(ElementwiseConstructPolicy, InlinedVector&& other) {
  793. // Fast path: if the other vector is on the heap then we don't worry about
  794. // actually move-assigning each element. Instead we only throw away our own
  795. // existing elements and adopt the heap allocation of the other vector.
  796. if (other.storage_.GetIsAllocated()) {
  797. DestroyExistingAndAdopt(std::move(other));
  798. return;
  799. }
  800. inlined_vector_internal::DestroyAdapter<A>::DestroyElements(
  801. storage_.GetAllocator(), data(), size());
  802. storage_.DeallocateIfAllocated();
  803. IteratorValueAdapter<A, MoveIterator<A>> other_values(
  804. MoveIterator<A>(other.storage_.GetInlinedData()));
  805. inlined_vector_internal::ConstructElements<A>(
  806. storage_.GetAllocator(), storage_.GetInlinedData(), other_values,
  807. other.storage_.GetSize());
  808. storage_.SetInlinedSize(other.storage_.GetSize());
  809. }
  810. Storage storage_;
  811. };
  812. // -----------------------------------------------------------------------------
  813. // InlinedVector Non-Member Functions
  814. // -----------------------------------------------------------------------------
  815. // `swap(...)`
  816. //
  817. // Swaps the contents of two inlined vectors.
  818. template <typename T, size_t N, typename A>
  819. void swap(absl::InlinedVector<T, N, A>& a,
  820. absl::InlinedVector<T, N, A>& b) noexcept(noexcept(a.swap(b))) {
  821. a.swap(b);
  822. }
  823. // `operator==(...)`
  824. //
  825. // Tests for value-equality of two inlined vectors.
  826. template <typename T, size_t N, typename A>
  827. bool operator==(const absl::InlinedVector<T, N, A>& a,
  828. const absl::InlinedVector<T, N, A>& b) {
  829. auto a_data = a.data();
  830. auto b_data = b.data();
  831. return std::equal(a_data, a_data + a.size(), b_data, b_data + b.size());
  832. }
  833. // `operator!=(...)`
  834. //
  835. // Tests for value-inequality of two inlined vectors.
  836. template <typename T, size_t N, typename A>
  837. bool operator!=(const absl::InlinedVector<T, N, A>& a,
  838. const absl::InlinedVector<T, N, A>& b) {
  839. return !(a == b);
  840. }
  841. // `operator<(...)`
  842. //
  843. // Tests whether the value of an inlined vector is less than the value of
  844. // another inlined vector using a lexicographical comparison algorithm.
  845. template <typename T, size_t N, typename A>
  846. bool operator<(const absl::InlinedVector<T, N, A>& a,
  847. const absl::InlinedVector<T, N, A>& b) {
  848. auto a_data = a.data();
  849. auto b_data = b.data();
  850. return std::lexicographical_compare(a_data, a_data + a.size(), b_data,
  851. b_data + b.size());
  852. }
  853. // `operator>(...)`
  854. //
  855. // Tests whether the value of an inlined vector is greater than the value of
  856. // another inlined vector using a lexicographical comparison algorithm.
  857. template <typename T, size_t N, typename A>
  858. bool operator>(const absl::InlinedVector<T, N, A>& a,
  859. const absl::InlinedVector<T, N, A>& b) {
  860. return b < a;
  861. }
  862. // `operator<=(...)`
  863. //
  864. // Tests whether the value of an inlined vector is less than or equal to the
  865. // value of another inlined vector using a lexicographical comparison algorithm.
  866. template <typename T, size_t N, typename A>
  867. bool operator<=(const absl::InlinedVector<T, N, A>& a,
  868. const absl::InlinedVector<T, N, A>& b) {
  869. return !(b < a);
  870. }
  871. // `operator>=(...)`
  872. //
  873. // Tests whether the value of an inlined vector is greater than or equal to the
  874. // value of another inlined vector using a lexicographical comparison algorithm.
  875. template <typename T, size_t N, typename A>
  876. bool operator>=(const absl::InlinedVector<T, N, A>& a,
  877. const absl::InlinedVector<T, N, A>& b) {
  878. return !(a < b);
  879. }
  880. // `AbslHashValue(...)`
  881. //
  882. // Provides `absl::Hash` support for `absl::InlinedVector`. It is uncommon to
  883. // call this directly.
  884. template <typename H, typename T, size_t N, typename A>
  885. H AbslHashValue(H h, const absl::InlinedVector<T, N, A>& a) {
  886. auto size = a.size();
  887. return H::combine(H::combine_contiguous(std::move(h), a.data(), size), size);
  888. }
  889. ABSL_NAMESPACE_END
  890. } // namespace absl
  891. #endif // ABSL_CONTAINER_INLINED_VECTOR_H_