small_vector.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. // Copyright (c) 2018 Google LLC
  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. // http://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. #ifndef SOURCE_UTIL_SMALL_VECTOR_H_
  15. #define SOURCE_UTIL_SMALL_VECTOR_H_
  16. #include <cassert>
  17. #include <iostream>
  18. #include <memory>
  19. #include <utility>
  20. #include <vector>
  21. #include "source/util/make_unique.h"
  22. namespace spvtools {
  23. namespace utils {
  24. // The |SmallVector| class is intended to be a drop-in replacement for
  25. // |std::vector|. The difference is in the implementation. A |SmallVector| is
  26. // optimized for when the number of elements in the vector are small. Small is
  27. // defined by the template parameter |small_size|.
  28. //
  29. // Note that |SmallVector| is not always faster than an |std::vector|, so you
  30. // should experiment with different values for |small_size| and compare to
  31. // using and |std::vector|.
  32. //
  33. // TODO: I have implemented the public member functions from |std::vector| that
  34. // I needed. If others are needed they should be implemented. Do not implement
  35. // public member functions that are not defined by std::vector.
  36. template <class T, size_t small_size>
  37. class SmallVector {
  38. public:
  39. using iterator = T*;
  40. using const_iterator = const T*;
  41. SmallVector()
  42. : size_(0),
  43. small_data_(reinterpret_cast<T*>(buffer)),
  44. large_data_(nullptr) {}
  45. SmallVector(const SmallVector& that) : SmallVector() { *this = that; }
  46. SmallVector(SmallVector&& that) : SmallVector() { *this = std::move(that); }
  47. SmallVector(const std::vector<T>& vec) : SmallVector() {
  48. if (vec.size() > small_size) {
  49. large_data_ = MakeUnique<std::vector<T>>(vec);
  50. } else {
  51. size_ = vec.size();
  52. for (uint32_t i = 0; i < size_; i++) {
  53. new (small_data_ + i) T(vec[i]);
  54. }
  55. }
  56. }
  57. template <class InputIt>
  58. SmallVector(InputIt first, InputIt last) : SmallVector() {
  59. insert(end(), first, last);
  60. }
  61. SmallVector(std::vector<T>&& vec) : SmallVector() {
  62. if (vec.size() > small_size) {
  63. large_data_ = MakeUnique<std::vector<T>>(std::move(vec));
  64. } else {
  65. size_ = vec.size();
  66. for (uint32_t i = 0; i < size_; i++) {
  67. new (small_data_ + i) T(std::move(vec[i]));
  68. }
  69. }
  70. vec.clear();
  71. }
  72. SmallVector(std::initializer_list<T> init_list) : SmallVector() {
  73. if (init_list.size() < small_size) {
  74. for (auto it = init_list.begin(); it != init_list.end(); ++it) {
  75. new (small_data_ + (size_++)) T(std::move(*it));
  76. }
  77. } else {
  78. large_data_ = MakeUnique<std::vector<T>>(std::move(init_list));
  79. }
  80. }
  81. SmallVector(size_t s, const T& v) : SmallVector() { resize(s, v); }
  82. virtual ~SmallVector() {
  83. for (T* p = small_data_; p < small_data_ + size_; ++p) {
  84. p->~T();
  85. }
  86. }
  87. SmallVector& operator=(const SmallVector& that) {
  88. assert(small_data_);
  89. if (that.large_data_) {
  90. if (large_data_) {
  91. *large_data_ = *that.large_data_;
  92. } else {
  93. large_data_ = MakeUnique<std::vector<T>>(*that.large_data_);
  94. }
  95. } else {
  96. large_data_.reset(nullptr);
  97. size_t i = 0;
  98. // Do a copy for any element in |this| that is already constructed.
  99. for (; i < size_ && i < that.size_; ++i) {
  100. small_data_[i] = that.small_data_[i];
  101. }
  102. if (i >= that.size_) {
  103. // If the size of |this| becomes smaller after the assignment, then
  104. // destroy any extra elements.
  105. for (; i < size_; ++i) {
  106. small_data_[i].~T();
  107. }
  108. } else {
  109. // If the size of |this| becomes larger after the assignement, copy
  110. // construct the new elements that are needed.
  111. for (; i < that.size_; ++i) {
  112. new (small_data_ + i) T(that.small_data_[i]);
  113. }
  114. }
  115. size_ = that.size_;
  116. }
  117. return *this;
  118. }
  119. SmallVector& operator=(SmallVector&& that) {
  120. if (that.large_data_) {
  121. large_data_.reset(that.large_data_.release());
  122. } else {
  123. large_data_.reset(nullptr);
  124. size_t i = 0;
  125. // Do a move for any element in |this| that is already constructed.
  126. for (; i < size_ && i < that.size_; ++i) {
  127. small_data_[i] = std::move(that.small_data_[i]);
  128. }
  129. if (i >= that.size_) {
  130. // If the size of |this| becomes smaller after the assignment, then
  131. // destroy any extra elements.
  132. for (; i < size_; ++i) {
  133. small_data_[i].~T();
  134. }
  135. } else {
  136. // If the size of |this| becomes larger after the assignement, move
  137. // construct the new elements that are needed.
  138. for (; i < that.size_; ++i) {
  139. new (small_data_ + i) T(std::move(that.small_data_[i]));
  140. }
  141. }
  142. size_ = that.size_;
  143. }
  144. // Reset |that| because all of the data has been moved to |this|.
  145. that.DestructSmallData();
  146. return *this;
  147. }
  148. template <class OtherVector>
  149. friend bool operator==(const SmallVector& lhs, const OtherVector& rhs) {
  150. if (lhs.size() != rhs.size()) {
  151. return false;
  152. }
  153. auto rit = rhs.begin();
  154. for (auto lit = lhs.begin(); lit != lhs.end(); ++lit, ++rit) {
  155. if (*lit != *rit) {
  156. return false;
  157. }
  158. }
  159. return true;
  160. }
  161. // Avoid infinite recursion from rewritten operators in C++20
  162. #if __cplusplus <= 201703L
  163. friend bool operator==(const std::vector<T>& lhs, const SmallVector& rhs) {
  164. return rhs == lhs;
  165. }
  166. #endif
  167. friend bool operator!=(const SmallVector& lhs, const std::vector<T>& rhs) {
  168. return !(lhs == rhs);
  169. }
  170. friend bool operator!=(const std::vector<T>& lhs, const SmallVector& rhs) {
  171. return rhs != lhs;
  172. }
  173. T& operator[](size_t i) {
  174. if (!large_data_) {
  175. return small_data_[i];
  176. } else {
  177. return (*large_data_)[i];
  178. }
  179. }
  180. const T& operator[](size_t i) const {
  181. if (!large_data_) {
  182. return small_data_[i];
  183. } else {
  184. return (*large_data_)[i];
  185. }
  186. }
  187. size_t size() const {
  188. if (!large_data_) {
  189. return size_;
  190. } else {
  191. return large_data_->size();
  192. }
  193. }
  194. iterator begin() {
  195. if (large_data_) {
  196. return large_data_->data();
  197. } else {
  198. return small_data_;
  199. }
  200. }
  201. const_iterator begin() const {
  202. if (large_data_) {
  203. return large_data_->data();
  204. } else {
  205. return small_data_;
  206. }
  207. }
  208. const_iterator cbegin() const { return begin(); }
  209. iterator end() {
  210. if (large_data_) {
  211. return large_data_->data() + large_data_->size();
  212. } else {
  213. return small_data_ + size_;
  214. }
  215. }
  216. const_iterator end() const {
  217. if (large_data_) {
  218. return large_data_->data() + large_data_->size();
  219. } else {
  220. return small_data_ + size_;
  221. }
  222. }
  223. const_iterator cend() const { return end(); }
  224. T* data() { return begin(); }
  225. const T* data() const { return cbegin(); }
  226. T& front() { return (*this)[0]; }
  227. const T& front() const { return (*this)[0]; }
  228. iterator erase(const_iterator pos) { return erase(pos, pos + 1); }
  229. iterator erase(const_iterator first, const_iterator last) {
  230. if (large_data_) {
  231. size_t start_index = first - large_data_->data();
  232. size_t end_index = last - large_data_->data();
  233. auto r = large_data_->erase(large_data_->begin() + start_index,
  234. large_data_->begin() + end_index);
  235. return large_data_->data() + (r - large_data_->begin());
  236. }
  237. // Since C++11, std::vector has |const_iterator| for the parameters, so I
  238. // follow that. However, I need iterators to modify the current container,
  239. // which is not const. This is why I cast away the const.
  240. iterator f = const_cast<iterator>(first);
  241. iterator l = const_cast<iterator>(last);
  242. iterator e = end();
  243. size_t num_of_del_elements = last - first;
  244. iterator ret = f;
  245. if (first == last) {
  246. return ret;
  247. }
  248. // Move |last| and any elements after it their earlier position.
  249. while (l != e) {
  250. *f = std::move(*l);
  251. ++f;
  252. ++l;
  253. }
  254. // Destroy the elements that were supposed to be deleted.
  255. while (f != l) {
  256. f->~T();
  257. ++f;
  258. }
  259. // Update the size.
  260. size_ -= num_of_del_elements;
  261. return ret;
  262. }
  263. void push_back(const T& value) {
  264. if (!large_data_ && size_ == small_size) {
  265. MoveToLargeData();
  266. }
  267. if (large_data_) {
  268. large_data_->push_back(value);
  269. return;
  270. }
  271. new (small_data_ + size_) T(value);
  272. ++size_;
  273. }
  274. void push_back(T&& value) {
  275. if (!large_data_ && size_ == small_size) {
  276. MoveToLargeData();
  277. }
  278. if (large_data_) {
  279. large_data_->push_back(std::move(value));
  280. return;
  281. }
  282. new (small_data_ + size_) T(std::move(value));
  283. ++size_;
  284. }
  285. void pop_back() {
  286. if (large_data_) {
  287. large_data_->pop_back();
  288. } else {
  289. --size_;
  290. small_data_[size_].~T();
  291. }
  292. }
  293. template <class InputIt>
  294. iterator insert(iterator pos, InputIt first, InputIt last) {
  295. size_t element_idx = (pos - begin());
  296. size_t num_of_new_elements = std::distance(first, last);
  297. size_t new_size = size_ + num_of_new_elements;
  298. if (!large_data_ && new_size > small_size) {
  299. MoveToLargeData();
  300. }
  301. if (large_data_) {
  302. typename std::vector<T>::iterator new_pos =
  303. large_data_->begin() + element_idx;
  304. large_data_->insert(new_pos, first, last);
  305. return begin() + element_idx;
  306. }
  307. // Move |pos| and all of the elements after it over |num_of_new_elements|
  308. // places. We start at the end and work backwards, to make sure we do not
  309. // overwrite data that we have not moved yet.
  310. for (iterator i = begin() + new_size - 1, j = end() - 1; j >= pos;
  311. --i, --j) {
  312. if (i >= begin() + size_) {
  313. new (i) T(std::move(*j));
  314. } else {
  315. *i = std::move(*j);
  316. }
  317. }
  318. // Copy the new elements into position.
  319. iterator p = pos;
  320. for (; first != last; ++p, ++first) {
  321. if (p >= small_data_ + size_) {
  322. new (p) T(*first);
  323. } else {
  324. *p = *first;
  325. }
  326. }
  327. // Update the size.
  328. size_ += num_of_new_elements;
  329. return pos;
  330. }
  331. bool empty() const {
  332. if (large_data_) {
  333. return large_data_->empty();
  334. }
  335. return size_ == 0;
  336. }
  337. void clear() {
  338. if (large_data_) {
  339. large_data_->clear();
  340. } else {
  341. DestructSmallData();
  342. }
  343. }
  344. template <class... Args>
  345. void emplace_back(Args&&... args) {
  346. if (!large_data_ && size_ == small_size) {
  347. MoveToLargeData();
  348. }
  349. if (large_data_) {
  350. large_data_->emplace_back(std::forward<Args>(args)...);
  351. } else {
  352. new (small_data_ + size_) T(std::forward<Args>(args)...);
  353. ++size_;
  354. }
  355. }
  356. void resize(size_t new_size, const T& v) {
  357. if (!large_data_ && new_size > small_size) {
  358. MoveToLargeData();
  359. }
  360. if (large_data_) {
  361. large_data_->resize(new_size, v);
  362. return;
  363. }
  364. // If |new_size| < |size_|, then destroy the extra elements.
  365. for (size_t i = new_size; i < size_; ++i) {
  366. small_data_[i].~T();
  367. }
  368. // If |new_size| > |size_|, the copy construct the new elements.
  369. for (size_t i = size_; i < new_size; ++i) {
  370. new (small_data_ + i) T(v);
  371. }
  372. // Update the size.
  373. size_ = new_size;
  374. }
  375. private:
  376. // Moves all of the element from |small_data_| into a new std::vector that can
  377. // be access through |large_data|.
  378. void MoveToLargeData() {
  379. assert(!large_data_);
  380. large_data_ = MakeUnique<std::vector<T>>();
  381. for (size_t i = 0; i < size_; ++i) {
  382. large_data_->emplace_back(std::move(small_data_[i]));
  383. }
  384. DestructSmallData();
  385. }
  386. // Destroys all of the elements in |small_data_| that have been constructed.
  387. void DestructSmallData() {
  388. for (size_t i = 0; i < size_; ++i) {
  389. small_data_[i].~T();
  390. }
  391. size_ = 0;
  392. }
  393. // The number of elements in |small_data_| that have been constructed.
  394. size_t size_;
  395. // The pointed used to access the array of elements when the number of
  396. // elements is small.
  397. T* small_data_;
  398. // The actual data used to store the array elements. It must never be used
  399. // directly, but must only be accessed through |small_data_|.
  400. typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type
  401. buffer[small_size];
  402. // A pointer to a vector that is used to store the elements of the vector when
  403. // this size exceeds |small_size|. If |large_data_| is nullptr, then the data
  404. // is stored in |small_data_|. Otherwise, the data is stored in
  405. // |large_data_|.
  406. std::unique_ptr<std::vector<T>> large_data_;
  407. }; // namespace utils
  408. } // namespace utils
  409. } // namespace spvtools
  410. #endif // SOURCE_UTIL_SMALL_VECTOR_H_