small_vector.h 12 KB

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