sparsetable.h 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825
  1. // Copyright (c) 2005, Google Inc.
  2. // All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. // * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. // * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. // ---
  30. //
  31. //
  32. // A sparsetable is a random container that implements a sparse array,
  33. // that is, an array that uses very little memory to store unassigned
  34. // indices (in this case, between 1-2 bits per unassigned index). For
  35. // instance, if you allocate an array of size 5 and assign a[2] = <big
  36. // struct>, then a[2] will take up a lot of memory but a[0], a[1],
  37. // a[3], and a[4] will not. Array elements that have a value are
  38. // called "assigned". Array elements that have no value yet, or have
  39. // had their value cleared using erase() or clear(), are called
  40. // "unassigned".
  41. //
  42. // Unassigned values seem to have the default value of T (see below).
  43. // Nevertheless, there is a difference between an unassigned index and
  44. // one explicitly assigned the value of T(). The latter is considered
  45. // assigned.
  46. //
  47. // Access to an array element is constant time, as is insertion and
  48. // deletion. Insertion and deletion may be fairly slow, however:
  49. // because of this container's memory economy, each insert and delete
  50. // causes a memory reallocation.
  51. //
  52. // NOTE: You should not test(), get(), or set() any index that is
  53. // greater than sparsetable.size(). If you need to do that, call
  54. // resize() first.
  55. //
  56. // --- Template parameters
  57. // PARAMETER DESCRIPTION DEFAULT
  58. // T The value of the array: the type of --
  59. // object that is stored in the array.
  60. //
  61. // GROUP_SIZE How large each "group" in the table 48
  62. // is (see below). Larger values use
  63. // a little less memory but cause most
  64. // operations to be a little slower
  65. //
  66. // Alloc: Allocator to use to allocate memory. libc_allocator_with_realloc
  67. //
  68. // --- Model of
  69. // Random Access Container
  70. //
  71. // --- Type requirements
  72. // T must be Copy Constructible. It need not be Assignable.
  73. //
  74. // --- Public base classes
  75. // None.
  76. //
  77. // --- Members
  78. // Type members
  79. //
  80. // MEMBER WHERE DEFINED DESCRIPTION
  81. // value_type container The type of object, T, stored in the array
  82. // allocator_type container Allocator to use
  83. // pointer container Pointer to p
  84. // const_pointer container Const pointer to p
  85. // reference container Reference to t
  86. // const_reference container Const reference to t
  87. // size_type container An unsigned integral type
  88. // difference_type container A signed integral type
  89. // iterator [*] container Iterator used to iterate over a sparsetable
  90. // const_iterator container Const iterator used to iterate over a table
  91. // reverse_iterator reversible Iterator used to iterate backwards over
  92. // container a sparsetable
  93. // const_reverse_iterator reversible container Guess
  94. // nonempty_iterator [+] sparsetable Iterates over assigned
  95. // array elements only
  96. // const_nonempty_iterator sparsetable Iterates over assigned
  97. // array elements only
  98. // reverse_nonempty_iterator sparsetable Iterates backwards over
  99. // assigned array elements only
  100. // const_reverse_nonempty_iterator sparsetable Iterates backwards over
  101. // assigned array elements only
  102. //
  103. // [*] All iterators are const in a sparsetable (though nonempty_iterators
  104. // may not be). Use get() and set() to assign values, not iterators.
  105. //
  106. // [+] iterators are random-access iterators. nonempty_iterators are
  107. // bidirectional iterators.
  108. // Iterator members
  109. // MEMBER WHERE DEFINED DESCRIPTION
  110. //
  111. // iterator begin() container An iterator to the beginning of the table
  112. // iterator end() container An iterator to the end of the table
  113. // const_iterator container A const_iterator pointing to the
  114. // begin() const beginning of a sparsetable
  115. // const_iterator container A const_iterator pointing to the
  116. // end() const end of a sparsetable
  117. //
  118. // reverse_iterator reversable Points to beginning of a reversed
  119. // rbegin() container sparsetable
  120. // reverse_iterator reversable Points to end of a reversed table
  121. // rend() container
  122. // const_reverse_iterator reversable Points to beginning of a
  123. // rbegin() const container reversed sparsetable
  124. // const_reverse_iterator reversable Points to end of a reversed table
  125. // rend() const container
  126. //
  127. // nonempty_iterator sparsetable Points to first assigned element
  128. // begin() of a sparsetable
  129. // nonempty_iterator sparsetable Points past last assigned element
  130. // end() of a sparsetable
  131. // const_nonempty_iterator sparsetable Points to first assigned element
  132. // begin() const of a sparsetable
  133. // const_nonempty_iterator sparsetable Points past last assigned element
  134. // end() const of a sparsetable
  135. //
  136. // reverse_nonempty_iterator sparsetable Points to first assigned element
  137. // begin() of a reversed sparsetable
  138. // reverse_nonempty_iterator sparsetable Points past last assigned element
  139. // end() of a reversed sparsetable
  140. // const_reverse_nonempty_iterator sparsetable Points to first assigned
  141. // begin() const elt of a reversed sparsetable
  142. // const_reverse_nonempty_iterator sparsetable Points past last assigned
  143. // end() const elt of a reversed sparsetable
  144. //
  145. //
  146. // Other members
  147. // MEMBER WHERE DEFINED DESCRIPTION
  148. // sparsetable() sparsetable A table of size 0; must resize()
  149. // before using.
  150. // sparsetable(size_type size) sparsetable A table of size size. All
  151. // indices are unassigned.
  152. // sparsetable(
  153. // const sparsetable &tbl) sparsetable Copy constructor
  154. // ~sparsetable() sparsetable The destructor
  155. // sparsetable &operator=( sparsetable The assignment operator
  156. // const sparsetable &tbl)
  157. //
  158. // void resize(size_type size) sparsetable Grow or shrink a table to
  159. // have size indices [*]
  160. //
  161. // void swap(sparsetable &x) sparsetable Swap two sparsetables
  162. // void swap(sparsetable &x, sparsetable Swap two sparsetables
  163. // sparsetable &y) (global, not member, function)
  164. //
  165. // size_type size() const sparsetable Number of "buckets" in the table
  166. // size_type max_size() const sparsetable Max allowed size of a sparsetable
  167. // bool empty() const sparsetable true if size() == 0
  168. // size_type num_nonempty() const sparsetable Number of assigned "buckets"
  169. //
  170. // const_reference get( sparsetable Value at index i, or default
  171. // size_type i) const value if i is unassigned
  172. // const_reference operator[]( sparsetable Identical to get(i) [+]
  173. // difference_type i) const
  174. // reference set(size_type i, sparsetable Set element at index i to
  175. // const_reference val) be a copy of val
  176. // bool test(size_type i) sparsetable True if element at index i
  177. // const has been assigned to
  178. // bool test(iterator pos) sparsetable True if element pointed to
  179. // const by pos has been assigned to
  180. // void erase(iterator pos) sparsetable Set element pointed to by
  181. // pos to be unassigned [!]
  182. // void erase(size_type i) sparsetable Set element i to be unassigned
  183. // void erase(iterator start, sparsetable Erases all elements between
  184. // iterator end) start and end
  185. // void clear() sparsetable Erases all elements in the table
  186. //
  187. // I/O versions exist for both FILE* and for File* (Google2-style files):
  188. // bool write_metadata(FILE *fp) sparsetable Writes a sparsetable to the
  189. // bool write_metadata(File *fp) given file. true if write
  190. // completes successfully
  191. // bool read_metadata(FILE *fp) sparsetable Replaces sparsetable with
  192. // bool read_metadata(File *fp) version read from fp. true
  193. // if read completes sucessfully
  194. // bool write_nopointer_data(FILE *fp) Read/write the data stored in
  195. // bool read_nopointer_data(FILE*fp) the table, if it's simple
  196. //
  197. // bool operator==( forward Tests two tables for equality.
  198. // const sparsetable &t1, container This is a global function,
  199. // const sparsetable &t2) not a member function.
  200. // bool operator<( forward Lexicographical comparison.
  201. // const sparsetable &t1, container This is a global function,
  202. // const sparsetable &t2) not a member function.
  203. //
  204. // [*] If you shrink a sparsetable using resize(), assigned elements
  205. // past the end of the table are removed using erase(). If you grow
  206. // a sparsetable, new unassigned indices are created.
  207. //
  208. // [+] Note that operator[] returns a const reference. You must use
  209. // set() to change the value of a table element.
  210. //
  211. // [!] Unassignment also calls the destructor.
  212. //
  213. // Iterators are invalidated whenever an item is inserted or
  214. // deleted (ie set() or erase() is used) or when the size of
  215. // the table changes (ie resize() or clear() is used).
  216. //
  217. // See doc/sparsetable.html for more information about how to use this class.
  218. // Note: this uses STL style for naming, rather than Google naming.
  219. // That's because this is an STL-y container
  220. #ifndef UTIL_GTL_SPARSETABLE_H_
  221. #define UTIL_GTL_SPARSETABLE_H_
  222. #include "internal/sparseconfig.h"
  223. #include <stdlib.h> // for malloc/free
  224. #include <stdio.h> // to read/write tables
  225. #include <string.h> // for memcpy
  226. #ifdef HAVE_STDINT_H
  227. #include <stdint.h> // the normal place uint16_t is defined
  228. #endif
  229. #ifdef HAVE_SYS_TYPES_H
  230. #include <sys/types.h> // the normal place u_int16_t is defined
  231. #endif
  232. #ifdef HAVE_INTTYPES_H
  233. #include <inttypes.h> // a third place for uint16_t or u_int16_t
  234. #endif
  235. #include <assert.h> // for bounds checking
  236. #include <iterator> // to define reverse_iterator for me
  237. #include <algorithm> // equal, lexicographical_compare, swap,...
  238. #include <memory> // uninitialized_copy, uninitialized_fill
  239. #include <vector> // a sparsetable is a vector of groups
  240. #include "type_traits.h"
  241. #include "internal/hashtable-common.h"
  242. #include "internal/libc_allocator_with_realloc.h"
  243. // A lot of work to get a type that's guaranteed to be 16 bits...
  244. #ifndef HAVE_U_INT16_T
  245. # if defined HAVE_UINT16_T
  246. typedef uint16_t u_int16_t; // true on solaris, possibly other C99 libc's
  247. # elif defined HAVE___UINT16
  248. typedef __int16 int16_t; // true on vc++7
  249. typedef unsigned __int16 u_int16_t;
  250. # else
  251. // Cannot find a 16-bit integer type. Hoping for the best with "short"...
  252. typedef short int int16_t;
  253. typedef unsigned short int u_int16_t;
  254. # endif
  255. #endif
  256. _START_GOOGLE_NAMESPACE_
  257. namespace base { // just to make google->opensource transition easier
  258. using GOOGLE_NAMESPACE::true_type;
  259. using GOOGLE_NAMESPACE::false_type;
  260. using GOOGLE_NAMESPACE::integral_constant;
  261. using GOOGLE_NAMESPACE::has_trivial_copy;
  262. using GOOGLE_NAMESPACE::has_trivial_destructor;
  263. using GOOGLE_NAMESPACE::is_same;
  264. }
  265. // The smaller this is, the faster lookup is (because the group bitmap is
  266. // smaller) and the faster insert is, because there's less to move.
  267. // On the other hand, there are more groups. Since group::size_type is
  268. // a short, this number should be of the form 32*x + 16 to avoid waste.
  269. static const u_int16_t DEFAULT_SPARSEGROUP_SIZE = 48; // fits in 1.5 words
  270. // Our iterator as simple as iterators can be: basically it's just
  271. // the index into our table. Dereference, the only complicated
  272. // thing, we punt to the table class. This just goes to show how
  273. // much machinery STL requires to do even the most trivial tasks.
  274. //
  275. // A NOTE ON ASSIGNING:
  276. // A sparse table does not actually allocate memory for entries
  277. // that are not filled. Because of this, it becomes complicated
  278. // to have a non-const iterator: we don't know, if the iterator points
  279. // to a not-filled bucket, whether you plan to fill it with something
  280. // or whether you plan to read its value (in which case you'll get
  281. // the default bucket value). Therefore, while we can define const
  282. // operations in a pretty 'normal' way, for non-const operations, we
  283. // define something that returns a helper object with operator= and
  284. // operator& that allocate a bucket lazily. We use this for table[]
  285. // and also for regular table iterators.
  286. template <class tabletype>
  287. class table_element_adaptor {
  288. public:
  289. typedef typename tabletype::value_type value_type;
  290. typedef typename tabletype::size_type size_type;
  291. typedef typename tabletype::reference reference;
  292. typedef typename tabletype::pointer pointer;
  293. table_element_adaptor(tabletype *tbl, size_type p)
  294. : table(tbl), pos(p) { }
  295. table_element_adaptor& operator= (const value_type &val) {
  296. table->set(pos, val);
  297. return *this;
  298. }
  299. operator value_type() { return table->get(pos); } // we look like a value
  300. pointer operator& () { return &table->mutating_get(pos); }
  301. private:
  302. tabletype* table;
  303. size_type pos;
  304. };
  305. // Our iterator as simple as iterators can be: basically it's just
  306. // the index into our table. Dereference, the only complicated
  307. // thing, we punt to the table class. This just goes to show how
  308. // much machinery STL requires to do even the most trivial tasks.
  309. //
  310. // By templatizing over tabletype, we have one iterator type which
  311. // we can use for both sparsetables and sparsebins. In fact it
  312. // works on any class that allows size() and operator[] (eg vector),
  313. // as long as it does the standard STL typedefs too (eg value_type).
  314. template <class tabletype>
  315. class table_iterator {
  316. public:
  317. typedef table_iterator iterator;
  318. typedef std::random_access_iterator_tag iterator_category;
  319. typedef typename tabletype::value_type value_type;
  320. typedef typename tabletype::difference_type difference_type;
  321. typedef typename tabletype::size_type size_type;
  322. typedef table_element_adaptor<tabletype> reference;
  323. typedef table_element_adaptor<tabletype>* pointer;
  324. // The "real" constructor
  325. table_iterator(tabletype *tbl, size_type p)
  326. : table(tbl), pos(p) { }
  327. // The default constructor, used when I define vars of type table::iterator
  328. table_iterator() : table(NULL), pos(0) { }
  329. // The copy constructor, for when I say table::iterator foo = tbl.begin()
  330. // The default destructor is fine; we don't define one
  331. // The default operator= is fine; we don't define one
  332. // The main thing our iterator does is dereference. If the table entry
  333. // we point to is empty, we return the default value type.
  334. // This is the big different function from the const iterator.
  335. reference operator*() {
  336. return table_element_adaptor<tabletype>(table, pos);
  337. }
  338. pointer operator->() { return &(operator*()); }
  339. // Helper function to assert things are ok; eg pos is still in range
  340. void check() const {
  341. assert(table);
  342. assert(pos <= table->size());
  343. }
  344. // Arithmetic: we just do arithmetic on pos. We don't even need to
  345. // do bounds checking, since STL doesn't consider that its job. :-)
  346. iterator& operator+=(size_type t) { pos += t; check(); return *this; }
  347. iterator& operator-=(size_type t) { pos -= t; check(); return *this; }
  348. iterator& operator++() { ++pos; check(); return *this; }
  349. iterator& operator--() { --pos; check(); return *this; }
  350. iterator operator++(int) { iterator tmp(*this); // for x++
  351. ++pos; check(); return tmp; }
  352. iterator operator--(int) { iterator tmp(*this); // for x--
  353. --pos; check(); return tmp; }
  354. iterator operator+(difference_type i) const { iterator tmp(*this);
  355. tmp += i; return tmp; }
  356. iterator operator-(difference_type i) const { iterator tmp(*this);
  357. tmp -= i; return tmp; }
  358. difference_type operator-(iterator it) const { // for "x = it2 - it"
  359. assert(table == it.table);
  360. return pos - it.pos;
  361. }
  362. reference operator[](difference_type n) const {
  363. return *(*this + n); // simple though not totally efficient
  364. }
  365. // Comparisons.
  366. bool operator==(const iterator& it) const {
  367. return table == it.table && pos == it.pos;
  368. }
  369. bool operator<(const iterator& it) const {
  370. assert(table == it.table); // life is bad bad bad otherwise
  371. return pos < it.pos;
  372. }
  373. bool operator!=(const iterator& it) const { return !(*this == it); }
  374. bool operator<=(const iterator& it) const { return !(it < *this); }
  375. bool operator>(const iterator& it) const { return it < *this; }
  376. bool operator>=(const iterator& it) const { return !(*this < it); }
  377. // Here's the info we actually need to be an iterator
  378. tabletype *table; // so we can dereference and bounds-check
  379. size_type pos; // index into the table
  380. };
  381. // support for "3 + iterator" has to be defined outside the class, alas
  382. template<class T>
  383. table_iterator<T> operator+(typename table_iterator<T>::difference_type i,
  384. table_iterator<T> it) {
  385. return it + i; // so people can say it2 = 3 + it
  386. }
  387. template <class tabletype>
  388. class const_table_iterator {
  389. public:
  390. typedef table_iterator<tabletype> iterator;
  391. typedef const_table_iterator const_iterator;
  392. typedef std::random_access_iterator_tag iterator_category;
  393. typedef typename tabletype::value_type value_type;
  394. typedef typename tabletype::difference_type difference_type;
  395. typedef typename tabletype::size_type size_type;
  396. typedef typename tabletype::const_reference reference; // we're const-only
  397. typedef typename tabletype::const_pointer pointer;
  398. // The "real" constructor
  399. const_table_iterator(const tabletype *tbl, size_type p)
  400. : table(tbl), pos(p) { }
  401. // The default constructor, used when I define vars of type table::iterator
  402. const_table_iterator() : table(NULL), pos(0) { }
  403. // The copy constructor, for when I say table::iterator foo = tbl.begin()
  404. // Also converts normal iterators to const iterators
  405. const_table_iterator(const iterator &from)
  406. : table(from.table), pos(from.pos) { }
  407. // The default destructor is fine; we don't define one
  408. // The default operator= is fine; we don't define one
  409. // The main thing our iterator does is dereference. If the table entry
  410. // we point to is empty, we return the default value type.
  411. reference operator*() const { return (*table)[pos]; }
  412. pointer operator->() const { return &(operator*()); }
  413. // Helper function to assert things are ok; eg pos is still in range
  414. void check() const {
  415. assert(table);
  416. assert(pos <= table->size());
  417. }
  418. // Arithmetic: we just do arithmetic on pos. We don't even need to
  419. // do bounds checking, since STL doesn't consider that its job. :-)
  420. const_iterator& operator+=(size_type t) { pos += t; check(); return *this; }
  421. const_iterator& operator-=(size_type t) { pos -= t; check(); return *this; }
  422. const_iterator& operator++() { ++pos; check(); return *this; }
  423. const_iterator& operator--() { --pos; check(); return *this; }
  424. const_iterator operator++(int) { const_iterator tmp(*this); // for x++
  425. ++pos; check(); return tmp; }
  426. const_iterator operator--(int) { const_iterator tmp(*this); // for x--
  427. --pos; check(); return tmp; }
  428. const_iterator operator+(difference_type i) const { const_iterator tmp(*this);
  429. tmp += i; return tmp; }
  430. const_iterator operator-(difference_type i) const { const_iterator tmp(*this);
  431. tmp -= i; return tmp; }
  432. difference_type operator-(const_iterator it) const { // for "x = it2 - it"
  433. assert(table == it.table);
  434. return pos - it.pos;
  435. }
  436. reference operator[](difference_type n) const {
  437. return *(*this + n); // simple though not totally efficient
  438. }
  439. // Comparisons.
  440. bool operator==(const const_iterator& it) const {
  441. return table == it.table && pos == it.pos;
  442. }
  443. bool operator<(const const_iterator& it) const {
  444. assert(table == it.table); // life is bad bad bad otherwise
  445. return pos < it.pos;
  446. }
  447. bool operator!=(const const_iterator& it) const { return !(*this == it); }
  448. bool operator<=(const const_iterator& it) const { return !(it < *this); }
  449. bool operator>(const const_iterator& it) const { return it < *this; }
  450. bool operator>=(const const_iterator& it) const { return !(*this < it); }
  451. // Here's the info we actually need to be an iterator
  452. const tabletype *table; // so we can dereference and bounds-check
  453. size_type pos; // index into the table
  454. };
  455. // support for "3 + iterator" has to be defined outside the class, alas
  456. template<class T>
  457. const_table_iterator<T> operator+(typename
  458. const_table_iterator<T>::difference_type i,
  459. const_table_iterator<T> it) {
  460. return it + i; // so people can say it2 = 3 + it
  461. }
  462. // ---------------------------------------------------------------------------
  463. /*
  464. // This is a 2-D iterator. You specify a begin and end over a list
  465. // of *containers*. We iterate over each container by iterating over
  466. // it. It's actually simple:
  467. // VECTOR.begin() VECTOR[0].begin() --------> VECTOR[0].end() ---,
  468. // | ________________________________________________/
  469. // | \_> VECTOR[1].begin() --------> VECTOR[1].end() -,
  470. // | ___________________________________________________/
  471. // v \_> ......
  472. // VECTOR.end()
  473. //
  474. // It's impossible to do random access on one of these things in constant
  475. // time, so it's just a bidirectional iterator.
  476. //
  477. // Unfortunately, because we need to use this for a non-empty iterator,
  478. // we use nonempty_begin() and nonempty_end() instead of begin() and end()
  479. // (though only going across, not down).
  480. */
  481. #define TWOD_BEGIN_ nonempty_begin
  482. #define TWOD_END_ nonempty_end
  483. #define TWOD_ITER_ nonempty_iterator
  484. #define TWOD_CONST_ITER_ const_nonempty_iterator
  485. template <class containertype>
  486. class two_d_iterator {
  487. public:
  488. typedef two_d_iterator iterator;
  489. typedef std::bidirectional_iterator_tag iterator_category;
  490. // apparently some versions of VC++ have trouble with two ::'s in a typename
  491. typedef typename containertype::value_type _tmp_vt;
  492. typedef typename _tmp_vt::value_type value_type;
  493. typedef typename _tmp_vt::difference_type difference_type;
  494. typedef typename _tmp_vt::reference reference;
  495. typedef typename _tmp_vt::pointer pointer;
  496. // The "real" constructor. begin and end specify how many rows we have
  497. // (in the diagram above); we always iterate over each row completely.
  498. two_d_iterator(typename containertype::iterator begin,
  499. typename containertype::iterator end,
  500. typename containertype::iterator curr)
  501. : row_begin(begin), row_end(end), row_current(curr), col_current() {
  502. if ( row_current != row_end ) {
  503. col_current = row_current->TWOD_BEGIN_();
  504. advance_past_end(); // in case cur->begin() == cur->end()
  505. }
  506. }
  507. // If you want to start at an arbitrary place, you can, I guess
  508. two_d_iterator(typename containertype::iterator begin,
  509. typename containertype::iterator end,
  510. typename containertype::iterator curr,
  511. typename containertype::value_type::TWOD_ITER_ col)
  512. : row_begin(begin), row_end(end), row_current(curr), col_current(col) {
  513. advance_past_end(); // in case cur->begin() == cur->end()
  514. }
  515. // The default constructor, used when I define vars of type table::iterator
  516. two_d_iterator() : row_begin(), row_end(), row_current(), col_current() { }
  517. // The default destructor is fine; we don't define one
  518. // The default operator= is fine; we don't define one
  519. // Happy dereferencer
  520. reference operator*() const { return *col_current; }
  521. pointer operator->() const { return &(operator*()); }
  522. // Arithmetic: we just do arithmetic on pos. We don't even need to
  523. // do bounds checking, since STL doesn't consider that its job. :-)
  524. // NOTE: this is not amortized constant time! What do we do about it?
  525. void advance_past_end() { // used when col_current points to end()
  526. while ( col_current == row_current->TWOD_END_() ) { // end of current row
  527. ++row_current; // go to beginning of next
  528. if ( row_current != row_end ) // col is irrelevant at end
  529. col_current = row_current->TWOD_BEGIN_();
  530. else
  531. break; // don't go past row_end
  532. }
  533. }
  534. iterator& operator++() {
  535. assert(row_current != row_end); // how to ++ from there?
  536. ++col_current;
  537. advance_past_end(); // in case col_current is at end()
  538. return *this;
  539. }
  540. iterator& operator--() {
  541. while ( row_current == row_end ||
  542. col_current == row_current->TWOD_BEGIN_() ) {
  543. assert(row_current != row_begin);
  544. --row_current;
  545. col_current = row_current->TWOD_END_(); // this is 1 too far
  546. }
  547. --col_current;
  548. return *this;
  549. }
  550. iterator operator++(int) { iterator tmp(*this); ++*this; return tmp; }
  551. iterator operator--(int) { iterator tmp(*this); --*this; return tmp; }
  552. // Comparisons.
  553. bool operator==(const iterator& it) const {
  554. return ( row_begin == it.row_begin &&
  555. row_end == it.row_end &&
  556. row_current == it.row_current &&
  557. (row_current == row_end || col_current == it.col_current) );
  558. }
  559. bool operator!=(const iterator& it) const { return !(*this == it); }
  560. // Here's the info we actually need to be an iterator
  561. // These need to be public so we convert from iterator to const_iterator
  562. typename containertype::iterator row_begin, row_end, row_current;
  563. typename containertype::value_type::TWOD_ITER_ col_current;
  564. };
  565. // The same thing again, but this time const. :-(
  566. template <class containertype>
  567. class const_two_d_iterator {
  568. public:
  569. typedef const_two_d_iterator iterator;
  570. typedef std::bidirectional_iterator_tag iterator_category;
  571. // apparently some versions of VC++ have trouble with two ::'s in a typename
  572. typedef typename containertype::value_type _tmp_vt;
  573. typedef typename _tmp_vt::value_type value_type;
  574. typedef typename _tmp_vt::difference_type difference_type;
  575. typedef typename _tmp_vt::const_reference reference;
  576. typedef typename _tmp_vt::const_pointer pointer;
  577. const_two_d_iterator(typename containertype::const_iterator begin,
  578. typename containertype::const_iterator end,
  579. typename containertype::const_iterator curr)
  580. : row_begin(begin), row_end(end), row_current(curr), col_current() {
  581. if ( curr != end ) {
  582. col_current = curr->TWOD_BEGIN_();
  583. advance_past_end(); // in case cur->begin() == cur->end()
  584. }
  585. }
  586. const_two_d_iterator(typename containertype::const_iterator begin,
  587. typename containertype::const_iterator end,
  588. typename containertype::const_iterator curr,
  589. typename containertype::value_type::TWOD_CONST_ITER_ col)
  590. : row_begin(begin), row_end(end), row_current(curr), col_current(col) {
  591. advance_past_end(); // in case cur->begin() == cur->end()
  592. }
  593. const_two_d_iterator()
  594. : row_begin(), row_end(), row_current(), col_current() {
  595. }
  596. // Need this explicitly so we can convert normal iterators to const iterators
  597. const_two_d_iterator(const two_d_iterator<containertype>& it) :
  598. row_begin(it.row_begin), row_end(it.row_end), row_current(it.row_current),
  599. col_current(it.col_current) { }
  600. typename containertype::const_iterator row_begin, row_end, row_current;
  601. typename containertype::value_type::TWOD_CONST_ITER_ col_current;
  602. // EVERYTHING FROM HERE DOWN IS THE SAME AS THE NON-CONST ITERATOR
  603. reference operator*() const { return *col_current; }
  604. pointer operator->() const { return &(operator*()); }
  605. void advance_past_end() { // used when col_current points to end()
  606. while ( col_current == row_current->TWOD_END_() ) { // end of current row
  607. ++row_current; // go to beginning of next
  608. if ( row_current != row_end ) // col is irrelevant at end
  609. col_current = row_current->TWOD_BEGIN_();
  610. else
  611. break; // don't go past row_end
  612. }
  613. }
  614. iterator& operator++() {
  615. assert(row_current != row_end); // how to ++ from there?
  616. ++col_current;
  617. advance_past_end(); // in case col_current is at end()
  618. return *this;
  619. }
  620. iterator& operator--() {
  621. while ( row_current == row_end ||
  622. col_current == row_current->TWOD_BEGIN_() ) {
  623. assert(row_current != row_begin);
  624. --row_current;
  625. col_current = row_current->TWOD_END_(); // this is 1 too far
  626. }
  627. --col_current;
  628. return *this;
  629. }
  630. iterator operator++(int) { iterator tmp(*this); ++*this; return tmp; }
  631. iterator operator--(int) { iterator tmp(*this); --*this; return tmp; }
  632. bool operator==(const iterator& it) const {
  633. return ( row_begin == it.row_begin &&
  634. row_end == it.row_end &&
  635. row_current == it.row_current &&
  636. (row_current == row_end || col_current == it.col_current) );
  637. }
  638. bool operator!=(const iterator& it) const { return !(*this == it); }
  639. };
  640. // We provide yet another version, to be as frugal with memory as
  641. // possible. This one frees each block of memory as it finishes
  642. // iterating over it. By the end, the entire table is freed.
  643. // For understandable reasons, you can only iterate over it once,
  644. // which is why it's an input iterator
  645. template <class containertype>
  646. class destructive_two_d_iterator {
  647. public:
  648. typedef destructive_two_d_iterator iterator;
  649. typedef std::input_iterator_tag iterator_category;
  650. // apparently some versions of VC++ have trouble with two ::'s in a typename
  651. typedef typename containertype::value_type _tmp_vt;
  652. typedef typename _tmp_vt::value_type value_type;
  653. typedef typename _tmp_vt::difference_type difference_type;
  654. typedef typename _tmp_vt::reference reference;
  655. typedef typename _tmp_vt::pointer pointer;
  656. destructive_two_d_iterator(typename containertype::iterator begin,
  657. typename containertype::iterator end,
  658. typename containertype::iterator curr)
  659. : row_begin(begin), row_end(end), row_current(curr), col_current() {
  660. if ( curr != end ) {
  661. col_current = curr->TWOD_BEGIN_();
  662. advance_past_end(); // in case cur->begin() == cur->end()
  663. }
  664. }
  665. destructive_two_d_iterator(typename containertype::iterator begin,
  666. typename containertype::iterator end,
  667. typename containertype::iterator curr,
  668. typename containertype::value_type::TWOD_ITER_ col)
  669. : row_begin(begin), row_end(end), row_current(curr), col_current(col) {
  670. advance_past_end(); // in case cur->begin() == cur->end()
  671. }
  672. destructive_two_d_iterator()
  673. : row_begin(), row_end(), row_current(), col_current() {
  674. }
  675. typename containertype::iterator row_begin, row_end, row_current;
  676. typename containertype::value_type::TWOD_ITER_ col_current;
  677. // This is the part that destroys
  678. void advance_past_end() { // used when col_current points to end()
  679. while ( col_current == row_current->TWOD_END_() ) { // end of current row
  680. row_current->clear(); // the destructive part
  681. // It would be nice if we could decrement sparsetable->num_buckets here
  682. ++row_current; // go to beginning of next
  683. if ( row_current != row_end ) // col is irrelevant at end
  684. col_current = row_current->TWOD_BEGIN_();
  685. else
  686. break; // don't go past row_end
  687. }
  688. }
  689. // EVERYTHING FROM HERE DOWN IS THE SAME AS THE REGULAR ITERATOR
  690. reference operator*() const { return *col_current; }
  691. pointer operator->() const { return &(operator*()); }
  692. iterator& operator++() {
  693. assert(row_current != row_end); // how to ++ from there?
  694. ++col_current;
  695. advance_past_end(); // in case col_current is at end()
  696. return *this;
  697. }
  698. iterator operator++(int) { iterator tmp(*this); ++*this; return tmp; }
  699. bool operator==(const iterator& it) const {
  700. return ( row_begin == it.row_begin &&
  701. row_end == it.row_end &&
  702. row_current == it.row_current &&
  703. (row_current == row_end || col_current == it.col_current) );
  704. }
  705. bool operator!=(const iterator& it) const { return !(*this == it); }
  706. };
  707. #undef TWOD_BEGIN_
  708. #undef TWOD_END_
  709. #undef TWOD_ITER_
  710. #undef TWOD_CONST_ITER_
  711. // SPARSE-TABLE
  712. // ------------
  713. // The idea is that a table with (logically) t buckets is divided
  714. // into t/M *groups* of M buckets each. (M is a constant set in
  715. // GROUP_SIZE for efficiency.) Each group is stored sparsely.
  716. // Thus, inserting into the table causes some array to grow, which is
  717. // slow but still constant time. Lookup involves doing a
  718. // logical-position-to-sparse-position lookup, which is also slow but
  719. // constant time. The larger M is, the slower these operations are
  720. // but the less overhead (slightly).
  721. //
  722. // To store the sparse array, we store a bitmap B, where B[i] = 1 iff
  723. // bucket i is non-empty. Then to look up bucket i we really look up
  724. // array[# of 1s before i in B]. This is constant time for fixed M.
  725. //
  726. // Terminology: the position of an item in the overall table (from
  727. // 1 .. t) is called its "location." The logical position in a group
  728. // (from 1 .. M ) is called its "position." The actual location in
  729. // the array (from 1 .. # of non-empty buckets in the group) is
  730. // called its "offset."
  731. template <class T, u_int16_t GROUP_SIZE, class Alloc>
  732. class sparsegroup {
  733. private:
  734. typedef typename Alloc::template rebind<T>::other value_alloc_type;
  735. public:
  736. // Basic types
  737. typedef T value_type;
  738. typedef Alloc allocator_type;
  739. typedef typename value_alloc_type::reference reference;
  740. typedef typename value_alloc_type::const_reference const_reference;
  741. typedef typename value_alloc_type::pointer pointer;
  742. typedef typename value_alloc_type::const_pointer const_pointer;
  743. typedef table_iterator<sparsegroup<T, GROUP_SIZE, Alloc> > iterator;
  744. typedef const_table_iterator<sparsegroup<T, GROUP_SIZE, Alloc> >
  745. const_iterator;
  746. typedef table_element_adaptor<sparsegroup<T, GROUP_SIZE, Alloc> >
  747. element_adaptor;
  748. typedef u_int16_t size_type; // max # of buckets
  749. typedef int16_t difference_type;
  750. typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
  751. typedef std::reverse_iterator<iterator> reverse_iterator; // from iterator.h
  752. // These are our special iterators, that go over non-empty buckets in a
  753. // group. These aren't const-only because you can change non-empty bcks.
  754. typedef pointer nonempty_iterator;
  755. typedef const_pointer const_nonempty_iterator;
  756. typedef std::reverse_iterator<nonempty_iterator> reverse_nonempty_iterator;
  757. typedef std::reverse_iterator<const_nonempty_iterator> const_reverse_nonempty_iterator;
  758. // Iterator functions
  759. iterator begin() { return iterator(this, 0); }
  760. const_iterator begin() const { return const_iterator(this, 0); }
  761. iterator end() { return iterator(this, size()); }
  762. const_iterator end() const { return const_iterator(this, size()); }
  763. reverse_iterator rbegin() { return reverse_iterator(end()); }
  764. const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); }
  765. reverse_iterator rend() { return reverse_iterator(begin()); }
  766. const_reverse_iterator rend() const { return const_reverse_iterator(begin()); }
  767. // We'll have versions for our special non-empty iterator too
  768. nonempty_iterator nonempty_begin() { return group; }
  769. const_nonempty_iterator nonempty_begin() const { return group; }
  770. nonempty_iterator nonempty_end() {
  771. return group + settings.num_buckets;
  772. }
  773. const_nonempty_iterator nonempty_end() const {
  774. return group + settings.num_buckets;
  775. }
  776. reverse_nonempty_iterator nonempty_rbegin() {
  777. return reverse_nonempty_iterator(nonempty_end());
  778. }
  779. const_reverse_nonempty_iterator nonempty_rbegin() const {
  780. return const_reverse_nonempty_iterator(nonempty_end());
  781. }
  782. reverse_nonempty_iterator nonempty_rend() {
  783. return reverse_nonempty_iterator(nonempty_begin());
  784. }
  785. const_reverse_nonempty_iterator nonempty_rend() const {
  786. return const_reverse_nonempty_iterator(nonempty_begin());
  787. }
  788. // This gives us the "default" value to return for an empty bucket.
  789. // We just use the default constructor on T, the template type
  790. const_reference default_value() const {
  791. static value_type defaultval = value_type();
  792. return defaultval;
  793. }
  794. private:
  795. // We need to do all this bit manipulation, of course. ick
  796. static size_type charbit(size_type i) { return i >> 3; }
  797. static size_type modbit(size_type i) { return 1 << (i&7); }
  798. int bmtest(size_type i) const { return bitmap[charbit(i)] & modbit(i); }
  799. void bmset(size_type i) { bitmap[charbit(i)] |= modbit(i); }
  800. void bmclear(size_type i) { bitmap[charbit(i)] &= ~modbit(i); }
  801. pointer allocate_group(size_type n) {
  802. pointer retval = settings.allocate(n);
  803. if (retval == NULL) {
  804. // We really should use PRIuS here, but I don't want to have to add
  805. // a whole new configure option, with concomitant macro namespace
  806. // pollution, just to print this (unlikely) error message. So I cast.
  807. fprintf(stderr, "sparsehash FATAL ERROR: failed to allocate %lu groups\n",
  808. static_cast<unsigned long>(n));
  809. exit(1);
  810. }
  811. return retval;
  812. }
  813. void free_group() {
  814. if (!group) return;
  815. pointer end_it = group + settings.num_buckets;
  816. for (pointer p = group; p != end_it; ++p)
  817. p->~value_type();
  818. settings.deallocate(group, settings.num_buckets);
  819. group = NULL;
  820. }
  821. static size_type bits_in_char(unsigned char c) {
  822. // We could make these ints. The tradeoff is size (eg does it overwhelm
  823. // the cache?) vs efficiency in referencing sub-word-sized array elements.
  824. static const char bits_in[256] = {
  825. 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,
  826. 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  827. 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  828. 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  829. 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  830. 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  831. 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  832. 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  833. 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  834. 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  835. 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  836. 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  837. 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  838. 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  839. 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  840. 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8,
  841. };
  842. return bits_in[c];
  843. }
  844. public: // get_iter() in sparsetable needs it
  845. // We need a small function that tells us how many set bits there are
  846. // in positions 0..i-1 of the bitmap. It uses a big table.
  847. // We make it static so templates don't allocate lots of these tables.
  848. // There are lots of ways to do this calculation (called 'popcount').
  849. // The 8-bit table lookup is one of the fastest, though this
  850. // implementation suffers from not doing any loop unrolling. See, eg,
  851. // http://www.dalkescientific.com/writings/diary/archive/2008/07/03/hakmem_and_other_popcounts.html
  852. // http://gurmeetsingh.wordpress.com/2008/08/05/fast-bit-counting-routines/
  853. static size_type pos_to_offset(const unsigned char *bm, size_type pos) {
  854. size_type retval = 0;
  855. // [Note: condition pos > 8 is an optimization; convince yourself we
  856. // give exactly the same result as if we had pos >= 8 here instead.]
  857. for ( ; pos > 8; pos -= 8 ) // bm[0..pos/8-1]
  858. retval += bits_in_char(*bm++); // chars we want *all* bits in
  859. return retval + bits_in_char(*bm & ((1 << pos)-1)); // char including pos
  860. }
  861. size_type pos_to_offset(size_type pos) const { // not static but still const
  862. return pos_to_offset(bitmap, pos);
  863. }
  864. // Returns the (logical) position in the bm[] array, i, such that
  865. // bm[i] is the offset-th set bit in the array. It is the inverse
  866. // of pos_to_offset. get_pos() uses this function to find the index
  867. // of an nonempty_iterator in the table. Bit-twiddling from
  868. // http://hackersdelight.org/basics.pdf
  869. static size_type offset_to_pos(const unsigned char *bm, size_type offset) {
  870. size_type retval = 0;
  871. // This is sizeof(this->bitmap).
  872. const size_type group_size = (GROUP_SIZE-1) / 8 + 1;
  873. for (size_type i = 0; i < group_size; i++) { // forward scan
  874. const size_type pop_count = bits_in_char(*bm);
  875. if (pop_count > offset) {
  876. unsigned char last_bm = *bm;
  877. for (; offset > 0; offset--) {
  878. last_bm &= (last_bm-1); // remove right-most set bit
  879. }
  880. // Clear all bits to the left of the rightmost bit (the &),
  881. // and then clear the rightmost bit but set all bits to the
  882. // right of it (the -1).
  883. last_bm = (last_bm & -last_bm) - 1;
  884. retval += bits_in_char(last_bm);
  885. return retval;
  886. }
  887. offset -= pop_count;
  888. retval += 8;
  889. bm++;
  890. }
  891. return retval;
  892. }
  893. size_type offset_to_pos(size_type offset) const {
  894. return offset_to_pos(bitmap, offset);
  895. }
  896. public:
  897. // Constructors -- default and copy -- and destructor
  898. explicit sparsegroup(allocator_type& a) :
  899. group(0), settings(alloc_impl<value_alloc_type>(a)) {
  900. memset(bitmap, 0, sizeof(bitmap));
  901. }
  902. sparsegroup(const sparsegroup& x) : group(0), settings(x.settings) {
  903. if ( settings.num_buckets ) {
  904. group = allocate_group(x.settings.num_buckets);
  905. std::uninitialized_copy(x.group, x.group + x.settings.num_buckets, group);
  906. }
  907. memcpy(bitmap, x.bitmap, sizeof(bitmap));
  908. }
  909. ~sparsegroup() { free_group(); }
  910. // Operator= is just like the copy constructor, I guess
  911. // TODO(austern): Make this exception safe. Handle exceptions in value_type's
  912. // copy constructor.
  913. sparsegroup &operator=(const sparsegroup& x) {
  914. if ( &x == this ) return *this; // x = x
  915. if ( x.settings.num_buckets == 0 ) {
  916. free_group();
  917. } else {
  918. pointer p = allocate_group(x.settings.num_buckets);
  919. std::uninitialized_copy(x.group, x.group + x.settings.num_buckets, p);
  920. free_group();
  921. group = p;
  922. }
  923. memcpy(bitmap, x.bitmap, sizeof(bitmap));
  924. settings.num_buckets = x.settings.num_buckets;
  925. return *this;
  926. }
  927. // Many STL algorithms use swap instead of copy constructors
  928. void swap(sparsegroup& x) {
  929. std::swap(group, x.group); // defined in <algorithm>
  930. for ( int i = 0; i < sizeof(bitmap) / sizeof(*bitmap); ++i )
  931. std::swap(bitmap[i], x.bitmap[i]); // swap not defined on arrays
  932. std::swap(settings.num_buckets, x.settings.num_buckets);
  933. // we purposefully don't swap the allocator, which may not be swap-able
  934. }
  935. // It's always nice to be able to clear a table without deallocating it
  936. void clear() {
  937. free_group();
  938. memset(bitmap, 0, sizeof(bitmap));
  939. settings.num_buckets = 0;
  940. }
  941. // Functions that tell you about size. Alas, these aren't so useful
  942. // because our table is always fixed size.
  943. size_type size() const { return GROUP_SIZE; }
  944. size_type max_size() const { return GROUP_SIZE; }
  945. bool empty() const { return false; }
  946. // We also may want to know how many *used* buckets there are
  947. size_type num_nonempty() const { return settings.num_buckets; }
  948. // get()/set() are explicitly const/non-const. You can use [] if
  949. // you want something that can be either (potentially more expensive).
  950. const_reference get(size_type i) const {
  951. if ( bmtest(i) ) // bucket i is occupied
  952. return group[pos_to_offset(bitmap, i)];
  953. else
  954. return default_value(); // return the default reference
  955. }
  956. // TODO(csilvers): make protected + friend
  957. // This is used by sparse_hashtable to get an element from the table
  958. // when we know it exists.
  959. const_reference unsafe_get(size_type i) const {
  960. assert(bmtest(i));
  961. return group[pos_to_offset(bitmap, i)];
  962. }
  963. // TODO(csilvers): make protected + friend
  964. reference mutating_get(size_type i) { // fills bucket i before getting
  965. if ( !bmtest(i) )
  966. set(i, default_value());
  967. return group[pos_to_offset(bitmap, i)];
  968. }
  969. // Syntactic sugar. It's easy to return a const reference. To
  970. // return a non-const reference, we need to use the assigner adaptor.
  971. const_reference operator[](size_type i) const {
  972. return get(i);
  973. }
  974. element_adaptor operator[](size_type i) {
  975. return element_adaptor(this, i);
  976. }
  977. private:
  978. // Create space at group[offset], assuming value_type has trivial
  979. // copy constructor and destructor, and the allocator_type is
  980. // the default libc_allocator_with_alloc. (Really, we want it to have
  981. // "trivial move", because that's what realloc and memmove both do.
  982. // But there's no way to capture that using type_traits, so we
  983. // pretend that move(x, y) is equivalent to "x.~T(); new(x) T(y);"
  984. // which is pretty much correct, if a bit conservative.)
  985. void set_aux(size_type offset, base::true_type) {
  986. group = settings.realloc_or_die(group, settings.num_buckets+1);
  987. // This is equivalent to memmove(), but faster on my Intel P4,
  988. // at least with gcc4.1 -O2 / glibc 2.3.6.
  989. for (size_type i = settings.num_buckets; i > offset; --i)
  990. // cast to void* to prevent compiler warnings about writing to an object
  991. // with no trivial copy-assignment
  992. memcpy(static_cast<void*>(group + i), group + i-1, sizeof(*group));
  993. }
  994. // Create space at group[offset], without special assumptions about value_type
  995. // and allocator_type.
  996. void set_aux(size_type offset, base::false_type) {
  997. // This is valid because 0 <= offset <= num_buckets
  998. pointer p = allocate_group(settings.num_buckets + 1);
  999. std::uninitialized_copy(group, group + offset, p);
  1000. std::uninitialized_copy(group + offset, group + settings.num_buckets,
  1001. p + offset + 1);
  1002. free_group();
  1003. group = p;
  1004. }
  1005. public:
  1006. // This returns a reference to the inserted item (which is a copy of val).
  1007. // TODO(austern): Make this exception safe: handle exceptions from
  1008. // value_type's copy constructor.
  1009. reference set(size_type i, const_reference val) {
  1010. size_type offset = pos_to_offset(bitmap, i); // where we'll find (or insert)
  1011. if ( bmtest(i) ) {
  1012. // Delete the old value, which we're replacing with the new one
  1013. group[offset].~value_type();
  1014. } else {
  1015. typedef base::integral_constant<bool,
  1016. (base::has_trivial_copy<value_type>::value &&
  1017. base::has_trivial_destructor<value_type>::value &&
  1018. base::is_same<
  1019. allocator_type,
  1020. libc_allocator_with_realloc<value_type> >::value)>
  1021. realloc_and_memmove_ok; // we pretend mv(x,y) == "x.~T(); new(x) T(y)"
  1022. set_aux(offset, realloc_and_memmove_ok());
  1023. ++settings.num_buckets;
  1024. bmset(i);
  1025. }
  1026. // This does the actual inserting. Since we made the array using
  1027. // malloc, we use "placement new" to just call the constructor.
  1028. new(&group[offset]) value_type(val);
  1029. return group[offset];
  1030. }
  1031. // We let you see if a bucket is non-empty without retrieving it
  1032. bool test(size_type i) const {
  1033. return bmtest(i) != 0;
  1034. }
  1035. bool test(iterator pos) const {
  1036. return bmtest(pos.pos) != 0;
  1037. }
  1038. private:
  1039. // Shrink the array, assuming value_type has trivial copy
  1040. // constructor and destructor, and the allocator_type is the default
  1041. // libc_allocator_with_alloc. (Really, we want it to have "trivial
  1042. // move", because that's what realloc and memmove both do. But
  1043. // there's no way to capture that using type_traits, so we pretend
  1044. // that move(x, y) is equivalent to ""x.~T(); new(x) T(y);"
  1045. // which is pretty much correct, if a bit conservative.)
  1046. void erase_aux(size_type offset, base::true_type) {
  1047. // This isn't technically necessary, since we know we have a
  1048. // trivial destructor, but is a cheap way to get a bit more safety.
  1049. group[offset].~value_type();
  1050. // This is equivalent to memmove(), but faster on my Intel P4,
  1051. // at lesat with gcc4.1 -O2 / glibc 2.3.6.
  1052. assert(settings.num_buckets > 0);
  1053. for (size_type i = offset; i < settings.num_buckets-1; ++i)
  1054. // cast to void* to prevent compiler warnings about writing to an object
  1055. // with no trivial copy-assignment
  1056. // hopefully inlined!
  1057. memcpy(static_cast<void*>(group + i), group + i+1, sizeof(*group));
  1058. group = settings.realloc_or_die(group, settings.num_buckets-1);
  1059. }
  1060. // Shrink the array, without any special assumptions about value_type and
  1061. // allocator_type.
  1062. void erase_aux(size_type offset, base::false_type) {
  1063. // This is valid because 0 <= offset < num_buckets. Note the inequality.
  1064. pointer p = allocate_group(settings.num_buckets - 1);
  1065. std::uninitialized_copy(group, group + offset, p);
  1066. std::uninitialized_copy(group + offset + 1, group + settings.num_buckets,
  1067. p + offset);
  1068. free_group();
  1069. group = p;
  1070. }
  1071. public:
  1072. // This takes the specified elements out of the group. This is
  1073. // "undefining", rather than "clearing".
  1074. // TODO(austern): Make this exception safe: handle exceptions from
  1075. // value_type's copy constructor.
  1076. void erase(size_type i) {
  1077. if ( bmtest(i) ) { // trivial to erase empty bucket
  1078. size_type offset = pos_to_offset(bitmap,i); // where we'll find (or insert)
  1079. if ( settings.num_buckets == 1 ) {
  1080. free_group();
  1081. group = NULL;
  1082. } else {
  1083. typedef base::integral_constant<bool,
  1084. (base::has_trivial_copy<value_type>::value &&
  1085. base::has_trivial_destructor<value_type>::value &&
  1086. base::is_same<
  1087. allocator_type,
  1088. libc_allocator_with_realloc<value_type> >::value)>
  1089. realloc_and_memmove_ok; // pretend mv(x,y) == "x.~T(); new(x) T(y)"
  1090. erase_aux(offset, realloc_and_memmove_ok());
  1091. }
  1092. --settings.num_buckets;
  1093. bmclear(i);
  1094. }
  1095. }
  1096. void erase(iterator pos) {
  1097. erase(pos.pos);
  1098. }
  1099. void erase(iterator start_it, iterator end_it) {
  1100. // This could be more efficient, but to do so we'd need to make
  1101. // bmclear() clear a range of indices. Doesn't seem worth it.
  1102. for ( ; start_it != end_it; ++start_it )
  1103. erase(start_it);
  1104. }
  1105. // I/O
  1106. // We support reading and writing groups to disk. We don't store
  1107. // the actual array contents (which we don't know how to store),
  1108. // just the bitmap and size. Meant to be used with table I/O.
  1109. template <typename OUTPUT> bool write_metadata(OUTPUT *fp) const {
  1110. // we explicitly set to u_int16_t
  1111. assert(sizeof(settings.num_buckets) == 2);
  1112. if ( !sparsehash_internal::write_bigendian_number(fp, settings.num_buckets,
  1113. 2) )
  1114. return false;
  1115. if ( !sparsehash_internal::write_data(fp, bitmap, sizeof(bitmap)) )
  1116. return false;
  1117. return true;
  1118. }
  1119. // Reading destroys the old group contents! Returns true if all was ok.
  1120. template <typename INPUT> bool read_metadata(INPUT *fp) {
  1121. clear();
  1122. if ( !sparsehash_internal::read_bigendian_number(fp, &settings.num_buckets,
  1123. 2) )
  1124. return false;
  1125. if ( !sparsehash_internal::read_data(fp, bitmap, sizeof(bitmap)) )
  1126. return false;
  1127. // We'll allocate the space, but we won't fill it: it will be
  1128. // left as uninitialized raw memory.
  1129. group = allocate_group(settings.num_buckets);
  1130. return true;
  1131. }
  1132. // Again, only meaningful if value_type is a POD.
  1133. template <typename INPUT> bool read_nopointer_data(INPUT *fp) {
  1134. for ( nonempty_iterator it = nonempty_begin();
  1135. it != nonempty_end(); ++it ) {
  1136. if ( !sparsehash_internal::read_data(fp, &(*it), sizeof(*it)) )
  1137. return false;
  1138. }
  1139. return true;
  1140. }
  1141. // If your keys and values are simple enough, we can write them
  1142. // to disk for you. "simple enough" means POD and no pointers.
  1143. // However, we don't try to normalize endianness.
  1144. template <typename OUTPUT> bool write_nopointer_data(OUTPUT *fp) const {
  1145. for ( const_nonempty_iterator it = nonempty_begin();
  1146. it != nonempty_end(); ++it ) {
  1147. if ( !sparsehash_internal::write_data(fp, &(*it), sizeof(*it)) )
  1148. return false;
  1149. }
  1150. return true;
  1151. }
  1152. // Comparisons. We only need to define == and < -- we get
  1153. // != > <= >= via relops.h (which we happily included above).
  1154. // Note the comparisons are pretty arbitrary: we compare
  1155. // values of the first index that isn't equal (using default
  1156. // value for empty buckets).
  1157. bool operator==(const sparsegroup& x) const {
  1158. return ( settings.num_buckets == x.settings.num_buckets &&
  1159. memcmp(bitmap, x.bitmap, sizeof(bitmap)) == 0 &&
  1160. std::equal(begin(), end(), x.begin()) ); // from <algorithm>
  1161. }
  1162. bool operator<(const sparsegroup& x) const { // also from <algorithm>
  1163. return std::lexicographical_compare(begin(), end(), x.begin(), x.end());
  1164. }
  1165. bool operator!=(const sparsegroup& x) const { return !(*this == x); }
  1166. bool operator<=(const sparsegroup& x) const { return !(x < *this); }
  1167. bool operator>(const sparsegroup& x) const { return x < *this; }
  1168. bool operator>=(const sparsegroup& x) const { return !(*this < x); }
  1169. private:
  1170. template <class A>
  1171. class alloc_impl : public A {
  1172. public:
  1173. typedef typename A::pointer pointer;
  1174. typedef typename A::size_type size_type;
  1175. // Convert a normal allocator to one that has realloc_or_die()
  1176. alloc_impl(const A& a) : A(a) { }
  1177. // realloc_or_die should only be used when using the default
  1178. // allocator (libc_allocator_with_realloc).
  1179. pointer realloc_or_die(pointer /*ptr*/, size_type /*n*/) {
  1180. fprintf(stderr, "realloc_or_die is only supported for "
  1181. "libc_allocator_with_realloc\n");
  1182. exit(1);
  1183. return NULL;
  1184. }
  1185. };
  1186. // A template specialization of alloc_impl for
  1187. // libc_allocator_with_realloc that can handle realloc_or_die.
  1188. template <class A>
  1189. class alloc_impl<libc_allocator_with_realloc<A> >
  1190. : public libc_allocator_with_realloc<A> {
  1191. public:
  1192. typedef typename libc_allocator_with_realloc<A>::pointer pointer;
  1193. typedef typename libc_allocator_with_realloc<A>::size_type size_type;
  1194. alloc_impl(const libc_allocator_with_realloc<A>& a)
  1195. : libc_allocator_with_realloc<A>(a) { }
  1196. pointer realloc_or_die(pointer ptr, size_type n) {
  1197. pointer retval = this->reallocate(ptr, n);
  1198. if (retval == NULL) {
  1199. fprintf(stderr, "sparsehash: FATAL ERROR: failed to reallocate "
  1200. "%lu elements for ptr %p", static_cast<unsigned long>(n), ptr);
  1201. exit(1);
  1202. }
  1203. return retval;
  1204. }
  1205. };
  1206. // Package allocator with num_buckets to eliminate memory needed for the
  1207. // zero-size allocator.
  1208. // If new fields are added to this class, we should add them to
  1209. // operator= and swap.
  1210. class Settings : public alloc_impl<value_alloc_type> {
  1211. public:
  1212. Settings(const alloc_impl<value_alloc_type>& a, u_int16_t n = 0)
  1213. : alloc_impl<value_alloc_type>(a), num_buckets(n) { }
  1214. Settings(const Settings& s)
  1215. : alloc_impl<value_alloc_type>(s), num_buckets(s.num_buckets) { }
  1216. u_int16_t num_buckets; // limits GROUP_SIZE to 64K
  1217. };
  1218. // The actual data
  1219. pointer group; // (small) array of T's
  1220. Settings settings; // allocator and num_buckets
  1221. unsigned char bitmap[(GROUP_SIZE-1)/8 + 1]; // fancy math is so we round up
  1222. };
  1223. // We need a global swap as well
  1224. template <class T, u_int16_t GROUP_SIZE, class Alloc>
  1225. inline void swap(sparsegroup<T,GROUP_SIZE,Alloc> &x,
  1226. sparsegroup<T,GROUP_SIZE,Alloc> &y) {
  1227. x.swap(y);
  1228. }
  1229. // ---------------------------------------------------------------------------
  1230. template <class T, u_int16_t GROUP_SIZE = DEFAULT_SPARSEGROUP_SIZE,
  1231. class Alloc = libc_allocator_with_realloc<T> >
  1232. class sparsetable {
  1233. private:
  1234. typedef typename Alloc::template rebind<T>::other value_alloc_type;
  1235. typedef typename Alloc::template rebind<
  1236. sparsegroup<T, GROUP_SIZE, value_alloc_type> >::other vector_alloc;
  1237. public:
  1238. // Basic types
  1239. typedef T value_type; // stolen from stl_vector.h
  1240. typedef Alloc allocator_type;
  1241. typedef typename value_alloc_type::size_type size_type;
  1242. typedef typename value_alloc_type::difference_type difference_type;
  1243. typedef typename value_alloc_type::reference reference;
  1244. typedef typename value_alloc_type::const_reference const_reference;
  1245. typedef typename value_alloc_type::pointer pointer;
  1246. typedef typename value_alloc_type::const_pointer const_pointer;
  1247. typedef table_iterator<sparsetable<T, GROUP_SIZE, Alloc> > iterator;
  1248. typedef const_table_iterator<sparsetable<T, GROUP_SIZE, Alloc> >
  1249. const_iterator;
  1250. typedef table_element_adaptor<sparsetable<T, GROUP_SIZE, Alloc> >
  1251. element_adaptor;
  1252. typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
  1253. typedef std::reverse_iterator<iterator> reverse_iterator; // from iterator.h
  1254. // These are our special iterators, that go over non-empty buckets in a
  1255. // table. These aren't const only because you can change non-empty bcks.
  1256. typedef two_d_iterator< std::vector< sparsegroup<value_type, GROUP_SIZE,
  1257. value_alloc_type>,
  1258. vector_alloc> >
  1259. nonempty_iterator;
  1260. typedef const_two_d_iterator< std::vector< sparsegroup<value_type,
  1261. GROUP_SIZE,
  1262. value_alloc_type>,
  1263. vector_alloc> >
  1264. const_nonempty_iterator;
  1265. typedef std::reverse_iterator<nonempty_iterator> reverse_nonempty_iterator;
  1266. typedef std::reverse_iterator<const_nonempty_iterator> const_reverse_nonempty_iterator;
  1267. // Another special iterator: it frees memory as it iterates (used to resize)
  1268. typedef destructive_two_d_iterator< std::vector< sparsegroup<value_type,
  1269. GROUP_SIZE,
  1270. value_alloc_type>,
  1271. vector_alloc> >
  1272. destructive_iterator;
  1273. // Iterator functions
  1274. iterator begin() { return iterator(this, 0); }
  1275. const_iterator begin() const { return const_iterator(this, 0); }
  1276. iterator end() { return iterator(this, size()); }
  1277. const_iterator end() const { return const_iterator(this, size()); }
  1278. reverse_iterator rbegin() { return reverse_iterator(end()); }
  1279. const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); }
  1280. reverse_iterator rend() { return reverse_iterator(begin()); }
  1281. const_reverse_iterator rend() const { return const_reverse_iterator(begin()); }
  1282. // Versions for our special non-empty iterator
  1283. nonempty_iterator nonempty_begin() {
  1284. return nonempty_iterator(groups.begin(), groups.end(), groups.begin());
  1285. }
  1286. const_nonempty_iterator nonempty_begin() const {
  1287. return const_nonempty_iterator(groups.begin(),groups.end(), groups.begin());
  1288. }
  1289. nonempty_iterator nonempty_end() {
  1290. return nonempty_iterator(groups.begin(), groups.end(), groups.end());
  1291. }
  1292. const_nonempty_iterator nonempty_end() const {
  1293. return const_nonempty_iterator(groups.begin(), groups.end(), groups.end());
  1294. }
  1295. reverse_nonempty_iterator nonempty_rbegin() {
  1296. return reverse_nonempty_iterator(nonempty_end());
  1297. }
  1298. const_reverse_nonempty_iterator nonempty_rbegin() const {
  1299. return const_reverse_nonempty_iterator(nonempty_end());
  1300. }
  1301. reverse_nonempty_iterator nonempty_rend() {
  1302. return reverse_nonempty_iterator(nonempty_begin());
  1303. }
  1304. const_reverse_nonempty_iterator nonempty_rend() const {
  1305. return const_reverse_nonempty_iterator(nonempty_begin());
  1306. }
  1307. destructive_iterator destructive_begin() {
  1308. return destructive_iterator(groups.begin(), groups.end(), groups.begin());
  1309. }
  1310. destructive_iterator destructive_end() {
  1311. return destructive_iterator(groups.begin(), groups.end(), groups.end());
  1312. }
  1313. typedef sparsegroup<value_type, GROUP_SIZE, allocator_type> group_type;
  1314. typedef std::vector<group_type, vector_alloc > group_vector_type;
  1315. typedef typename group_vector_type::reference GroupsReference;
  1316. typedef typename group_vector_type::const_reference GroupsConstReference;
  1317. typedef typename group_vector_type::iterator GroupsIterator;
  1318. typedef typename group_vector_type::const_iterator GroupsConstIterator;
  1319. // How to deal with the proper group
  1320. static size_type num_groups(size_type num) { // how many to hold num buckets
  1321. return num == 0 ? 0 : ((num-1) / GROUP_SIZE) + 1;
  1322. }
  1323. u_int16_t pos_in_group(size_type i) const {
  1324. return static_cast<u_int16_t>(i % GROUP_SIZE);
  1325. }
  1326. size_type group_num(size_type i) const {
  1327. return i / GROUP_SIZE;
  1328. }
  1329. GroupsReference which_group(size_type i) {
  1330. return groups[group_num(i)];
  1331. }
  1332. GroupsConstReference which_group(size_type i) const {
  1333. return groups[group_num(i)];
  1334. }
  1335. public:
  1336. // Constructors -- default, normal (when you specify size), and copy
  1337. explicit sparsetable(size_type sz = 0, Alloc alloc = Alloc())
  1338. : groups(vector_alloc(alloc)), settings(alloc, sz) {
  1339. groups.resize(num_groups(sz), group_type(settings));
  1340. }
  1341. // We can get away with using the default copy constructor,
  1342. // and default destructor, and hence the default operator=. Huzzah!
  1343. // Many STL algorithms use swap instead of copy constructors
  1344. void swap(sparsetable& x) {
  1345. std::swap(groups, x.groups); // defined in stl_algobase.h
  1346. std::swap(settings.table_size, x.settings.table_size);
  1347. std::swap(settings.num_buckets, x.settings.num_buckets);
  1348. }
  1349. // It's always nice to be able to clear a table without deallocating it
  1350. void clear() {
  1351. GroupsIterator group;
  1352. for ( group = groups.begin(); group != groups.end(); ++group ) {
  1353. group->clear();
  1354. }
  1355. settings.num_buckets = 0;
  1356. }
  1357. // ACCESSOR FUNCTIONS for the things we templatize on, basically
  1358. allocator_type get_allocator() const {
  1359. return allocator_type(settings);
  1360. }
  1361. // Functions that tell you about size.
  1362. // NOTE: empty() is non-intuitive! It does not tell you the number
  1363. // of not-empty buckets (use num_nonempty() for that). Instead
  1364. // it says whether you've allocated any buckets or not.
  1365. size_type size() const { return settings.table_size; }
  1366. size_type max_size() const { return settings.max_size(); }
  1367. bool empty() const { return settings.table_size == 0; }
  1368. // We also may want to know how many *used* buckets there are
  1369. size_type num_nonempty() const { return settings.num_buckets; }
  1370. // OK, we'll let you resize one of these puppies
  1371. void resize(size_type new_size) {
  1372. groups.resize(num_groups(new_size), group_type(settings));
  1373. if ( new_size < settings.table_size) {
  1374. // lower num_buckets, clear last group
  1375. if ( pos_in_group(new_size) > 0 ) // need to clear inside last group
  1376. groups.back().erase(groups.back().begin() + pos_in_group(new_size),
  1377. groups.back().end());
  1378. settings.num_buckets = 0; // refigure # of used buckets
  1379. GroupsConstIterator group;
  1380. for ( group = groups.begin(); group != groups.end(); ++group )
  1381. settings.num_buckets += group->num_nonempty();
  1382. }
  1383. settings.table_size = new_size;
  1384. }
  1385. // We let you see if a bucket is non-empty without retrieving it
  1386. bool test(size_type i) const {
  1387. assert(i < settings.table_size);
  1388. return which_group(i).test(pos_in_group(i));
  1389. }
  1390. bool test(iterator pos) const {
  1391. return which_group(pos.pos).test(pos_in_group(pos.pos));
  1392. }
  1393. bool test(const_iterator pos) const {
  1394. return which_group(pos.pos).test(pos_in_group(pos.pos));
  1395. }
  1396. // We only return const_references because it's really hard to
  1397. // return something settable for empty buckets. Use set() instead.
  1398. const_reference get(size_type i) const {
  1399. assert(i < settings.table_size);
  1400. return which_group(i).get(pos_in_group(i));
  1401. }
  1402. // TODO(csilvers): make protected + friend
  1403. // This is used by sparse_hashtable to get an element from the table
  1404. // when we know it exists (because the caller has called test(i)).
  1405. const_reference unsafe_get(size_type i) const {
  1406. assert(i < settings.table_size);
  1407. assert(test(i));
  1408. return which_group(i).unsafe_get(pos_in_group(i));
  1409. }
  1410. // TODO(csilvers): make protected + friend element_adaptor
  1411. reference mutating_get(size_type i) { // fills bucket i before getting
  1412. assert(i < settings.table_size);
  1413. typename group_type::size_type old_numbuckets = which_group(i).num_nonempty();
  1414. reference retval = which_group(i).mutating_get(pos_in_group(i));
  1415. settings.num_buckets += which_group(i).num_nonempty() - old_numbuckets;
  1416. return retval;
  1417. }
  1418. // Syntactic sugar. As in sparsegroup, the non-const version is harder
  1419. const_reference operator[](size_type i) const {
  1420. return get(i);
  1421. }
  1422. element_adaptor operator[](size_type i) {
  1423. return element_adaptor(this, i);
  1424. }
  1425. // Needed for hashtables, gets as a nonempty_iterator. Crashes for empty bcks
  1426. const_nonempty_iterator get_iter(size_type i) const {
  1427. assert(test(i)); // how can a nonempty_iterator point to an empty bucket?
  1428. return const_nonempty_iterator(
  1429. groups.begin(), groups.end(),
  1430. groups.begin() + group_num(i),
  1431. (groups[group_num(i)].nonempty_begin() +
  1432. groups[group_num(i)].pos_to_offset(pos_in_group(i))));
  1433. }
  1434. // For nonempty we can return a non-const version
  1435. nonempty_iterator get_iter(size_type i) {
  1436. assert(test(i)); // how can a nonempty_iterator point to an empty bucket?
  1437. return nonempty_iterator(
  1438. groups.begin(), groups.end(),
  1439. groups.begin() + group_num(i),
  1440. (groups[group_num(i)].nonempty_begin() +
  1441. groups[group_num(i)].pos_to_offset(pos_in_group(i))));
  1442. }
  1443. // And the reverse transformation.
  1444. size_type get_pos(const const_nonempty_iterator& it) const {
  1445. difference_type current_row = it.row_current - it.row_begin;
  1446. difference_type current_col = (it.col_current -
  1447. groups[current_row].nonempty_begin());
  1448. return ((current_row * GROUP_SIZE) +
  1449. groups[current_row].offset_to_pos(current_col));
  1450. }
  1451. // This returns a reference to the inserted item (which is a copy of val)
  1452. // The trick is to figure out whether we're replacing or inserting anew
  1453. reference set(size_type i, const_reference val) {
  1454. assert(i < settings.table_size);
  1455. typename group_type::size_type old_numbuckets = which_group(i).num_nonempty();
  1456. reference retval = which_group(i).set(pos_in_group(i), val);
  1457. settings.num_buckets += which_group(i).num_nonempty() - old_numbuckets;
  1458. return retval;
  1459. }
  1460. // This takes the specified elements out of the table. This is
  1461. // "undefining", rather than "clearing".
  1462. void erase(size_type i) {
  1463. assert(i < settings.table_size);
  1464. typename group_type::size_type old_numbuckets = which_group(i).num_nonempty();
  1465. which_group(i).erase(pos_in_group(i));
  1466. settings.num_buckets += which_group(i).num_nonempty() - old_numbuckets;
  1467. }
  1468. void erase(iterator pos) {
  1469. erase(pos.pos);
  1470. }
  1471. void erase(iterator start_it, iterator end_it) {
  1472. // This could be more efficient, but then we'd need to figure
  1473. // out if we spanned groups or not. Doesn't seem worth it.
  1474. for ( ; start_it != end_it; ++start_it )
  1475. erase(start_it);
  1476. }
  1477. // We support reading and writing tables to disk. We don't store
  1478. // the actual array contents (which we don't know how to store),
  1479. // just the groups and sizes. Returns true if all went ok.
  1480. private:
  1481. // Every time the disk format changes, this should probably change too
  1482. typedef unsigned long MagicNumberType;
  1483. static const MagicNumberType MAGIC_NUMBER = 0x24687531;
  1484. // Old versions of this code write all data in 32 bits. We need to
  1485. // support these files as well as having support for 64-bit systems.
  1486. // So we use the following encoding scheme: for values < 2^32-1, we
  1487. // store in 4 bytes in big-endian order. For values > 2^32, we
  1488. // store 0xFFFFFFF followed by 8 bytes in big-endian order. This
  1489. // causes us to mis-read old-version code that stores exactly
  1490. // 0xFFFFFFF, but I don't think that is likely to have happened for
  1491. // these particular values.
  1492. template <typename OUTPUT, typename IntType>
  1493. static bool write_32_or_64(OUTPUT* fp, IntType value) {
  1494. if ( value < 0xFFFFFFFFULL ) { // fits in 4 bytes
  1495. if ( !sparsehash_internal::write_bigendian_number(fp, value, 4) )
  1496. return false;
  1497. } else {
  1498. if ( !sparsehash_internal::write_bigendian_number(fp, 0xFFFFFFFFUL, 4) )
  1499. return false;
  1500. if ( !sparsehash_internal::write_bigendian_number(fp, value, 8) )
  1501. return false;
  1502. }
  1503. return true;
  1504. }
  1505. template <typename INPUT, typename IntType>
  1506. static bool read_32_or_64(INPUT* fp, IntType *value) { // reads into value
  1507. MagicNumberType first4 = 0; // a convenient 32-bit unsigned type
  1508. if ( !sparsehash_internal::read_bigendian_number(fp, &first4, 4) )
  1509. return false;
  1510. if ( first4 < 0xFFFFFFFFULL ) {
  1511. *value = first4;
  1512. } else {
  1513. if ( !sparsehash_internal::read_bigendian_number(fp, value, 8) )
  1514. return false;
  1515. }
  1516. return true;
  1517. }
  1518. public:
  1519. // read/write_metadata() and read_write/nopointer_data() are DEPRECATED.
  1520. // Use serialize() and unserialize(), below, for new code.
  1521. template <typename OUTPUT> bool write_metadata(OUTPUT *fp) const {
  1522. if ( !write_32_or_64(fp, MAGIC_NUMBER) ) return false;
  1523. if ( !write_32_or_64(fp, settings.table_size) ) return false;
  1524. if ( !write_32_or_64(fp, settings.num_buckets) ) return false;
  1525. GroupsConstIterator group;
  1526. for ( group = groups.begin(); group != groups.end(); ++group )
  1527. if ( group->write_metadata(fp) == false ) return false;
  1528. return true;
  1529. }
  1530. // Reading destroys the old table contents! Returns true if read ok.
  1531. template <typename INPUT> bool read_metadata(INPUT *fp) {
  1532. size_type magic_read = 0;
  1533. if ( !read_32_or_64(fp, &magic_read) ) return false;
  1534. if ( magic_read != MAGIC_NUMBER ) {
  1535. clear(); // just to be consistent
  1536. return false;
  1537. }
  1538. if ( !read_32_or_64(fp, &settings.table_size) ) return false;
  1539. if ( !read_32_or_64(fp, &settings.num_buckets) ) return false;
  1540. resize(settings.table_size); // so the vector's sized ok
  1541. GroupsIterator group;
  1542. for ( group = groups.begin(); group != groups.end(); ++group )
  1543. if ( group->read_metadata(fp) == false ) return false;
  1544. return true;
  1545. }
  1546. // This code is identical to that for SparseGroup
  1547. // If your keys and values are simple enough, we can write them
  1548. // to disk for you. "simple enough" means no pointers.
  1549. // However, we don't try to normalize endianness
  1550. bool write_nopointer_data(FILE *fp) const {
  1551. for ( const_nonempty_iterator it = nonempty_begin();
  1552. it != nonempty_end(); ++it ) {
  1553. if ( !fwrite(&*it, sizeof(*it), 1, fp) ) return false;
  1554. }
  1555. return true;
  1556. }
  1557. // When reading, we have to override the potential const-ness of *it
  1558. bool read_nopointer_data(FILE *fp) {
  1559. for ( nonempty_iterator it = nonempty_begin();
  1560. it != nonempty_end(); ++it ) {
  1561. if ( !fread(reinterpret_cast<void*>(&(*it)), sizeof(*it), 1, fp) )
  1562. return false;
  1563. }
  1564. return true;
  1565. }
  1566. // INPUT and OUTPUT must be either a FILE, *or* a C++ stream
  1567. // (istream, ostream, etc) *or* a class providing
  1568. // Read(void*, size_t) and Write(const void*, size_t)
  1569. // (respectively), which writes a buffer into a stream
  1570. // (which the INPUT/OUTPUT instance presumably owns).
  1571. typedef sparsehash_internal::pod_serializer<value_type> NopointerSerializer;
  1572. // ValueSerializer: a functor. operator()(OUTPUT*, const value_type&)
  1573. template <typename ValueSerializer, typename OUTPUT>
  1574. bool serialize(ValueSerializer serializer, OUTPUT *fp) {
  1575. if ( !write_metadata(fp) )
  1576. return false;
  1577. for ( const_nonempty_iterator it = nonempty_begin();
  1578. it != nonempty_end(); ++it ) {
  1579. if ( !serializer(fp, *it) ) return false;
  1580. }
  1581. return true;
  1582. }
  1583. // ValueSerializer: a functor. operator()(INPUT*, value_type*)
  1584. template <typename ValueSerializer, typename INPUT>
  1585. bool unserialize(ValueSerializer serializer, INPUT *fp) {
  1586. clear();
  1587. if ( !read_metadata(fp) )
  1588. return false;
  1589. for ( nonempty_iterator it = nonempty_begin();
  1590. it != nonempty_end(); ++it ) {
  1591. if ( !serializer(fp, &*it) ) return false;
  1592. }
  1593. return true;
  1594. }
  1595. // Comparisons. Note the comparisons are pretty arbitrary: we
  1596. // compare values of the first index that isn't equal (using default
  1597. // value for empty buckets).
  1598. bool operator==(const sparsetable& x) const {
  1599. return ( settings.table_size == x.settings.table_size &&
  1600. settings.num_buckets == x.settings.num_buckets &&
  1601. groups == x.groups );
  1602. }
  1603. bool operator<(const sparsetable& x) const {
  1604. return std::lexicographical_compare(begin(), end(), x.begin(), x.end());
  1605. }
  1606. bool operator!=(const sparsetable& x) const { return !(*this == x); }
  1607. bool operator<=(const sparsetable& x) const { return !(x < *this); }
  1608. bool operator>(const sparsetable& x) const { return x < *this; }
  1609. bool operator>=(const sparsetable& x) const { return !(*this < x); }
  1610. private:
  1611. // Package allocator with table_size and num_buckets to eliminate memory
  1612. // needed for the zero-size allocator.
  1613. // If new fields are added to this class, we should add them to
  1614. // operator= and swap.
  1615. class Settings : public allocator_type {
  1616. public:
  1617. typedef typename allocator_type::size_type size_type;
  1618. Settings(const allocator_type& a, size_type sz = 0, size_type n = 0)
  1619. : allocator_type(a), table_size(sz), num_buckets(n) { }
  1620. Settings(const Settings& s)
  1621. : allocator_type(s),
  1622. table_size(s.table_size), num_buckets(s.num_buckets) { }
  1623. size_type table_size; // how many buckets they want
  1624. size_type num_buckets; // number of non-empty buckets
  1625. };
  1626. // The actual data
  1627. group_vector_type groups; // our list of groups
  1628. Settings settings; // allocator, table size, buckets
  1629. };
  1630. // We need a global swap as well
  1631. template <class T, u_int16_t GROUP_SIZE, class Alloc>
  1632. inline void swap(sparsetable<T,GROUP_SIZE,Alloc> &x,
  1633. sparsetable<T,GROUP_SIZE,Alloc> &y) {
  1634. x.swap(y);
  1635. }
  1636. _END_GOOGLE_NAMESPACE_
  1637. #endif // UTIL_GTL_SPARSETABLE_H_