inlineskiplist.h 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204
  1. // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
  2. // This source code is licensed under both the GPLv2 (found in the
  3. // COPYING file in the root directory) and Apache 2.0 License
  4. // (found in the LICENSE.Apache file in the root directory).
  5. //
  6. // Copyright (c) 2011 The LevelDB Authors. All rights reserved. Use of
  7. // this source code is governed by a BSD-style license that can be found
  8. // in the LICENSE file. See the AUTHORS file for names of contributors.
  9. //
  10. // InlineSkipList is derived from SkipList (skiplist.h), but it optimizes
  11. // the memory layout by requiring that the key storage be allocated through
  12. // the skip list instance. For the common case of SkipList<const char*,
  13. // Cmp> this saves 1 pointer per skip list node and gives better cache
  14. // locality, at the expense of wasted padding from using AllocateAligned
  15. // instead of Allocate for the keys. The unused padding will be from
  16. // 0 to sizeof(void*)-1 bytes, and the space savings are sizeof(void*)
  17. // bytes, so despite the padding the space used is always less than
  18. // SkipList<const char*, ..>.
  19. //
  20. // Thread safety -------------
  21. //
  22. // Writes via Insert require external synchronization, most likely a mutex.
  23. // InsertConcurrently can be safely called concurrently with reads and
  24. // with other concurrent inserts. Reads require a guarantee that the
  25. // InlineSkipList will not be destroyed while the read is in progress.
  26. // Apart from that, reads progress without any internal locking or
  27. // synchronization.
  28. //
  29. // Invariants:
  30. //
  31. // (1) Allocated nodes are never deleted until the InlineSkipList is
  32. // destroyed. This is trivially guaranteed by the code since we never
  33. // delete any skip list nodes.
  34. //
  35. // (2) The contents of a Node except for the next/prev pointers are
  36. // immutable after the Node has been linked into the InlineSkipList.
  37. // Only Insert() modifies the list, and it is careful to initialize a
  38. // node and use release-stores to publish the nodes in one or more lists.
  39. //
  40. // ... prev vs. next pointer ordering ...
  41. //
  42. #pragma once
  43. #include <assert.h>
  44. #include <stdlib.h>
  45. #include <type_traits>
  46. #include "memory/allocator.h"
  47. #include "port/likely.h"
  48. #include "port/port.h"
  49. #include "rocksdb/slice.h"
  50. #include "test_util/sync_point.h"
  51. #include "util/atomic.h"
  52. #include "util/random.h"
  53. namespace ROCKSDB_NAMESPACE {
  54. template <class Comparator>
  55. class InlineSkipList {
  56. private:
  57. struct Node;
  58. struct Splice;
  59. public:
  60. using DecodedKey =
  61. typename std::remove_reference<Comparator>::type::DecodedType;
  62. static const uint16_t kMaxPossibleHeight = 32;
  63. // Create a new InlineSkipList object that will use "cmp" for comparing
  64. // keys, and will allocate memory using "*allocator". Objects allocated
  65. // in the allocator must remain allocated for the lifetime of the
  66. // skiplist object.
  67. explicit InlineSkipList(Comparator cmp, Allocator* allocator,
  68. int32_t max_height = 12,
  69. int32_t branching_factor = 4);
  70. // No copying allowed
  71. InlineSkipList(const InlineSkipList&) = delete;
  72. InlineSkipList& operator=(const InlineSkipList&) = delete;
  73. // Allocates a key and a skip-list node, returning a pointer to the key
  74. // portion of the node. This method is thread-safe if the allocator
  75. // is thread-safe.
  76. char* AllocateKey(size_t key_size);
  77. // Allocate a splice using allocator.
  78. Splice* AllocateSplice();
  79. // Allocate a splice on heap.
  80. Splice* AllocateSpliceOnHeap();
  81. // Inserts a key allocated by AllocateKey, after the actual key value
  82. // has been filled in.
  83. //
  84. // REQUIRES: nothing that compares equal to key is currently in the list.
  85. // REQUIRES: no concurrent calls to any of inserts.
  86. bool Insert(const char* key);
  87. // Inserts a key allocated by AllocateKey with a hint of last insert
  88. // position in the skip-list. If hint points to nullptr, a new hint will be
  89. // populated, which can be used in subsequent calls.
  90. //
  91. // It can be used to optimize the workload where there are multiple groups
  92. // of keys, and each key is likely to insert to a location close to the last
  93. // inserted key in the same group. One example is sequential inserts.
  94. //
  95. // REQUIRES: nothing that compares equal to key is currently in the list.
  96. // REQUIRES: no concurrent calls to any of inserts.
  97. bool InsertWithHint(const char* key, void** hint);
  98. // Like InsertConcurrently, but with a hint
  99. //
  100. // REQUIRES: nothing that compares equal to key is currently in the list.
  101. // REQUIRES: no concurrent calls that use same hint
  102. bool InsertWithHintConcurrently(const char* key, void** hint);
  103. // Like Insert, but external synchronization is not required.
  104. bool InsertConcurrently(const char* key);
  105. // Inserts a node into the skip list. key must have been allocated by
  106. // AllocateKey and then filled in by the caller. If UseCAS is true,
  107. // then external synchronization is not required, otherwise this method
  108. // may not be called concurrently with any other insertions.
  109. //
  110. // Regardless of whether UseCAS is true, the splice must be owned
  111. // exclusively by the current thread. If allow_partial_splice_fix is
  112. // true, then the cost of insertion is amortized O(log D), where D is
  113. // the distance from the splice to the inserted key (measured as the
  114. // number of intervening nodes). Note that this bound is very good for
  115. // sequential insertions! If allow_partial_splice_fix is false then
  116. // the existing splice will be ignored unless the current key is being
  117. // inserted immediately after the splice. allow_partial_splice_fix ==
  118. // false has worse running time for the non-sequential case O(log N),
  119. // but a better constant factor.
  120. template <bool UseCAS>
  121. bool Insert(const char* key, Splice* splice, bool allow_partial_splice_fix);
  122. // Returns true iff an entry that compares equal to key is in the list.
  123. bool Contains(const char* key) const;
  124. // Return estimated number of entries from `start_ikey` to `end_ikey`.
  125. uint64_t ApproximateNumEntries(const Slice& start_ikey,
  126. const Slice& end_ikey) const;
  127. // Validate correctness of the skip-list.
  128. void TEST_Validate() const;
  129. // Iteration over the contents of a skip list
  130. class Iterator {
  131. public:
  132. // Initialize an iterator over the specified list.
  133. // The returned iterator is not valid.
  134. explicit Iterator(const InlineSkipList* list);
  135. // Change the underlying skiplist used for this iterator
  136. // This enables us not changing the iterator without deallocating
  137. // an old one and then allocating a new one
  138. void SetList(const InlineSkipList* list);
  139. // Returns true iff the iterator is positioned at a valid node.
  140. bool Valid() const;
  141. // Returns the key at the current position.
  142. // REQUIRES: Valid()
  143. const char* key() const;
  144. // Advances to the next position.
  145. // REQUIRES: Valid()
  146. void Next();
  147. [[nodiscard]] Status NextAndValidate(bool allow_data_in_errors);
  148. // Advances to the previous position.
  149. // REQUIRES: Valid()
  150. void Prev();
  151. [[nodiscard]] Status PrevAndValidate(bool allow_data_in_errors);
  152. // Advance to the first entry with a key >= target
  153. void Seek(const char* target);
  154. [[nodiscard]] Status SeekAndValidate(
  155. const char* target, bool allow_data_in_errors,
  156. bool detect_key_out_of_order,
  157. const std::function<Status(const char*, bool)>&
  158. key_validation_callback);
  159. // Retreat to the last entry with a key <= target
  160. void SeekForPrev(const char* target);
  161. // Advance to a random entry in the list.
  162. void RandomSeek();
  163. // Position at the first entry in list.
  164. // Final state of iterator is Valid() iff list is not empty.
  165. void SeekToFirst();
  166. // Position at the last entry in list.
  167. // Final state of iterator is Valid() iff list is not empty.
  168. void SeekToLast();
  169. private:
  170. const InlineSkipList* list_;
  171. Node* node_;
  172. // Intentionally copyable
  173. };
  174. private:
  175. const uint16_t kMaxHeight_;
  176. const uint16_t kBranching_;
  177. const uint32_t kScaledInverseBranching_;
  178. Allocator* const allocator_; // Allocator used for allocations of nodes
  179. // Immutable after construction
  180. Comparator const compare_;
  181. Node* const head_;
  182. // Maximum height of any node in the list (or in the process of being added).
  183. // Modified only by Insert(). Relaxed reads are always OK because starting
  184. // from higher levels only helps efficiency, not correctness.
  185. RelaxedAtomic<int> max_height_;
  186. // seq_splice_ is a Splice used for insertions in the non-concurrent
  187. // case. It caches the prev and next found during the most recent
  188. // non-concurrent insertion.
  189. Splice* seq_splice_;
  190. inline int GetMaxHeight() const { return max_height_.LoadRelaxed(); }
  191. int RandomHeight();
  192. Node* AllocateNode(size_t key_size, int height);
  193. bool Equal(const char* a, const char* b) const {
  194. return (compare_(a, b) == 0);
  195. }
  196. bool LessThan(const char* a, const char* b) const {
  197. return (compare_(a, b) < 0);
  198. }
  199. // Return true if key is greater than the data stored in "n". Null n
  200. // is considered infinite. n should not be head_.
  201. bool KeyIsAfterNode(const char* key, Node* n) const;
  202. bool KeyIsAfterNode(const DecodedKey& key, Node* n) const;
  203. // Returns the earliest node with a key >= key.
  204. // Returns OK, if no corruption is found.
  205. // node is set to the found node, or to nullptr if no node is found.
  206. // Returns Corruption if a corruption is found.
  207. Status FindGreaterOrEqual(const char* key, Node** node,
  208. bool detect_key_out_of_order,
  209. bool allow_data_in_errors,
  210. const std::function<Status(const char*, bool)>&
  211. key_validation_callback) const;
  212. // Returns the latest node with a key < key.
  213. // Returns head_ if there is no such node.
  214. // Fills prev[level] with pointer to previous node at "level" for every
  215. // level in [0..max_height_-1], if prev is non-null.
  216. // @param corrupted_node If not null, will validate the order of visited
  217. // nodes. If a pair of out-of-order nodes n1 and n2 are found, n1 will be
  218. // returned and *corrupted_node will be set to n2.
  219. Node* FindLessThan(const char* key, Node** corrupted_node) const;
  220. // Return the last node in the list.
  221. // Return head_ if list is empty.
  222. Node* FindLast() const;
  223. // Returns a random entry.
  224. Node* FindRandomEntry() const;
  225. // Traverses a single level of the list, setting *out_prev to the last
  226. // node before the key and *out_next to the first node after. Assumes
  227. // that the key is not present in the skip list. On entry, before should
  228. // point to a node that is before the key, and after should point to
  229. // a node that is after the key. after should be nullptr if a good after
  230. // node isn't conveniently available.
  231. template <bool prefetch_before>
  232. void FindSpliceForLevel(const DecodedKey& key, Node* before, Node* after,
  233. int level, Node** out_prev, Node** out_next);
  234. // Recomputes Splice levels from highest_level (inclusive) down to
  235. // lowest_level (inclusive).
  236. void RecomputeSpliceLevels(const DecodedKey& key, Splice* splice,
  237. int recompute_level);
  238. static Status Corruption(Node* prev, Node* next, bool allow_data_in_errors);
  239. };
  240. // Implementation details follow
  241. template <class Comparator>
  242. struct InlineSkipList<Comparator>::Splice {
  243. // The invariant of a Splice is that prev_[i+1].key <= prev_[i].key <
  244. // next_[i].key <= next_[i+1].key for all i. That means that if a
  245. // key is bracketed by prev_[i] and next_[i] then it is bracketed by
  246. // all higher levels. It is _not_ required that prev_[i]->Next(i) ==
  247. // next_[i] (it probably did at some point in the past, but intervening
  248. // or concurrent operations might have inserted nodes in between).
  249. int height_ = 0;
  250. Node** prev_;
  251. Node** next_;
  252. };
  253. // The Node data type is more of a pointer into custom-managed memory than
  254. // a traditional C++ struct. The key is stored in the bytes immediately
  255. // after the struct, and the next_ pointers for nodes with height > 1 are
  256. // stored immediately _before_ the struct. This avoids the need to include
  257. // any pointer or sizing data, which reduces per-node memory overheads.
  258. template <class Comparator>
  259. struct InlineSkipList<Comparator>::Node {
  260. // Stores the height of the node in the memory location normally used for
  261. // next_[0]. This is used for passing data from AllocateKey to Insert.
  262. void StashHeight(const int height) {
  263. static_assert(sizeof(int) <= sizeof(next_[0]));
  264. memcpy(static_cast<void*>(&next_[0]), &height, sizeof(int));
  265. }
  266. // Retrieves the value passed to StashHeight. Undefined after a call
  267. // to SetNext or NoBarrier_SetNext.
  268. int UnstashHeight() const {
  269. int rv;
  270. memcpy(&rv, &next_[0], sizeof(int));
  271. return rv;
  272. }
  273. const char* Key() const { return reinterpret_cast<const char*>(&next_[1]); }
  274. // Accessors/mutators for links. Wrapped in methods so we can add
  275. // the appropriate barriers as necessary, and perform the necessary
  276. // addressing trickery for storing links below the Node in memory.
  277. Node* Next(int n) {
  278. assert(n >= 0);
  279. // Use an 'acquire load' so that we observe a fully initialized
  280. // version of the returned Node.
  281. return ((&next_[0] - n)->Load());
  282. }
  283. void SetNext(int n, Node* x) {
  284. assert(n >= 0);
  285. // Use a 'release store' so that anybody who reads through this
  286. // pointer observes a fully initialized version of the inserted node.
  287. (&next_[0] - n)->Store(x);
  288. }
  289. bool CASNext(int n, Node* expected, Node* x) {
  290. assert(n >= 0);
  291. return (&next_[0] - n)->CasStrong(expected, x);
  292. }
  293. // No-barrier variants that can be safely used in a few locations.
  294. Node* NoBarrier_Next(int n) {
  295. assert(n >= 0);
  296. return (&next_[0] - n)->LoadRelaxed();
  297. }
  298. void NoBarrier_SetNext(int n, Node* x) {
  299. assert(n >= 0);
  300. (&next_[0] - n)->StoreRelaxed(x);
  301. }
  302. // Insert node after prev on specific level.
  303. void InsertAfter(Node* prev, int level) {
  304. // NoBarrier_SetNext() suffices since we will add a barrier when
  305. // we publish a pointer to "this" in prev.
  306. NoBarrier_SetNext(level, prev->NoBarrier_Next(level));
  307. prev->SetNext(level, this);
  308. }
  309. private:
  310. // next_[0] is the lowest level link (level 0). Higher levels are
  311. // stored _earlier_, so level 1 is at next_[-1].
  312. AcqRelAtomic<Node*> next_[1];
  313. };
  314. template <class Comparator>
  315. inline InlineSkipList<Comparator>::Iterator::Iterator(
  316. const InlineSkipList* list) {
  317. SetList(list);
  318. }
  319. template <class Comparator>
  320. inline void InlineSkipList<Comparator>::Iterator::SetList(
  321. const InlineSkipList* list) {
  322. list_ = list;
  323. node_ = nullptr;
  324. }
  325. template <class Comparator>
  326. inline bool InlineSkipList<Comparator>::Iterator::Valid() const {
  327. return node_ != nullptr;
  328. }
  329. template <class Comparator>
  330. inline const char* InlineSkipList<Comparator>::Iterator::key() const {
  331. assert(Valid());
  332. return node_->Key();
  333. }
  334. template <class Comparator>
  335. inline void InlineSkipList<Comparator>::Iterator::Next() {
  336. assert(Valid());
  337. // Capture the key before move on to next node
  338. TEST_SYNC_POINT_CALLBACK(
  339. "InlineSkipList::Iterator::Next::key",
  340. static_cast<void*>(const_cast<char*>((node_->Key()))));
  341. node_ = node_->Next(0);
  342. }
  343. template <class Comparator>
  344. inline Status InlineSkipList<Comparator>::Iterator::NextAndValidate(
  345. bool allow_data_in_errors) {
  346. assert(Valid());
  347. // Capture the key before move on to next node
  348. TEST_SYNC_POINT_CALLBACK(
  349. "InlineSkipList::Iterator::Next::key",
  350. static_cast<void*>(const_cast<char*>((node_->Key()))));
  351. Node* prev_node = node_;
  352. node_ = node_->Next(0);
  353. // Verify that keys are increasing.
  354. if (prev_node != list_->head_ && node_ != nullptr &&
  355. list_->compare_(prev_node->Key(), node_->Key()) >= 0) {
  356. Node* node = node_;
  357. // invalidates the iterator
  358. node_ = nullptr;
  359. return Corruption(prev_node, node, allow_data_in_errors);
  360. }
  361. return Status::OK();
  362. }
  363. template <class Comparator>
  364. inline void InlineSkipList<Comparator>::Iterator::Prev() {
  365. // Instead of using explicit "prev" links, we just search for the
  366. // last node that falls before key.
  367. assert(Valid());
  368. node_ = list_->FindLessThan(node_->Key(), nullptr);
  369. if (node_ == list_->head_) {
  370. node_ = nullptr;
  371. }
  372. }
  373. template <class Comparator>
  374. inline Status InlineSkipList<Comparator>::Iterator::PrevAndValidate(
  375. const bool allow_data_in_errors) {
  376. assert(Valid());
  377. // Skip list validation is done in FindLessThan().
  378. Node* corrupted_node = nullptr;
  379. node_ = list_->FindLessThan(node_->Key(), &corrupted_node);
  380. if (corrupted_node) {
  381. Node* node = node_;
  382. node_ = nullptr;
  383. return Corruption(node, corrupted_node, allow_data_in_errors);
  384. }
  385. if (node_ == list_->head_) {
  386. node_ = nullptr;
  387. }
  388. return Status::OK();
  389. }
  390. template <class Comparator>
  391. inline void InlineSkipList<Comparator>::Iterator::Seek(const char* target) {
  392. auto status =
  393. list_->FindGreaterOrEqual(target, &node_, false, false, nullptr);
  394. assert(status.ok());
  395. }
  396. template <class Comparator>
  397. inline Status InlineSkipList<Comparator>::Iterator::SeekAndValidate(
  398. const char* target, const bool allow_data_in_errors,
  399. bool check_key_out_of_order,
  400. const std::function<Status(const char*, bool)>& key_validation_callback) {
  401. return list_->FindGreaterOrEqual(target, &node_, allow_data_in_errors,
  402. check_key_out_of_order,
  403. key_validation_callback);
  404. }
  405. template <class Comparator>
  406. inline void InlineSkipList<Comparator>::Iterator::SeekForPrev(
  407. const char* target) {
  408. Seek(target);
  409. if (!Valid()) {
  410. SeekToLast();
  411. }
  412. while (Valid() && list_->LessThan(target, key())) {
  413. Prev();
  414. }
  415. }
  416. template <class Comparator>
  417. inline void InlineSkipList<Comparator>::Iterator::RandomSeek() {
  418. node_ = list_->FindRandomEntry();
  419. }
  420. template <class Comparator>
  421. inline void InlineSkipList<Comparator>::Iterator::SeekToFirst() {
  422. node_ = list_->head_->Next(0);
  423. }
  424. template <class Comparator>
  425. inline void InlineSkipList<Comparator>::Iterator::SeekToLast() {
  426. node_ = list_->FindLast();
  427. if (node_ == list_->head_) {
  428. node_ = nullptr;
  429. }
  430. }
  431. template <class Comparator>
  432. int InlineSkipList<Comparator>::RandomHeight() {
  433. auto rnd = Random::GetTLSInstance();
  434. // Increase height with probability 1 in kBranching
  435. int height = 1;
  436. while (height < kMaxHeight_ && height < kMaxPossibleHeight &&
  437. rnd->Next() < kScaledInverseBranching_) {
  438. height++;
  439. }
  440. TEST_SYNC_POINT_CALLBACK("InlineSkipList::RandomHeight::height", &height);
  441. assert(height > 0);
  442. assert(height <= kMaxHeight_);
  443. assert(height <= kMaxPossibleHeight);
  444. return height;
  445. }
  446. template <class Comparator>
  447. bool InlineSkipList<Comparator>::KeyIsAfterNode(const char* key,
  448. Node* n) const {
  449. // nullptr n is considered infinite
  450. assert(n != head_);
  451. return (n != nullptr) && (compare_(n->Key(), key) < 0);
  452. }
  453. template <class Comparator>
  454. bool InlineSkipList<Comparator>::KeyIsAfterNode(const DecodedKey& key,
  455. Node* n) const {
  456. // nullptr n is considered infinite
  457. assert(n != head_);
  458. return (n != nullptr) && (compare_(n->Key(), key) < 0);
  459. }
  460. template <class Comparator>
  461. Status InlineSkipList<Comparator>::FindGreaterOrEqual(
  462. const char* key, Node** node, bool allow_data_in_errors,
  463. bool detect_key_out_of_order,
  464. const std::function<Status(const char*, bool)>& key_validation_callback)
  465. const {
  466. // Note: It looks like we could reduce duplication by implementing
  467. // this function as FindLessThan(key)->Next(0), but we wouldn't be able
  468. // to exit early on equality and the result wouldn't even be correct.
  469. // A concurrent insert might occur after FindLessThan(key) but before
  470. // we get a chance to call Next(0).
  471. Node* x = head_;
  472. *node = nullptr;
  473. int level = GetMaxHeight() - 1;
  474. Node* last_bigger = nullptr;
  475. const DecodedKey key_decoded = compare_.decode_key(key);
  476. while (true) {
  477. Node* next = x->Next(level);
  478. if (next != nullptr) {
  479. PREFETCH(next->Next(level), 0, 1);
  480. if (detect_key_out_of_order && x != head_ &&
  481. compare_(x->Key(), next->Key()) >= 0) {
  482. return Corruption(x, next, allow_data_in_errors);
  483. }
  484. if (key_validation_callback != nullptr) {
  485. auto status =
  486. key_validation_callback(next->Key(), allow_data_in_errors);
  487. if (!status.ok()) {
  488. return status;
  489. }
  490. }
  491. }
  492. // Make sure the lists are sorted
  493. assert(x == head_ || next == nullptr || KeyIsAfterNode(next->Key(), x));
  494. // Make sure we haven't overshot during our search
  495. assert(x == head_ || KeyIsAfterNode(key_decoded, x));
  496. int cmp = (next == nullptr || next == last_bigger)
  497. ? 1
  498. : compare_(next->Key(), key_decoded);
  499. if (cmp == 0 || (cmp > 0 && level == 0)) {
  500. *node = next;
  501. return Status::OK();
  502. } else if (cmp < 0) {
  503. // Keep searching in this list
  504. x = next;
  505. } else {
  506. // Switch to next list, reuse compare_() result
  507. last_bigger = next;
  508. level--;
  509. }
  510. }
  511. }
  512. template <class Comparator>
  513. typename InlineSkipList<Comparator>::Node*
  514. InlineSkipList<Comparator>::FindLessThan(const char* key,
  515. Node** const out_of_order_node) const {
  516. int level = GetMaxHeight() - 1;
  517. assert(level >= 0);
  518. Node* x = head_;
  519. // KeyIsAfter(key, last_not_after) is definitely false
  520. Node* last_not_after = nullptr;
  521. const DecodedKey key_decoded = compare_.decode_key(key);
  522. while (true) {
  523. assert(x != nullptr);
  524. Node* next = x->Next(level);
  525. if (next != nullptr) {
  526. PREFETCH(next->Next(level), 0, 1);
  527. if (out_of_order_node && x != head_ &&
  528. compare_(x->Key(), next->Key()) >= 0) {
  529. *out_of_order_node = next;
  530. return x;
  531. }
  532. }
  533. assert(x == head_ || next == nullptr || KeyIsAfterNode(next->Key(), x));
  534. assert(x == head_ || KeyIsAfterNode(key_decoded, x));
  535. if (next != last_not_after && KeyIsAfterNode(key_decoded, next)) {
  536. // Keep searching in this list
  537. assert(next != nullptr);
  538. x = next;
  539. } else {
  540. if (level == 0) {
  541. return x;
  542. } else {
  543. // Switch to next list, reuse KeyIsAfterNode() result
  544. last_not_after = next;
  545. level--;
  546. }
  547. }
  548. }
  549. }
  550. template <class Comparator>
  551. typename InlineSkipList<Comparator>::Node*
  552. InlineSkipList<Comparator>::FindLast() const {
  553. Node* x = head_;
  554. int level = GetMaxHeight() - 1;
  555. while (true) {
  556. Node* next = x->Next(level);
  557. if (next == nullptr) {
  558. if (level == 0) {
  559. return x;
  560. } else {
  561. // Switch to next list
  562. level--;
  563. }
  564. } else {
  565. x = next;
  566. }
  567. }
  568. }
  569. template <class Comparator>
  570. typename InlineSkipList<Comparator>::Node*
  571. InlineSkipList<Comparator>::FindRandomEntry() const {
  572. // TODO(bjlemaire): consider adding PREFETCH calls.
  573. Node *x = head_, *scan_node = nullptr, *limit_node = nullptr;
  574. // We start at the max level.
  575. // FOr each level, we look at all the nodes at the level, and
  576. // we randomly pick one of them. Then decrement the level
  577. // and reiterate the process.
  578. // eg: assume GetMaxHeight()=5, and there are #100 elements (nodes).
  579. // level 4 nodes: lvl_nodes={#1, #15, #67, #84}. Randomly pick #15.
  580. // We will consider all the nodes between #15 (inclusive) and #67
  581. // (exclusive). #67 is called 'limit_node' here.
  582. // level 3 nodes: lvl_nodes={#15, #21, #45, #51}. Randomly choose
  583. // #51. #67 remains 'limit_node'.
  584. // [...]
  585. // level 0 nodes: lvl_nodes={#56,#57,#58,#59}. Randomly pick $57.
  586. // Return Node #57.
  587. std::vector<Node*> lvl_nodes;
  588. Random* rnd = Random::GetTLSInstance();
  589. int level = GetMaxHeight() - 1;
  590. while (level >= 0) {
  591. lvl_nodes.clear();
  592. scan_node = x;
  593. while (scan_node != limit_node) {
  594. lvl_nodes.push_back(scan_node);
  595. scan_node = scan_node->Next(level);
  596. }
  597. uint32_t rnd_idx = rnd->Next() % lvl_nodes.size();
  598. x = lvl_nodes[rnd_idx];
  599. if (rnd_idx + 1 < lvl_nodes.size()) {
  600. limit_node = lvl_nodes[rnd_idx + 1];
  601. }
  602. level--;
  603. }
  604. // There is a special case where x could still be the head_
  605. // (note that the head_ contains no key).
  606. return x == head_ && head_ != nullptr ? head_->Next(0) : x;
  607. }
  608. template <class Comparator>
  609. uint64_t InlineSkipList<Comparator>::ApproximateNumEntries(
  610. const Slice& start_ikey, const Slice& end_ikey) const {
  611. // The number of entries at a given level for the given range, in terms of
  612. // the actual number of entries in that range (level 0), follows a binomial
  613. // distribution, which is very well approximated by the Poisson distribution.
  614. // That has stddev sqrt(x) where x is the expected number of entries (mean)
  615. // at this level, and the best predictor of x is the number of observed
  616. // entries (at this level). To predict the number of entries on level 0 we use
  617. // x * kBranchinng ^ level. From the standard deviation, the P99+ relative
  618. // error is roughly 3 * sqrt(x) / x. Thus, a reasonable approach would be to
  619. // find the smallest level with at least some moderate constant number entries
  620. // in range. E.g. with at least ~40 entries, we expect P99+ relative error
  621. // (approximation accuracy) of ~ 50% = 3 * sqrt(40) / 40; P95 error of
  622. // ~30%; P75 error of < 20%.
  623. //
  624. // However, there are two issues with this approach, and an observation:
  625. // * Pointer chasing on the larger (bottom) levels is much slower because of
  626. // cache hierarchy effects, so when the result is smaller, getting the result
  627. // will be substantially slower, despite traversing a similar number of
  628. // entries. (We could be clever about pipelining our pointer chasing but
  629. // that's complicated.)
  630. // * The larger (bottom) levels also have lower variance because there's a
  631. // chance (or certainty) that we reach level 0 and return the exact answer.
  632. // * For applications in query planning, we can also tolerate more variance on
  633. // small results because the impact of misestimating is likely smaller.
  634. //
  635. // These factors point us to an approach in which we have a higher minimum
  636. // threshold number of samples for higher levels and lower for lower levels
  637. // (see sufficient_samples below). This seems to yield roughly consistent
  638. // relative error (stddev around 20%, less for large results) and roughly
  639. // consistent query time around the time of two memtable point queries.
  640. //
  641. // Engineering observation: it is tempting to think that taking into account
  642. // what we already found in how many entries occur on higher levels, not just
  643. // the first iterated level with a sufficient number of samples, would yield
  644. // a more accurate estimate. But that doesn't work because of the particular
  645. // correlations and independences of the data: each level higher is just an
  646. // independently probabilistic filtering of the level below it. That
  647. // filtering from level l to l+1 has no more information about levels
  648. // 0 .. l-1 than we can get from level l. The structure of RandomHeight() is
  649. // a clue to these correlations and independences.
  650. Node* lb = head_;
  651. Node* ub = nullptr;
  652. uint64_t count = 0;
  653. for (int level = GetMaxHeight() - 1; level >= 0; level--) {
  654. auto sufficient_samples = static_cast<uint64_t>(level) * kBranching_ + 10U;
  655. if (count >= sufficient_samples) {
  656. // No more counting; apply powers of kBranching and avoid floating point
  657. count *= kBranching_;
  658. continue;
  659. }
  660. count = 0;
  661. Node* next;
  662. // Get a more precise lower bound (for start key)
  663. for (;;) {
  664. next = lb->Next(level);
  665. if (next == ub) {
  666. break;
  667. }
  668. assert(next != nullptr);
  669. if (compare_(next->Key(), start_ikey) >= 0) {
  670. break;
  671. }
  672. lb = next;
  673. }
  674. // Count entries on this level until upper bound (for end key)
  675. for (;;) {
  676. if (next == ub) {
  677. break;
  678. }
  679. assert(next != nullptr);
  680. if (compare_(next->Key(), end_ikey) >= 0) {
  681. // Save refined upper bound to potentially save key comparison
  682. ub = next;
  683. break;
  684. }
  685. count++;
  686. next = next->Next(level);
  687. }
  688. }
  689. return count;
  690. }
  691. template <class Comparator>
  692. InlineSkipList<Comparator>::InlineSkipList(const Comparator cmp,
  693. Allocator* allocator,
  694. int32_t max_height,
  695. int32_t branching_factor)
  696. : kMaxHeight_(static_cast<uint16_t>(max_height)),
  697. kBranching_(static_cast<uint16_t>(branching_factor)),
  698. kScaledInverseBranching_((Random::kMaxNext + 1) / kBranching_),
  699. allocator_(allocator),
  700. compare_(cmp),
  701. head_(AllocateNode(0, max_height)),
  702. max_height_(1),
  703. seq_splice_(AllocateSplice()) {
  704. assert(max_height > 0 && kMaxHeight_ == static_cast<uint32_t>(max_height));
  705. assert(branching_factor > 1 &&
  706. kBranching_ == static_cast<uint32_t>(branching_factor));
  707. assert(kScaledInverseBranching_ > 0);
  708. for (int i = 0; i < kMaxHeight_; ++i) {
  709. head_->SetNext(i, nullptr);
  710. }
  711. }
  712. template <class Comparator>
  713. char* InlineSkipList<Comparator>::AllocateKey(size_t key_size) {
  714. return const_cast<char*>(AllocateNode(key_size, RandomHeight())->Key());
  715. }
  716. template <class Comparator>
  717. typename InlineSkipList<Comparator>::Node*
  718. InlineSkipList<Comparator>::AllocateNode(size_t key_size, int height) {
  719. auto prefix = sizeof(AcqRelAtomic<Node*>) * (height - 1);
  720. // prefix is space for the height - 1 pointers that we store before
  721. // the Node instance (next_[-(height - 1) .. -1]). Node starts at
  722. // raw + prefix, and holds the bottom-mode (level 0) skip list pointer
  723. // next_[0]. key_size is the bytes for the key, which comes just after
  724. // the Node.
  725. char* raw = allocator_->AllocateAligned(prefix + sizeof(Node) + key_size);
  726. Node* x = reinterpret_cast<Node*>(raw + prefix);
  727. // Once we've linked the node into the skip list we don't actually need
  728. // to know its height, because we can implicitly use the fact that we
  729. // traversed into a node at level h to known that h is a valid level
  730. // for that node. We need to convey the height to the Insert step,
  731. // however, so that it can perform the proper links. Since we're not
  732. // using the pointers at the moment, StashHeight temporarily borrow
  733. // storage from next_[0] for that purpose.
  734. x->StashHeight(height);
  735. return x;
  736. }
  737. template <class Comparator>
  738. typename InlineSkipList<Comparator>::Splice*
  739. InlineSkipList<Comparator>::AllocateSplice() {
  740. // size of prev_ and next_
  741. size_t array_size = sizeof(Node*) * (kMaxHeight_ + 1);
  742. char* raw = allocator_->AllocateAligned(sizeof(Splice) + array_size * 2);
  743. Splice* splice = reinterpret_cast<Splice*>(raw);
  744. splice->height_ = 0;
  745. splice->prev_ = reinterpret_cast<Node**>(raw + sizeof(Splice));
  746. splice->next_ = reinterpret_cast<Node**>(raw + sizeof(Splice) + array_size);
  747. return splice;
  748. }
  749. template <class Comparator>
  750. typename InlineSkipList<Comparator>::Splice*
  751. InlineSkipList<Comparator>::AllocateSpliceOnHeap() {
  752. size_t array_size = sizeof(Node*) * (kMaxHeight_ + 1);
  753. char* raw = new char[sizeof(Splice) + array_size * 2];
  754. Splice* splice = reinterpret_cast<Splice*>(raw);
  755. splice->height_ = 0;
  756. splice->prev_ = reinterpret_cast<Node**>(raw + sizeof(Splice));
  757. splice->next_ = reinterpret_cast<Node**>(raw + sizeof(Splice) + array_size);
  758. return splice;
  759. }
  760. template <class Comparator>
  761. bool InlineSkipList<Comparator>::Insert(const char* key) {
  762. return Insert<false>(key, seq_splice_, false);
  763. }
  764. template <class Comparator>
  765. bool InlineSkipList<Comparator>::InsertConcurrently(const char* key) {
  766. Node* prev[kMaxPossibleHeight];
  767. Node* next[kMaxPossibleHeight];
  768. Splice splice;
  769. splice.prev_ = prev;
  770. splice.next_ = next;
  771. return Insert<true>(key, &splice, false);
  772. }
  773. template <class Comparator>
  774. bool InlineSkipList<Comparator>::InsertWithHint(const char* key, void** hint) {
  775. assert(hint != nullptr);
  776. Splice* splice = reinterpret_cast<Splice*>(*hint);
  777. if (splice == nullptr) {
  778. splice = AllocateSplice();
  779. *hint = splice;
  780. }
  781. return Insert<false>(key, splice, true);
  782. }
  783. template <class Comparator>
  784. bool InlineSkipList<Comparator>::InsertWithHintConcurrently(const char* key,
  785. void** hint) {
  786. assert(hint != nullptr);
  787. Splice* splice = reinterpret_cast<Splice*>(*hint);
  788. if (splice == nullptr) {
  789. splice = AllocateSpliceOnHeap();
  790. *hint = splice;
  791. }
  792. return Insert<true>(key, splice, true);
  793. }
  794. template <class Comparator>
  795. template <bool prefetch_before>
  796. void InlineSkipList<Comparator>::FindSpliceForLevel(const DecodedKey& key,
  797. Node* before, Node* after,
  798. int level, Node** out_prev,
  799. Node** out_next) {
  800. while (true) {
  801. Node* next = before->Next(level);
  802. if (next != nullptr) {
  803. PREFETCH(next->Next(level), 0, 1);
  804. }
  805. if (prefetch_before == true) {
  806. if (next != nullptr && level > 0) {
  807. PREFETCH(next->Next(level - 1), 0, 1);
  808. }
  809. }
  810. assert(before == head_ || next == nullptr ||
  811. KeyIsAfterNode(next->Key(), before));
  812. assert(before == head_ || KeyIsAfterNode(key, before));
  813. if (next == after || !KeyIsAfterNode(key, next)) {
  814. // found it
  815. *out_prev = before;
  816. *out_next = next;
  817. return;
  818. }
  819. before = next;
  820. }
  821. }
  822. template <class Comparator>
  823. void InlineSkipList<Comparator>::RecomputeSpliceLevels(const DecodedKey& key,
  824. Splice* splice,
  825. int recompute_level) {
  826. assert(recompute_level > 0);
  827. assert(recompute_level <= splice->height_);
  828. for (int i = recompute_level - 1; i >= 0; --i) {
  829. FindSpliceForLevel<true>(key, splice->prev_[i + 1], splice->next_[i + 1], i,
  830. &splice->prev_[i], &splice->next_[i]);
  831. }
  832. }
  833. template <class Comparator>
  834. template <bool UseCAS>
  835. bool InlineSkipList<Comparator>::Insert(const char* key, Splice* splice,
  836. bool allow_partial_splice_fix) {
  837. Node* x = reinterpret_cast<Node*>(const_cast<char*>(key)) - 1;
  838. const DecodedKey key_decoded = compare_.decode_key(key);
  839. int height = x->UnstashHeight();
  840. assert(height >= 1 && height <= kMaxHeight_);
  841. int max_height = max_height_.LoadRelaxed();
  842. while (height > max_height) {
  843. if (max_height_.CasWeakRelaxed(max_height, height)) {
  844. // successfully updated it
  845. max_height = height;
  846. break;
  847. }
  848. // else retry, possibly exiting the loop because somebody else
  849. // increased it
  850. }
  851. assert(max_height <= kMaxPossibleHeight);
  852. int recompute_height = 0;
  853. if (splice->height_ < max_height) {
  854. // Either splice has never been used or max_height has grown since
  855. // last use. We could potentially fix it in the latter case, but
  856. // that is tricky.
  857. splice->prev_[max_height] = head_;
  858. splice->next_[max_height] = nullptr;
  859. splice->height_ = max_height;
  860. recompute_height = max_height;
  861. } else {
  862. // Splice is a valid proper-height splice that brackets some
  863. // key, but does it bracket this one? We need to validate it and
  864. // recompute a portion of the splice (levels 0..recompute_height-1)
  865. // that is a superset of all levels that don't bracket the new key.
  866. // Several choices are reasonable, because we have to balance the work
  867. // saved against the extra comparisons required to validate the Splice.
  868. //
  869. // One strategy is just to recompute all of orig_splice_height if the
  870. // bottom level isn't bracketing. This pessimistically assumes that
  871. // we will either get a perfect Splice hit (increasing sequential
  872. // inserts) or have no locality.
  873. //
  874. // Another strategy is to walk up the Splice's levels until we find
  875. // a level that brackets the key. This strategy lets the Splice
  876. // hint help for other cases: it turns insertion from O(log N) into
  877. // O(log D), where D is the number of nodes in between the key that
  878. // produced the Splice and the current insert (insertion is aided
  879. // whether the new key is before or after the splice). If you have
  880. // a way of using a prefix of the key to map directly to the closest
  881. // Splice out of O(sqrt(N)) Splices and we make it so that splices
  882. // can also be used as hints during read, then we end up with Oshman's
  883. // and Shavit's SkipTrie, which has O(log log N) lookup and insertion
  884. // (compare to O(log N) for skip list).
  885. //
  886. // We control the pessimistic strategy with allow_partial_splice_fix.
  887. // A good strategy is probably to be pessimistic for seq_splice_,
  888. // optimistic if the caller actually went to the work of providing
  889. // a Splice.
  890. while (recompute_height < max_height) {
  891. if (splice->prev_[recompute_height]->Next(recompute_height) !=
  892. splice->next_[recompute_height]) {
  893. // splice isn't tight at this level, there must have been some inserts
  894. // to this
  895. // location that didn't update the splice. We might only be a little
  896. // stale, but if
  897. // the splice is very stale it would be O(N) to fix it. We haven't used
  898. // up any of
  899. // our budget of comparisons, so always move up even if we are
  900. // pessimistic about
  901. // our chances of success.
  902. ++recompute_height;
  903. } else if (splice->prev_[recompute_height] != head_ &&
  904. !KeyIsAfterNode(key_decoded,
  905. splice->prev_[recompute_height])) {
  906. // key is from before splice
  907. if (allow_partial_splice_fix) {
  908. // skip all levels with the same node without more comparisons
  909. Node* bad = splice->prev_[recompute_height];
  910. while (splice->prev_[recompute_height] == bad) {
  911. ++recompute_height;
  912. }
  913. } else {
  914. // we're pessimistic, recompute everything
  915. recompute_height = max_height;
  916. }
  917. } else if (KeyIsAfterNode(key_decoded, splice->next_[recompute_height])) {
  918. // key is from after splice
  919. if (allow_partial_splice_fix) {
  920. Node* bad = splice->next_[recompute_height];
  921. while (splice->next_[recompute_height] == bad) {
  922. ++recompute_height;
  923. }
  924. } else {
  925. recompute_height = max_height;
  926. }
  927. } else {
  928. // this level brackets the key, we won!
  929. break;
  930. }
  931. }
  932. }
  933. assert(recompute_height <= max_height);
  934. if (recompute_height > 0) {
  935. RecomputeSpliceLevels(key_decoded, splice, recompute_height);
  936. }
  937. bool splice_is_valid = true;
  938. if (UseCAS) {
  939. for (int i = 0; i < height; ++i) {
  940. while (true) {
  941. // Checking for duplicate keys on the level 0 is sufficient
  942. if (UNLIKELY(i == 0 && splice->next_[i] != nullptr &&
  943. compare_(splice->next_[i]->Key(), key_decoded) <= 0)) {
  944. // duplicate key
  945. return false;
  946. }
  947. if (UNLIKELY(i == 0 && splice->prev_[i] != head_ &&
  948. compare_(splice->prev_[i]->Key(), key_decoded) >= 0)) {
  949. // duplicate key
  950. return false;
  951. }
  952. assert(splice->next_[i] == nullptr ||
  953. compare_(x->Key(), splice->next_[i]->Key()) < 0);
  954. assert(splice->prev_[i] == head_ ||
  955. compare_(splice->prev_[i]->Key(), x->Key()) < 0);
  956. x->NoBarrier_SetNext(i, splice->next_[i]);
  957. if (splice->prev_[i]->CASNext(i, splice->next_[i], x)) {
  958. // success
  959. break;
  960. }
  961. // CAS failed, we need to recompute prev and next. It is unlikely
  962. // to be helpful to try to use a different level as we redo the
  963. // search, because it should be unlikely that lots of nodes have
  964. // been inserted between prev[i] and next[i]. No point in using
  965. // next[i] as the after hint, because we know it is stale.
  966. FindSpliceForLevel<false>(key_decoded, splice->prev_[i], nullptr, i,
  967. &splice->prev_[i], &splice->next_[i]);
  968. // Since we've narrowed the bracket for level i, we might have
  969. // violated the Splice constraint between i and i-1. Make sure
  970. // we recompute the whole thing next time.
  971. if (i > 0) {
  972. splice_is_valid = false;
  973. }
  974. }
  975. }
  976. } else {
  977. for (int i = 0; i < height; ++i) {
  978. if (i >= recompute_height &&
  979. splice->prev_[i]->Next(i) != splice->next_[i]) {
  980. FindSpliceForLevel<false>(key_decoded, splice->prev_[i], nullptr, i,
  981. &splice->prev_[i], &splice->next_[i]);
  982. }
  983. // Checking for duplicate keys on the level 0 is sufficient
  984. if (UNLIKELY(i == 0 && splice->next_[i] != nullptr &&
  985. compare_(splice->next_[i]->Key(), key_decoded) <= 0)) {
  986. // duplicate key
  987. return false;
  988. }
  989. if (UNLIKELY(i == 0 && splice->prev_[i] != head_ &&
  990. compare_(splice->prev_[i]->Key(), key_decoded) >= 0)) {
  991. // duplicate key
  992. return false;
  993. }
  994. assert(splice->next_[i] == nullptr ||
  995. compare_(x->Key(), splice->next_[i]->Key()) < 0);
  996. assert(splice->prev_[i] == head_ ||
  997. compare_(splice->prev_[i]->Key(), x->Key()) < 0);
  998. assert(splice->prev_[i]->Next(i) == splice->next_[i]);
  999. x->NoBarrier_SetNext(i, splice->next_[i]);
  1000. splice->prev_[i]->SetNext(i, x);
  1001. }
  1002. }
  1003. if (splice_is_valid) {
  1004. for (int i = 0; i < height; ++i) {
  1005. splice->prev_[i] = x;
  1006. }
  1007. assert(splice->prev_[splice->height_] == head_);
  1008. assert(splice->next_[splice->height_] == nullptr);
  1009. for (int i = 0; i < splice->height_; ++i) {
  1010. assert(splice->next_[i] == nullptr ||
  1011. compare_(key, splice->next_[i]->Key()) < 0);
  1012. assert(splice->prev_[i] == head_ ||
  1013. compare_(splice->prev_[i]->Key(), key) <= 0);
  1014. assert(splice->prev_[i + 1] == splice->prev_[i] ||
  1015. splice->prev_[i + 1] == head_ ||
  1016. compare_(splice->prev_[i + 1]->Key(), splice->prev_[i]->Key()) <
  1017. 0);
  1018. assert(splice->next_[i + 1] == splice->next_[i] ||
  1019. splice->next_[i + 1] == nullptr ||
  1020. compare_(splice->next_[i]->Key(), splice->next_[i + 1]->Key()) <
  1021. 0);
  1022. }
  1023. } else {
  1024. splice->height_ = 0;
  1025. }
  1026. return true;
  1027. }
  1028. template <class Comparator>
  1029. bool InlineSkipList<Comparator>::Contains(const char* key) const {
  1030. Node* x = nullptr;
  1031. auto status = FindGreaterOrEqual(key, &x, false, false, nullptr);
  1032. assert(status.ok());
  1033. if (x != nullptr && Equal(key, x->Key())) {
  1034. return true;
  1035. } else {
  1036. return false;
  1037. }
  1038. }
  1039. template <class Comparator>
  1040. void InlineSkipList<Comparator>::TEST_Validate() const {
  1041. // Interate over all levels at the same time, and verify nodes appear in
  1042. // the right order, and nodes appear in upper level also appear in lower
  1043. // levels.
  1044. Node* nodes[kMaxPossibleHeight];
  1045. int max_height = GetMaxHeight();
  1046. assert(max_height > 0);
  1047. for (int i = 0; i < max_height; i++) {
  1048. nodes[i] = head_;
  1049. }
  1050. while (nodes[0] != nullptr) {
  1051. Node* l0_next = nodes[0]->Next(0);
  1052. if (l0_next == nullptr) {
  1053. break;
  1054. }
  1055. assert(nodes[0] == head_ || compare_(nodes[0]->Key(), l0_next->Key()) < 0);
  1056. nodes[0] = l0_next;
  1057. int i = 1;
  1058. while (i < max_height) {
  1059. Node* next = nodes[i]->Next(i);
  1060. if (next == nullptr) {
  1061. break;
  1062. }
  1063. auto cmp = compare_(nodes[0]->Key(), next->Key());
  1064. assert(cmp <= 0);
  1065. if (cmp == 0) {
  1066. assert(next == nodes[0]);
  1067. nodes[i] = next;
  1068. } else {
  1069. break;
  1070. }
  1071. i++;
  1072. }
  1073. }
  1074. for (int i = 1; i < max_height; i++) {
  1075. assert(nodes[i] != nullptr && nodes[i]->Next(i) == nullptr);
  1076. }
  1077. }
  1078. template <class Comparator>
  1079. Status InlineSkipList<Comparator>::Corruption(Node* prev, Node* next,
  1080. bool allow_data_in_errors) {
  1081. std::string msg = "Out-of-order keys found in skiplist.";
  1082. if (allow_data_in_errors) {
  1083. msg.append(" prev key: " + Slice(prev->Key()).ToString(true));
  1084. msg.append(" next key: " + Slice(next->Key()).ToString(true));
  1085. }
  1086. return Status::Corruption(msg);
  1087. }
  1088. } // namespace ROCKSDB_NAMESPACE