tables.nim 98 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## The ``tables`` module implements variants of an efficient `hash table`:idx:
  10. ## (also often named `dictionary`:idx: in other programming languages) that is
  11. ## a mapping from keys to values.
  12. ##
  13. ## There are several different types of hash tables available:
  14. ## * `Table<#Table>`_ is the usual hash table,
  15. ## * `OrderedTable<#OrderedTable>`_ is like ``Table`` but remembers insertion order,
  16. ## * `CountTable<#CountTable>`_ is a mapping from a key to its number of occurrences
  17. ##
  18. ## For consistency with every other data type in Nim these have **value**
  19. ## semantics, this means that ``=`` performs a copy of the hash table.
  20. ##
  21. ## For `ref semantics<manual.html#types-reference-and-pointer-types>`_
  22. ## use their ``Ref`` variants: `TableRef<#TableRef>`_,
  23. ## `OrderedTableRef<#OrderedTableRef>`_, and `CountTableRef<#CountTableRef>`_.
  24. ##
  25. ## To give an example, when ``a`` is a ``Table``, then ``var b = a`` gives ``b``
  26. ## as a new independent table. ``b`` is initialised with the contents of ``a``.
  27. ## Changing ``b`` does not affect ``a`` and vice versa:
  28. ##
  29. ## .. code-block::
  30. ## import tables
  31. ##
  32. ## var
  33. ## a = {1: "one", 2: "two"}.toTable # creates a Table
  34. ## b = a
  35. ##
  36. ## echo a, b # output: {1: one, 2: two}{1: one, 2: two}
  37. ##
  38. ## b[3] = "three"
  39. ## echo a, b # output: {1: one, 2: two}{1: one, 2: two, 3: three}
  40. ## echo a == b # output: false
  41. ##
  42. ## On the other hand, when ``a`` is a ``TableRef`` instead, then changes to ``b``
  43. ## also affect ``a``. Both ``a`` and ``b`` **ref** the same data structure:
  44. ##
  45. ## .. code-block::
  46. ## import tables
  47. ##
  48. ## var
  49. ## a = {1: "one", 2: "two"}.newTable # creates a TableRef
  50. ## b = a
  51. ##
  52. ## echo a, b # output: {1: one, 2: two}{1: one, 2: two}
  53. ##
  54. ## b[3] = "three"
  55. ## echo a, b # output: {1: one, 2: two, 3: three}{1: one, 2: two, 3: three}
  56. ## echo a == b # output: true
  57. ##
  58. ## ----
  59. ##
  60. ## Basic usage
  61. ## ===========
  62. ##
  63. ## Table
  64. ## -----
  65. ##
  66. ## .. code-block::
  67. ## import tables
  68. ## from sequtils import zip
  69. ##
  70. ## let
  71. ## names = ["John", "Paul", "George", "Ringo"]
  72. ## years = [1940, 1942, 1943, 1940]
  73. ##
  74. ## var beatles = initTable[string, int]()
  75. ##
  76. ## for pairs in zip(names, years):
  77. ## let (name, birthYear) = pairs
  78. ## beatles[name] = birthYear
  79. ##
  80. ## echo beatles
  81. ## # {"George": 1943, "Ringo": 1940, "Paul": 1942, "John": 1940}
  82. ##
  83. ##
  84. ## var beatlesByYear = initTable[int, seq[string]]()
  85. ##
  86. ## for pairs in zip(years, names):
  87. ## let (birthYear, name) = pairs
  88. ## if not beatlesByYear.hasKey(birthYear):
  89. ## # if a key doesn't exist, we create one with an empty sequence
  90. ## # before we can add elements to it
  91. ## beatlesByYear[birthYear] = @[]
  92. ## beatlesByYear[birthYear].add(name)
  93. ##
  94. ## echo beatlesByYear
  95. ## # {1940: @["John", "Ringo"], 1942: @["Paul"], 1943: @["George"]}
  96. ##
  97. ##
  98. ##
  99. ## OrderedTable
  100. ## ------------
  101. ##
  102. ## `OrderedTable<#OrderedTable>`_ is used when it is important to preserve
  103. ## the insertion order of keys.
  104. ##
  105. ## .. code-block::
  106. ## import tables
  107. ##
  108. ## let
  109. ## a = [('z', 1), ('y', 2), ('x', 3)]
  110. ## t = a.toTable # regular table
  111. ## ot = a.toOrderedTable # ordered tables
  112. ##
  113. ## echo t # {'x': 3, 'y': 2, 'z': 1}
  114. ## echo ot # {'z': 1, 'y': 2, 'x': 3}
  115. ##
  116. ##
  117. ##
  118. ## CountTable
  119. ## ----------
  120. ##
  121. ## `CountTable<#CountTable>`_ is useful for counting number of items of some
  122. ## container (e.g. string, sequence or array), as it is a mapping where the
  123. ## items are the keys, and their number of occurrences are the values.
  124. ## For that purpose `toCountTable proc<#toCountTable,openArray[A]>`_
  125. ## comes handy:
  126. ##
  127. ## .. code-block::
  128. ## import tables
  129. ##
  130. ## let myString = "abracadabra"
  131. ## let letterFrequencies = toCountTable(myString)
  132. ## echo letterFrequencies
  133. ## # 'a': 5, 'b': 2, 'c': 1, 'd': 1, 'r': 2}
  134. ##
  135. ## The same could have been achieved by manually iterating over a container
  136. ## and increasing each key's value with `inc proc
  137. ## <#inc,CountTable[A],A,Positive>`_:
  138. ##
  139. ## .. code-block::
  140. ## import tables
  141. ##
  142. ## let myString = "abracadabra"
  143. ## var letterFrequencies = initCountTable[char]()
  144. ## for c in myString:
  145. ## letterFrequencies.inc(c)
  146. ## echo letterFrequencies
  147. ## # output: {'a': 5, 'b': 2, 'c': 1, 'd': 1, 'r': 2}
  148. ##
  149. ## ----
  150. ##
  151. ##
  152. ##
  153. ## Hashing
  154. ## -------
  155. ##
  156. ## If you are using simple standard types like ``int`` or ``string`` for the
  157. ## keys of the table you won't have any problems, but as soon as you try to use
  158. ## a more complex object as a key you will be greeted by a strange compiler
  159. ## error:
  160. ##
  161. ## Error: type mismatch: got (Person)
  162. ## but expected one of:
  163. ## hashes.hash(x: openArray[A]): Hash
  164. ## hashes.hash(x: int): Hash
  165. ## hashes.hash(x: float): Hash
  166. ## …
  167. ##
  168. ## What is happening here is that the types used for table keys require to have
  169. ## a ``hash()`` proc which will convert them to a `Hash <hashes.html#Hash>`_
  170. ## value, and the compiler is listing all the hash functions it knows.
  171. ## Additionally there has to be a ``==`` operator that provides the same
  172. ## semantics as its corresponding ``hash`` proc.
  173. ##
  174. ## After you add ``hash`` and ``==`` for your custom type everything will work.
  175. ## Currently, however, ``hash`` for objects is not defined, whereas
  176. ## ``system.==`` for objects does exist and performs a "deep" comparison (every
  177. ## field is compared) which is usually what you want. So in the following
  178. ## example implementing only ``hash`` suffices:
  179. ##
  180. ## .. code-block::
  181. ## import tables, hashes
  182. ##
  183. ## type
  184. ## Person = object
  185. ## firstName, lastName: string
  186. ##
  187. ## proc hash(x: Person): Hash =
  188. ## ## Piggyback on the already available string hash proc.
  189. ## ##
  190. ## ## Without this proc nothing works!
  191. ## result = x.firstName.hash !& x.lastName.hash
  192. ## result = !$result
  193. ##
  194. ## var
  195. ## salaries = initTable[Person, int]()
  196. ## p1, p2: Person
  197. ##
  198. ## p1.firstName = "Jon"
  199. ## p1.lastName = "Ross"
  200. ## salaries[p1] = 30_000
  201. ##
  202. ## p2.firstName = "소진"
  203. ## p2.lastName = "박"
  204. ## salaries[p2] = 45_000
  205. ##
  206. ## ----
  207. ##
  208. ## See also
  209. ## ========
  210. ##
  211. ## * `json module<json.html>`_ for table-like structure which allows
  212. ## heterogeneous members
  213. ## * `sharedtables module<sharedtables.html>`_ for shared hash table support
  214. ## * `strtabs module<strtabs.html>`_ for efficient hash tables
  215. ## mapping from strings to strings
  216. ## * `hashes module<hashes.html>`_ for helper functions for hashing
  217. import hashes, math, algorithm
  218. include "system/inclrtl"
  219. type
  220. KeyValuePair[A, B] = tuple[hcode: Hash, key: A, val: B]
  221. KeyValuePairSeq[A, B] = seq[KeyValuePair[A, B]]
  222. Table*[A, B] = object
  223. ## Generic hash table, consisting of a key-value pair.
  224. ##
  225. ## `data` and `counter` are internal implementation details which
  226. ## can't be accessed.
  227. ##
  228. ## For creating an empty Table, use `initTable proc<#initTable,int>`_.
  229. data: KeyValuePairSeq[A, B]
  230. counter: int
  231. TableRef*[A, B] = ref Table[A, B] ## Ref version of `Table<#Table>`_.
  232. ##
  233. ## For creating a new empty TableRef, use `newTable proc
  234. ## <#newTable,int>`_.
  235. const
  236. defaultInitialSize* = 64
  237. # ------------------------------ helpers ---------------------------------
  238. # Do NOT move these to tableimpl.nim, because sharedtables uses that
  239. # file and has its own implementation.
  240. template maxHash(t): untyped = high(t.data)
  241. template dataLen(t): untyped = len(t.data)
  242. include tableimpl
  243. proc rightSize*(count: Natural): int {.inline.}
  244. template get(t, key): untyped =
  245. ## retrieves the value at ``t[key]``. The value can be modified.
  246. ## If ``key`` is not in ``t``, the ``KeyError`` exception is raised.
  247. mixin rawGet
  248. var hc: Hash
  249. var index = rawGet(t, key, hc)
  250. if index >= 0: result = t.data[index].val
  251. else:
  252. when compiles($key):
  253. raise newException(KeyError, "key not found: " & $key)
  254. else:
  255. raise newException(KeyError, "key not found")
  256. proc enlarge[A, B](t: var Table[A, B]) =
  257. var n: KeyValuePairSeq[A, B]
  258. newSeq(n, len(t.data) * growthFactor)
  259. swap(t.data, n)
  260. for i in countup(0, high(n)):
  261. let eh = n[i].hcode
  262. if isFilled(eh):
  263. var j: Hash = eh and maxHash(t)
  264. while isFilled(t.data[j].hcode):
  265. j = nextTry(j, maxHash(t))
  266. when defined(js):
  267. rawInsert(t, t.data, n[i].key, n[i].val, eh, j)
  268. else:
  269. rawInsert(t, t.data, move n[i].key, move n[i].val, eh, j)
  270. # -------------------------------------------------------------------
  271. # ------------------------------ Table ------------------------------
  272. # -------------------------------------------------------------------
  273. proc initTable*[A, B](initialSize = defaultInitialSize): Table[A, B] =
  274. ## Creates a new hash table that is empty.
  275. ##
  276. ## ``initialSize`` must be a power of two (default: 64).
  277. ## If you need to accept runtime values for this you could use the
  278. ## `nextPowerOfTwo proc<math.html#nextPowerOfTwo,int>`_ from the
  279. ## `math module<math.html>`_ or the `rightSize proc<#rightSize,Natural>`_
  280. ## from this module.
  281. ##
  282. ## Starting from Nim v0.20, tables are initialized by default and it is
  283. ## not necessary to call this function explicitly.
  284. ##
  285. ## See also:
  286. ## * `toTable proc<#toTable,openArray[]>`_
  287. ## * `newTable proc<#newTable,int>`_ for creating a `TableRef`
  288. runnableExamples:
  289. let
  290. a = initTable[int, string]()
  291. b = initTable[char, seq[int]]()
  292. initImpl(result, initialSize)
  293. proc `[]=`*[A, B](t: var Table[A, B], key: A, val: B) =
  294. ## Inserts a ``(key, value)`` pair into ``t``.
  295. ##
  296. ## See also:
  297. ## * `[] proc<#[],Table[A,B],A>`_ for retrieving a value of a key
  298. ## * `hasKeyOrPut proc<#hasKeyOrPut,Table[A,B],A,B>`_
  299. ## * `mgetOrPut proc<#mgetOrPut,Table[A,B],A,B>`_
  300. ## * `del proc<#del,Table[A,B],A>`_ for removing a key from the table
  301. runnableExamples:
  302. var a = initTable[char, int]()
  303. a['x'] = 7
  304. a['y'] = 33
  305. doAssert a == {'x': 7, 'y': 33}.toTable
  306. putImpl(enlarge)
  307. proc toTable*[A, B](pairs: openArray[(A, B)]): Table[A, B] =
  308. ## Creates a new hash table that contains the given ``pairs``.
  309. ##
  310. ## ``pairs`` is a container consisting of ``(key, value)`` tuples.
  311. ##
  312. ## See also:
  313. ## * `initTable proc<#initTable,int>`_
  314. ## * `newTable proc<#newTable,openArray[]>`_ for a `TableRef` version
  315. runnableExamples:
  316. let a = [('a', 5), ('b', 9)]
  317. let b = toTable(a)
  318. assert b == {'a': 5, 'b': 9}.toTable
  319. result = initTable[A, B](rightSize(pairs.len))
  320. for key, val in items(pairs): result[key] = val
  321. proc `[]`*[A, B](t: Table[A, B], key: A): B =
  322. ## Retrieves the value at ``t[key]``.
  323. ##
  324. ## If ``key`` is not in ``t``, the ``KeyError`` exception is raised.
  325. ## One can check with `hasKey proc<#hasKey,Table[A,B],A>`_ whether
  326. ## the key exists.
  327. ##
  328. ## See also:
  329. ## * `getOrDefault proc<#getOrDefault,Table[A,B],A>`_ to return
  330. ## a default value (e.g. zero for int) if the key doesn't exist
  331. ## * `getOrDefault proc<#getOrDefault,Table[A,B],A,B>`_ to return
  332. ## a custom value if the key doesn't exist
  333. ## * `[]= proc<#[]=,Table[A,B],A,B>`_ for inserting a new
  334. ## (key, value) pair in the table
  335. ## * `hasKey proc<#hasKey,Table[A,B],A>`_ for checking if a key is in
  336. ## the table
  337. runnableExamples:
  338. let a = {'a': 5, 'b': 9}.toTable
  339. doAssert a['a'] == 5
  340. doAssertRaises(KeyError):
  341. echo a['z']
  342. get(t, key)
  343. proc `[]`*[A, B](t: var Table[A, B], key: A): var B =
  344. ## Retrieves the value at ``t[key]``. The value can be modified.
  345. ##
  346. ## If ``key`` is not in ``t``, the ``KeyError`` exception is raised.
  347. ##
  348. ## See also:
  349. ## * `getOrDefault proc<#getOrDefault,Table[A,B],A>`_ to return
  350. ## a default value (e.g. zero for int) if the key doesn't exist
  351. ## * `getOrDefault proc<#getOrDefault,Table[A,B],A,B>`_ to return
  352. ## a custom value if the key doesn't exist
  353. ## * `[]= proc<#[]=,Table[A,B],A,B>`_ for inserting a new
  354. ## (key, value) pair in the table
  355. ## * `hasKey proc<#hasKey,Table[A,B],A>`_ for checking if a key is in
  356. ## the table
  357. get(t, key)
  358. proc hasKey*[A, B](t: Table[A, B], key: A): bool =
  359. ## Returns true if ``key`` is in the table ``t``.
  360. ##
  361. ## See also:
  362. ## * `contains proc<#contains,Table[A,B],A>`_ for use with the `in` operator
  363. ## * `[] proc<#[],Table[A,B],A>`_ for retrieving a value of a key
  364. ## * `getOrDefault proc<#getOrDefault,Table[A,B],A>`_ to return
  365. ## a default value (e.g. zero for int) if the key doesn't exist
  366. ## * `getOrDefault proc<#getOrDefault,Table[A,B],A,B>`_ to return
  367. ## a custom value if the key doesn't exist
  368. runnableExamples:
  369. let a = {'a': 5, 'b': 9}.toTable
  370. doAssert a.hasKey('a') == true
  371. doAssert a.hasKey('z') == false
  372. var hc: Hash
  373. result = rawGet(t, key, hc) >= 0
  374. proc contains*[A, B](t: Table[A, B], key: A): bool =
  375. ## Alias of `hasKey proc<#hasKey,Table[A,B],A>`_ for use with
  376. ## the ``in`` operator.
  377. runnableExamples:
  378. let a = {'a': 5, 'b': 9}.toTable
  379. doAssert 'b' in a == true
  380. doAssert a.contains('z') == false
  381. return hasKey[A, B](t, key)
  382. proc hasKeyOrPut*[A, B](t: var Table[A, B], key: A, val: B): bool =
  383. ## Returns true if ``key`` is in the table, otherwise inserts ``value``.
  384. ##
  385. ## See also:
  386. ## * `hasKey proc<#hasKey,Table[A,B],A>`_
  387. ## * `[] proc<#[],Table[A,B],A>`_ for retrieving a value of a key
  388. ## * `getOrDefault proc<#getOrDefault,Table[A,B],A>`_ to return
  389. ## a default value (e.g. zero for int) if the key doesn't exist
  390. ## * `getOrDefault proc<#getOrDefault,Table[A,B],A,B>`_ to return
  391. ## a custom value if the key doesn't exist
  392. runnableExamples:
  393. var a = {'a': 5, 'b': 9}.toTable
  394. if a.hasKeyOrPut('a', 50):
  395. a['a'] = 99
  396. if a.hasKeyOrPut('z', 50):
  397. a['z'] = 99
  398. doAssert a == {'a': 99, 'b': 9, 'z': 50}.toTable
  399. hasKeyOrPutImpl(enlarge)
  400. proc getOrDefault*[A, B](t: Table[A, B], key: A): B =
  401. ## Retrieves the value at ``t[key]`` if ``key`` is in ``t``. Otherwise, the
  402. ## default initialization value for type ``B`` is returned (e.g. 0 for any
  403. ## integer type).
  404. ##
  405. ## See also:
  406. ## * `[] proc<#[],Table[A,B],A>`_ for retrieving a value of a key
  407. ## * `hasKey proc<#hasKey,Table[A,B],A>`_
  408. ## * `hasKeyOrPut proc<#hasKeyOrPut,Table[A,B],A,B>`_
  409. ## * `mgetOrPut proc<#mgetOrPut,Table[A,B],A,B>`_
  410. ## * `getOrDefault proc<#getOrDefault,Table[A,B],A,B>`_ to return
  411. ## a custom value if the key doesn't exist
  412. runnableExamples:
  413. let a = {'a': 5, 'b': 9}.toTable
  414. doAssert a.getOrDefault('a') == 5
  415. doAssert a.getOrDefault('z') == 0
  416. getOrDefaultImpl(t, key)
  417. proc getOrDefault*[A, B](t: Table[A, B], key: A, default: B): B =
  418. ## Retrieves the value at ``t[key]`` if ``key`` is in ``t``.
  419. ## Otherwise, ``default`` is returned.
  420. ##
  421. ## See also:
  422. ## * `[] proc<#[],Table[A,B],A>`_ for retrieving a value of a key
  423. ## * `hasKey proc<#hasKey,Table[A,B],A>`_
  424. ## * `hasKeyOrPut proc<#hasKeyOrPut,Table[A,B],A,B>`_
  425. ## * `mgetOrPut proc<#mgetOrPut,Table[A,B],A,B>`_
  426. ## * `getOrDefault proc<#getOrDefault,Table[A,B],A>`_ to return
  427. ## a default value (e.g. zero for int) if the key doesn't exist
  428. runnableExamples:
  429. let a = {'a': 5, 'b': 9}.toTable
  430. doAssert a.getOrDefault('a', 99) == 5
  431. doAssert a.getOrDefault('z', 99) == 99
  432. getOrDefaultImpl(t, key, default)
  433. proc mgetOrPut*[A, B](t: var Table[A, B], key: A, val: B): var B =
  434. ## Retrieves value at ``t[key]`` or puts ``val`` if not present, either way
  435. ## returning a value which can be modified.
  436. ##
  437. ## See also:
  438. ## * `[] proc<#[],Table[A,B],A>`_ for retrieving a value of a key
  439. ## * `hasKey proc<#hasKey,Table[A,B],A>`_
  440. ## * `hasKeyOrPut proc<#hasKeyOrPut,Table[A,B],A,B>`_
  441. ## * `getOrDefault proc<#getOrDefault,Table[A,B],A>`_ to return
  442. ## a default value (e.g. zero for int) if the key doesn't exist
  443. ## * `getOrDefault proc<#getOrDefault,Table[A,B],A,B>`_ to return
  444. ## a custom value if the key doesn't exist
  445. runnableExamples:
  446. var a = {'a': 5, 'b': 9}.toTable
  447. doAssert a.mgetOrPut('a', 99) == 5
  448. doAssert a.mgetOrPut('z', 99) == 99
  449. doAssert a == {'a': 5, 'b': 9, 'z': 99}.toTable
  450. mgetOrPutImpl(enlarge)
  451. proc len*[A, B](t: Table[A, B]): int =
  452. ## Returns the number of keys in ``t``.
  453. runnableExamples:
  454. let a = {'a': 5, 'b': 9}.toTable
  455. doAssert len(a) == 2
  456. result = t.counter
  457. proc add*[A, B](t: var Table[A, B], key: A, val: B) =
  458. ## Puts a new ``(key, value)`` pair into ``t`` even if ``t[key]`` already exists.
  459. ##
  460. ## **This can introduce duplicate keys into the table!**
  461. ##
  462. ## Use `[]= proc<#[]=,Table[A,B],A,B>`_ for inserting a new
  463. ## (key, value) pair in the table without introducing duplicates.
  464. addImpl(enlarge)
  465. proc del*[A, B](t: var Table[A, B], key: A) =
  466. ## Deletes ``key`` from hash table ``t``. Does nothing if the key does not exist.
  467. ##
  468. ## See also:
  469. ## * `take proc<#take,Table[A,B],A,B>`_
  470. ## * `clear proc<#clear,Table[A,B]>`_ to empty the whole table
  471. runnableExamples:
  472. var a = {'a': 5, 'b': 9, 'c': 13}.toTable
  473. a.del('a')
  474. doAssert a == {'b': 9, 'c': 13}.toTable
  475. a.del('z')
  476. doAssert a == {'b': 9, 'c': 13}.toTable
  477. delImpl()
  478. proc take*[A, B](t: var Table[A, B], key: A, val: var B): bool =
  479. ## Deletes the ``key`` from the table.
  480. ## Returns ``true``, if the ``key`` existed, and sets ``val`` to the
  481. ## mapping of the key. Otherwise, returns ``false``, and the ``val`` is
  482. ## unchanged.
  483. ##
  484. ## See also:
  485. ## * `del proc<#del,Table[A,B],A>`_
  486. ## * `clear proc<#clear,Table[A,B]>`_ to empty the whole table
  487. runnableExamples:
  488. var
  489. a = {'a': 5, 'b': 9, 'c': 13}.toTable
  490. i: int
  491. doAssert a.take('b', i) == true
  492. doAssert a == {'a': 5, 'c': 13}.toTable
  493. doAssert i == 9
  494. i = 0
  495. doAssert a.take('z', i) == false
  496. doAssert a == {'a': 5, 'c': 13}.toTable
  497. doAssert i == 0
  498. var hc: Hash
  499. var index = rawGet(t, key, hc)
  500. result = index >= 0
  501. if result:
  502. shallowCopy(val, t.data[index].val)
  503. delImplIdx(t, index)
  504. proc clear*[A, B](t: var Table[A, B]) =
  505. ## Resets the table so that it is empty.
  506. ##
  507. ## See also:
  508. ## * `del proc<#del,Table[A,B],A>`_
  509. ## * `take proc<#take,Table[A,B],A,B>`_
  510. runnableExamples:
  511. var a = {'a': 5, 'b': 9, 'c': 13}.toTable
  512. doAssert len(a) == 3
  513. clear(a)
  514. doAssert len(a) == 0
  515. clearImpl()
  516. proc `$`*[A, B](t: Table[A, B]): string =
  517. ## The ``$`` operator for hash tables. Used internally when calling `echo`
  518. ## on a table.
  519. dollarImpl()
  520. proc `==`*[A, B](s, t: Table[A, B]): bool =
  521. ## The ``==`` operator for hash tables. Returns ``true`` if the content of both
  522. ## tables contains the same key-value pairs. Insert order does not matter.
  523. runnableExamples:
  524. let
  525. a = {'a': 5, 'b': 9, 'c': 13}.toTable
  526. b = {'b': 9, 'c': 13, 'a': 5}.toTable
  527. doAssert a == b
  528. equalsImpl(s, t)
  529. proc rightSize*(count: Natural): int {.inline.} =
  530. ## Return the value of ``initialSize`` to support ``count`` items.
  531. ##
  532. ## If more items are expected to be added, simply add that
  533. ## expected extra amount to the parameter before calling this.
  534. ##
  535. ## Internally, we want mustRehash(rightSize(x), x) == false.
  536. result = nextPowerOfTwo(count * 3 div 2 + 4)
  537. proc indexBy*[A, B, C](collection: A, index: proc(x: B): C): Table[C, B] =
  538. ## Index the collection with the proc provided.
  539. # TODO: As soon as supported, change collection: A to collection: A[B]
  540. result = initTable[C, B]()
  541. for item in collection:
  542. result[index(item)] = item
  543. template withValue*[A, B](t: var Table[A, B], key: A, value, body: untyped) =
  544. ## Retrieves the value at ``t[key]``.
  545. ##
  546. ## ``value`` can be modified in the scope of the ``withValue`` call.
  547. ##
  548. ## .. code-block:: nim
  549. ##
  550. ## sharedTable.withValue(key, value) do:
  551. ## # block is executed only if ``key`` in ``t``
  552. ## value.name = "username"
  553. ## value.uid = 1000
  554. ##
  555. mixin rawGet
  556. var hc: Hash
  557. var index = rawGet(t, key, hc)
  558. let hasKey = index >= 0
  559. if hasKey:
  560. var value {.inject.} = addr(t.data[index].val)
  561. body
  562. template withValue*[A, B](t: var Table[A, B], key: A,
  563. value, body1, body2: untyped) =
  564. ## Retrieves the value at ``t[key]``.
  565. ##
  566. ## ``value`` can be modified in the scope of the ``withValue`` call.
  567. ##
  568. ## .. code-block:: nim
  569. ##
  570. ## table.withValue(key, value) do:
  571. ## # block is executed only if ``key`` in ``t``
  572. ## value.name = "username"
  573. ## value.uid = 1000
  574. ## do:
  575. ## # block is executed when ``key`` not in ``t``
  576. ## raise newException(KeyError, "Key not found")
  577. ##
  578. mixin rawGet
  579. var hc: Hash
  580. var index = rawGet(t, key, hc)
  581. let hasKey = index >= 0
  582. if hasKey:
  583. var value {.inject.} = addr(t.data[index].val)
  584. body1
  585. else:
  586. body2
  587. iterator pairs*[A, B](t: Table[A, B]): (A, B) =
  588. ## Iterates over any ``(key, value)`` pair in the table ``t``.
  589. ##
  590. ## See also:
  591. ## * `mpairs iterator<#mpairs.i,Table[A,B]>`_
  592. ## * `keys iterator<#keys.i,Table[A,B]>`_
  593. ## * `values iterator<#values.i,Table[A,B]>`_
  594. ##
  595. ## **Examples:**
  596. ##
  597. ## .. code-block::
  598. ## let a = {
  599. ## 'o': [1, 5, 7, 9],
  600. ## 'e': [2, 4, 6, 8]
  601. ## }.toTable
  602. ##
  603. ## for k, v in a.pairs:
  604. ## echo "key: ", k
  605. ## echo "value: ", v
  606. ##
  607. ## # key: e
  608. ## # value: [2, 4, 6, 8]
  609. ## # key: o
  610. ## # value: [1, 5, 7, 9]
  611. let L = len(t)
  612. for h in 0 .. high(t.data):
  613. if isFilled(t.data[h].hcode):
  614. yield (t.data[h].key, t.data[h].val)
  615. assert(len(t) == L, "the length of the table changed while iterating over it")
  616. iterator mpairs*[A, B](t: var Table[A, B]): (A, var B) =
  617. ## Iterates over any ``(key, value)`` pair in the table ``t`` (must be
  618. ## declared as `var`). The values can be modified.
  619. ##
  620. ## See also:
  621. ## * `pairs iterator<#pairs.i,Table[A,B]>`_
  622. ## * `mvalues iterator<#mvalues.i,Table[A,B]>`_
  623. runnableExamples:
  624. var a = {
  625. 'o': @[1, 5, 7, 9],
  626. 'e': @[2, 4, 6, 8]
  627. }.toTable
  628. for k, v in a.mpairs:
  629. v.add(v[0] + 10)
  630. doAssert a == {'e': @[2, 4, 6, 8, 12], 'o': @[1, 5, 7, 9, 11]}.toTable
  631. let L = len(t)
  632. for h in 0 .. high(t.data):
  633. if isFilled(t.data[h].hcode):
  634. yield (t.data[h].key, t.data[h].val)
  635. assert(len(t) == L, "the length of the table changed while iterating over it")
  636. iterator keys*[A, B](t: Table[A, B]): A =
  637. ## Iterates over any key in the table ``t``.
  638. ##
  639. ## See also:
  640. ## * `pairs iterator<#pairs.i,Table[A,B]>`_
  641. ## * `values iterator<#values.i,Table[A,B]>`_
  642. runnableExamples:
  643. var a = {
  644. 'o': @[1, 5, 7, 9],
  645. 'e': @[2, 4, 6, 8]
  646. }.toTable
  647. for k in a.keys:
  648. a[k].add(99)
  649. doAssert a == {'e': @[2, 4, 6, 8, 99], 'o': @[1, 5, 7, 9, 99]}.toTable
  650. let L = len(t)
  651. for h in 0 .. high(t.data):
  652. if isFilled(t.data[h].hcode):
  653. yield t.data[h].key
  654. assert(len(t) == L, "the length of the table changed while iterating over it")
  655. iterator values*[A, B](t: Table[A, B]): B =
  656. ## Iterates over any value in the table ``t``.
  657. ##
  658. ## See also:
  659. ## * `pairs iterator<#pairs.i,Table[A,B]>`_
  660. ## * `keys iterator<#keys.i,Table[A,B]>`_
  661. ## * `mvalues iterator<#mvalues.i,Table[A,B]>`_
  662. runnableExamples:
  663. let a = {
  664. 'o': @[1, 5, 7, 9],
  665. 'e': @[2, 4, 6, 8]
  666. }.toTable
  667. for v in a.values:
  668. doAssert v.len == 4
  669. let L = len(t)
  670. for h in 0 .. high(t.data):
  671. if isFilled(t.data[h].hcode):
  672. yield t.data[h].val
  673. assert(len(t) == L, "the length of the table changed while iterating over it")
  674. iterator mvalues*[A, B](t: var Table[A, B]): var B =
  675. ## Iterates over any value in the table ``t`` (must be
  676. ## declared as `var`). The values can be modified.
  677. ##
  678. ## See also:
  679. ## * `mpairs iterator<#mpairs.i,Table[A,B]>`_
  680. ## * `values iterator<#values.i,Table[A,B]>`_
  681. runnableExamples:
  682. var a = {
  683. 'o': @[1, 5, 7, 9],
  684. 'e': @[2, 4, 6, 8]
  685. }.toTable
  686. for v in a.mvalues:
  687. v.add(99)
  688. doAssert a == {'e': @[2, 4, 6, 8, 99], 'o': @[1, 5, 7, 9, 99]}.toTable
  689. let L = len(t)
  690. for h in 0 .. high(t.data):
  691. if isFilled(t.data[h].hcode):
  692. yield t.data[h].val
  693. assert(len(t) == L, "the length of the table changed while iterating over it")
  694. iterator allValues*[A, B](t: Table[A, B]; key: A): B =
  695. ## Iterates over any value in the table ``t`` that belongs to the given ``key``.
  696. ##
  697. ## Used if you have a table with duplicate keys (as a result of using
  698. ## `add proc<#add,Table[A,B],A,B>`_).
  699. ##
  700. ## **Examples:**
  701. ##
  702. ## .. code-block::
  703. ## var a = {'a': 3, 'b': 5}.toTable
  704. ## for i in 1..3:
  705. ## a.add('z', 10*i)
  706. ## echo a # {'a': 3, 'b': 5, 'z': 10, 'z': 20, 'z': 30}
  707. ##
  708. ## for v in a.allValues('z'):
  709. ## echo v
  710. ## # 10
  711. ## # 20
  712. ## # 30
  713. var h: Hash = genHash(key) and high(t.data)
  714. let L = len(t)
  715. while isFilled(t.data[h].hcode):
  716. if t.data[h].key == key:
  717. yield t.data[h].val
  718. assert(len(t) == L, "the length of the table changed while iterating over it")
  719. h = nextTry(h, high(t.data))
  720. # -------------------------------------------------------------------
  721. # ---------------------------- TableRef -----------------------------
  722. # -------------------------------------------------------------------
  723. proc newTable*[A, B](initialSize = defaultInitialSize): <//>TableRef[A, B] =
  724. ## Creates a new ref hash table that is empty.
  725. ##
  726. ## ``initialSize`` must be a power of two (default: 64).
  727. ## If you need to accept runtime values for this you could use the
  728. ## `nextPowerOfTwo proc<math.html#nextPowerOfTwo,int>`_ from the
  729. ## `math module<math.html>`_ or the `rightSize proc<#rightSize,Natural>`_
  730. ## from this module.
  731. ##
  732. ## See also:
  733. ## * `newTable proc<#newTable,openArray[]>`_ for creating a `TableRef`
  734. ## from a collection of `(key, value)` pairs
  735. ## * `initTable proc<#initTable,int>`_ for creating a `Table`
  736. runnableExamples:
  737. let
  738. a = newTable[int, string]()
  739. b = newTable[char, seq[int]]()
  740. new(result)
  741. result[] = initTable[A, B](initialSize)
  742. proc newTable*[A, B](pairs: openArray[(A, B)]): <//>TableRef[A, B] =
  743. ## Creates a new ref hash table that contains the given ``pairs``.
  744. ##
  745. ## ``pairs`` is a container consisting of ``(key, value)`` tuples.
  746. ##
  747. ## See also:
  748. ## * `newTable proc<#newTable,int>`_
  749. ## * `toTable proc<#toTable,openArray[]>`_ for a `Table` version
  750. runnableExamples:
  751. let a = [('a', 5), ('b', 9)]
  752. let b = newTable(a)
  753. assert b == {'a': 5, 'b': 9}.newTable
  754. new(result)
  755. result[] = toTable[A, B](pairs)
  756. proc newTableFrom*[A, B, C](collection: A, index: proc(x: B): C): <//>TableRef[C, B] =
  757. ## Index the collection with the proc provided.
  758. # TODO: As soon as supported, change collection: A to collection: A[B]
  759. result = newTable[C, B]()
  760. for item in collection:
  761. result[index(item)] = item
  762. proc `[]`*[A, B](t: TableRef[A, B], key: A): var B =
  763. ## Retrieves the value at ``t[key]``.
  764. ##
  765. ## If ``key`` is not in ``t``, the ``KeyError`` exception is raised.
  766. ## One can check with `hasKey proc<#hasKey,TableRef[A,B],A>`_ whether
  767. ## the key exists.
  768. ##
  769. ## See also:
  770. ## * `getOrDefault proc<#getOrDefault,TableRef[A,B],A>`_ to return
  771. ## a default value (e.g. zero for int) if the key doesn't exist
  772. ## * `getOrDefault proc<#getOrDefault,TableRef[A,B],A,B>`_ to return
  773. ## a custom value if the key doesn't exist
  774. ## * `[]= proc<#[]=,TableRef[A,B],A,B>`_ for inserting a new
  775. ## (key, value) pair in the table
  776. ## * `hasKey proc<#hasKey,TableRef[A,B],A>`_ for checking if a key is in
  777. ## the table
  778. runnableExamples:
  779. let a = {'a': 5, 'b': 9}.newTable
  780. doAssert a['a'] == 5
  781. doAssertRaises(KeyError):
  782. echo a['z']
  783. result = t[][key]
  784. proc `[]=`*[A, B](t: TableRef[A, B], key: A, val: B) =
  785. ## Inserts a ``(key, value)`` pair into ``t``.
  786. ##
  787. ## See also:
  788. ## * `[] proc<#[],TableRef[A,B],A>`_ for retrieving a value of a key
  789. ## * `hasKeyOrPut proc<#hasKeyOrPut,TableRef[A,B],A,B>`_
  790. ## * `mgetOrPut proc<#mgetOrPut,TableRef[A,B],A,B>`_
  791. ## * `del proc<#del,TableRef[A,B],A>`_ for removing a key from the table
  792. runnableExamples:
  793. var a = newTable[char, int]()
  794. a['x'] = 7
  795. a['y'] = 33
  796. doAssert a == {'x': 7, 'y': 33}.newTable
  797. t[][key] = val
  798. proc hasKey*[A, B](t: TableRef[A, B], key: A): bool =
  799. ## Returns true if ``key`` is in the table ``t``.
  800. ##
  801. ## See also:
  802. ## * `contains proc<#contains,TableRef[A,B],A>`_ for use with the `in`
  803. ## operator
  804. ## * `[] proc<#[],TableRef[A,B],A>`_ for retrieving a value of a key
  805. ## * `getOrDefault proc<#getOrDefault,TableRef[A,B],A>`_ to return
  806. ## a default value (e.g. zero for int) if the key doesn't exist
  807. ## * `getOrDefault proc<#getOrDefault,TableRef[A,B],A,B>`_ to return
  808. ## a custom value if the key doesn't exist
  809. runnableExamples:
  810. let a = {'a': 5, 'b': 9}.newTable
  811. doAssert a.hasKey('a') == true
  812. doAssert a.hasKey('z') == false
  813. result = t[].hasKey(key)
  814. proc contains*[A, B](t: TableRef[A, B], key: A): bool =
  815. ## Alias of `hasKey proc<#hasKey,TableRef[A,B],A>`_ for use with
  816. ## the ``in`` operator.
  817. runnableExamples:
  818. let a = {'a': 5, 'b': 9}.newTable
  819. doAssert 'b' in a == true
  820. doAssert a.contains('z') == false
  821. return hasKey[A, B](t, key)
  822. proc hasKeyOrPut*[A, B](t: var TableRef[A, B], key: A, val: B): bool =
  823. ## Returns true if ``key`` is in the table, otherwise inserts ``value``.
  824. ##
  825. ## See also:
  826. ## * `hasKey proc<#hasKey,TableRef[A,B],A>`_
  827. ## * `[] proc<#[],TableRef[A,B],A>`_ for retrieving a value of a key
  828. ## * `getOrDefault proc<#getOrDefault,TableRef[A,B],A>`_ to return
  829. ## a default value (e.g. zero for int) if the key doesn't exist
  830. ## * `getOrDefault proc<#getOrDefault,TableRef[A,B],A,B>`_ to return
  831. ## a custom value if the key doesn't exist
  832. runnableExamples:
  833. var a = {'a': 5, 'b': 9}.newTable
  834. if a.hasKeyOrPut('a', 50):
  835. a['a'] = 99
  836. if a.hasKeyOrPut('z', 50):
  837. a['z'] = 99
  838. doAssert a == {'a': 99, 'b': 9, 'z': 50}.newTable
  839. t[].hasKeyOrPut(key, val)
  840. proc getOrDefault*[A, B](t: TableRef[A, B], key: A): B =
  841. ## Retrieves the value at ``t[key]`` if ``key`` is in ``t``. Otherwise, the
  842. ## default initialization value for type ``B`` is returned (e.g. 0 for any
  843. ## integer type).
  844. ##
  845. ## See also:
  846. ## * `[] proc<#[],TableRef[A,B],A>`_ for retrieving a value of a key
  847. ## * `hasKey proc<#hasKey,TableRef[A,B],A>`_
  848. ## * `hasKeyOrPut proc<#hasKeyOrPut,TableRef[A,B],A,B>`_
  849. ## * `mgetOrPut proc<#mgetOrPut,TableRef[A,B],A,B>`_
  850. ## * `getOrDefault proc<#getOrDefault,TableRef[A,B],A,B>`_ to return
  851. ## a custom value if the key doesn't exist
  852. runnableExamples:
  853. let a = {'a': 5, 'b': 9}.newTable
  854. doAssert a.getOrDefault('a') == 5
  855. doAssert a.getOrDefault('z') == 0
  856. getOrDefault(t[], key)
  857. proc getOrDefault*[A, B](t: TableRef[A, B], key: A, default: B): B =
  858. ## Retrieves the value at ``t[key]`` if ``key`` is in ``t``.
  859. ## Otherwise, ``default`` is returned.
  860. ##
  861. ## See also:
  862. ## * `[] proc<#[],TableRef[A,B],A>`_ for retrieving a value of a key
  863. ## * `hasKey proc<#hasKey,TableRef[A,B],A>`_
  864. ## * `hasKeyOrPut proc<#hasKeyOrPut,TableRef[A,B],A,B>`_
  865. ## * `mgetOrPut proc<#mgetOrPut,TableRef[A,B],A,B>`_
  866. ## * `getOrDefault proc<#getOrDefault,TableRef[A,B],A>`_ to return
  867. ## a default value (e.g. zero for int) if the key doesn't exist
  868. runnableExamples:
  869. let a = {'a': 5, 'b': 9}.newTable
  870. doAssert a.getOrDefault('a', 99) == 5
  871. doAssert a.getOrDefault('z', 99) == 99
  872. getOrDefault(t[], key, default)
  873. proc mgetOrPut*[A, B](t: TableRef[A, B], key: A, val: B): var B =
  874. ## Retrieves value at ``t[key]`` or puts ``val`` if not present, either way
  875. ## returning a value which can be modified.
  876. ##
  877. ## See also:
  878. ## * `[] proc<#[],TableRef[A,B],A>`_ for retrieving a value of a key
  879. ## * `hasKey proc<#hasKey,TableRef[A,B],A>`_
  880. ## * `hasKeyOrPut proc<#hasKeyOrPut,TableRef[A,B],A,B>`_
  881. ## * `getOrDefault proc<#getOrDefault,TableRef[A,B],A>`_ to return
  882. ## a default value (e.g. zero for int) if the key doesn't exist
  883. ## * `getOrDefault proc<#getOrDefault,TableRef[A,B],A,B>`_ to return
  884. ## a custom value if the key doesn't exist
  885. runnableExamples:
  886. var a = {'a': 5, 'b': 9}.newTable
  887. doAssert a.mgetOrPut('a', 99) == 5
  888. doAssert a.mgetOrPut('z', 99) == 99
  889. doAssert a == {'a': 5, 'b': 9, 'z': 99}.newTable
  890. t[].mgetOrPut(key, val)
  891. proc len*[A, B](t: TableRef[A, B]): int =
  892. ## Returns the number of keys in ``t``.
  893. runnableExamples:
  894. let a = {'a': 5, 'b': 9}.newTable
  895. doAssert len(a) == 2
  896. result = t.counter
  897. proc add*[A, B](t: TableRef[A, B], key: A, val: B) =
  898. ## Puts a new ``(key, value)`` pair into ``t`` even if ``t[key]`` already exists.
  899. ##
  900. ## **This can introduce duplicate keys into the table!**
  901. ##
  902. ## Use `[]= proc<#[]=,TableRef[A,B],A,B>`_ for inserting a new
  903. ## (key, value) pair in the table without introducing duplicates.
  904. t[].add(key, val)
  905. proc del*[A, B](t: TableRef[A, B], key: A) =
  906. ## Deletes ``key`` from hash table ``t``. Does nothing if the key does not exist.
  907. ##
  908. ## **If duplicate keys were added, this may need to be called multiple times.**
  909. ##
  910. ## See also:
  911. ## * `take proc<#take,TableRef[A,B],A,B>`_
  912. ## * `clear proc<#clear,TableRef[A,B]>`_ to empty the whole table
  913. runnableExamples:
  914. var a = {'a': 5, 'b': 9, 'c': 13}.newTable
  915. a.del('a')
  916. doAssert a == {'b': 9, 'c': 13}.newTable
  917. a.del('z')
  918. doAssert a == {'b': 9, 'c': 13}.newTable
  919. t[].del(key)
  920. proc take*[A, B](t: TableRef[A, B], key: A, val: var B): bool =
  921. ## Deletes the ``key`` from the table.
  922. ## Returns ``true``, if the ``key`` existed, and sets ``val`` to the
  923. ## mapping of the key. Otherwise, returns ``false``, and the ``val`` is
  924. ## unchanged.
  925. ##
  926. ## **If duplicate keys were added, this may need to be called multiple times.**
  927. ##
  928. ## See also:
  929. ## * `del proc<#del,TableRef[A,B],A>`_
  930. ## * `clear proc<#clear,TableRef[A,B]>`_ to empty the whole table
  931. runnableExamples:
  932. var
  933. a = {'a': 5, 'b': 9, 'c': 13}.newTable
  934. i: int
  935. doAssert a.take('b', i) == true
  936. doAssert a == {'a': 5, 'c': 13}.newTable
  937. doAssert i == 9
  938. i = 0
  939. doAssert a.take('z', i) == false
  940. doAssert a == {'a': 5, 'c': 13}.newTable
  941. doAssert i == 0
  942. result = t[].take(key, val)
  943. proc clear*[A, B](t: TableRef[A, B]) =
  944. ## Resets the table so that it is empty.
  945. ##
  946. ## See also:
  947. ## * `del proc<#del,Table[A,B],A>`_
  948. ## * `take proc<#take,Table[A,B],A,B>`_
  949. runnableExamples:
  950. var a = {'a': 5, 'b': 9, 'c': 13}.newTable
  951. doAssert len(a) == 3
  952. clear(a)
  953. doAssert len(a) == 0
  954. clearImpl()
  955. proc `$`*[A, B](t: TableRef[A, B]): string =
  956. ## The ``$`` operator for hash tables. Used internally when calling `echo`
  957. ## on a table.
  958. dollarImpl()
  959. proc `==`*[A, B](s, t: TableRef[A, B]): bool =
  960. ## The ``==`` operator for hash tables. Returns ``true`` if either both tables
  961. ## are ``nil``, or neither is ``nil`` and the content of both tables contains the
  962. ## same key-value pairs. Insert order does not matter.
  963. runnableExamples:
  964. let
  965. a = {'a': 5, 'b': 9, 'c': 13}.newTable
  966. b = {'b': 9, 'c': 13, 'a': 5}.newTable
  967. doAssert a == b
  968. if isNil(s): result = isNil(t)
  969. elif isNil(t): result = false
  970. else: equalsImpl(s[], t[])
  971. iterator pairs*[A, B](t: TableRef[A, B]): (A, B) =
  972. ## Iterates over any ``(key, value)`` pair in the table ``t``.
  973. ##
  974. ## See also:
  975. ## * `mpairs iterator<#mpairs.i,TableRef[A,B]>`_
  976. ## * `keys iterator<#keys.i,TableRef[A,B]>`_
  977. ## * `values iterator<#values.i,TableRef[A,B]>`_
  978. ##
  979. ## **Examples:**
  980. ##
  981. ## .. code-block::
  982. ## let a = {
  983. ## 'o': [1, 5, 7, 9],
  984. ## 'e': [2, 4, 6, 8]
  985. ## }.newTable
  986. ##
  987. ## for k, v in a.pairs:
  988. ## echo "key: ", k
  989. ## echo "value: ", v
  990. ##
  991. ## # key: e
  992. ## # value: [2, 4, 6, 8]
  993. ## # key: o
  994. ## # value: [1, 5, 7, 9]
  995. let L = len(t)
  996. for h in 0 .. high(t.data):
  997. if isFilled(t.data[h].hcode):
  998. yield (t.data[h].key, t.data[h].val)
  999. assert(len(t) == L, "the length of the table changed while iterating over it")
  1000. iterator mpairs*[A, B](t: TableRef[A, B]): (A, var B) =
  1001. ## Iterates over any ``(key, value)`` pair in the table ``t``. The values
  1002. ## can be modified.
  1003. ##
  1004. ## See also:
  1005. ## * `pairs iterator<#pairs.i,TableRef[A,B]>`_
  1006. ## * `mvalues iterator<#mvalues.i,TableRef[A,B]>`_
  1007. runnableExamples:
  1008. let a = {
  1009. 'o': @[1, 5, 7, 9],
  1010. 'e': @[2, 4, 6, 8]
  1011. }.newTable
  1012. for k, v in a.mpairs:
  1013. v.add(v[0] + 10)
  1014. doAssert a == {'e': @[2, 4, 6, 8, 12], 'o': @[1, 5, 7, 9, 11]}.newTable
  1015. let L = len(t)
  1016. for h in 0 .. high(t.data):
  1017. if isFilled(t.data[h].hcode):
  1018. yield (t.data[h].key, t.data[h].val)
  1019. assert(len(t) == L, "the length of the table changed while iterating over it")
  1020. iterator keys*[A, B](t: TableRef[A, B]): A =
  1021. ## Iterates over any key in the table ``t``.
  1022. ##
  1023. ## See also:
  1024. ## * `pairs iterator<#pairs.i,TableRef[A,B]>`_
  1025. ## * `values iterator<#values.i,TableRef[A,B]>`_
  1026. runnableExamples:
  1027. let a = {
  1028. 'o': @[1, 5, 7, 9],
  1029. 'e': @[2, 4, 6, 8]
  1030. }.newTable
  1031. for k in a.keys:
  1032. a[k].add(99)
  1033. doAssert a == {'e': @[2, 4, 6, 8, 99], 'o': @[1, 5, 7, 9, 99]}.newTable
  1034. let L = len(t)
  1035. for h in 0 .. high(t.data):
  1036. if isFilled(t.data[h].hcode):
  1037. yield t.data[h].key
  1038. assert(len(t) == L, "the length of the table changed while iterating over it")
  1039. iterator values*[A, B](t: TableRef[A, B]): B =
  1040. ## Iterates over any value in the table ``t``.
  1041. ##
  1042. ## See also:
  1043. ## * `pairs iterator<#pairs.i,TableRef[A,B]>`_
  1044. ## * `keys iterator<#keys.i,TableRef[A,B]>`_
  1045. ## * `mvalues iterator<#mvalues.i,TableRef[A,B]>`_
  1046. runnableExamples:
  1047. let a = {
  1048. 'o': @[1, 5, 7, 9],
  1049. 'e': @[2, 4, 6, 8]
  1050. }.newTable
  1051. for v in a.values:
  1052. doAssert v.len == 4
  1053. let L = len(t)
  1054. for h in 0 .. high(t.data):
  1055. if isFilled(t.data[h].hcode):
  1056. yield t.data[h].val
  1057. assert(len(t) == L, "the length of the table changed while iterating over it")
  1058. iterator mvalues*[A, B](t: TableRef[A, B]): var B =
  1059. ## Iterates over any value in the table ``t``. The values can be modified.
  1060. ##
  1061. ## See also:
  1062. ## * `mpairs iterator<#mpairs.i,TableRef[A,B]>`_
  1063. ## * `values iterator<#values.i,TableRef[A,B]>`_
  1064. runnableExamples:
  1065. let a = {
  1066. 'o': @[1, 5, 7, 9],
  1067. 'e': @[2, 4, 6, 8]
  1068. }.newTable
  1069. for v in a.mvalues:
  1070. v.add(99)
  1071. doAssert a == {'e': @[2, 4, 6, 8, 99], 'o': @[1, 5, 7, 9, 99]}.newTable
  1072. let L = len(t)
  1073. for h in 0 .. high(t.data):
  1074. if isFilled(t.data[h].hcode):
  1075. yield t.data[h].val
  1076. assert(len(t) == L, "the length of the table changed while iterating over it")
  1077. # ---------------------------------------------------------------------------
  1078. # ------------------------------ OrderedTable -------------------------------
  1079. # ---------------------------------------------------------------------------
  1080. type
  1081. OrderedKeyValuePair[A, B] = tuple[
  1082. hcode: Hash, next: int, key: A, val: B]
  1083. OrderedKeyValuePairSeq[A, B] = seq[OrderedKeyValuePair[A, B]]
  1084. OrderedTable*[A, B] = object
  1085. ## Hash table that remembers insertion order.
  1086. ##
  1087. ## For creating an empty OrderedTable, use `initOrderedTable proc
  1088. ## <#initOrderedTable,int>`_.
  1089. data: OrderedKeyValuePairSeq[A, B]
  1090. counter, first, last: int
  1091. OrderedTableRef*[A, B] = ref OrderedTable[A, B] ## Ref version of
  1092. ## `OrderedTable<#OrderedTable>`_.
  1093. ##
  1094. ## For creating a new empty OrderedTableRef, use `newOrderedTable proc
  1095. ## <#newOrderedTable,int>`_.
  1096. # ------------------------------ helpers ---------------------------------
  1097. proc rawGetKnownHC[A, B](t: OrderedTable[A, B], key: A, hc: Hash): int =
  1098. rawGetKnownHCImpl()
  1099. proc rawGetDeep[A, B](t: OrderedTable[A, B], key: A, hc: var Hash): int {.inline.} =
  1100. rawGetDeepImpl()
  1101. proc rawGet[A, B](t: OrderedTable[A, B], key: A, hc: var Hash): int =
  1102. rawGetImpl()
  1103. proc rawInsert[A, B](t: var OrderedTable[A, B],
  1104. data: var OrderedKeyValuePairSeq[A, B],
  1105. key: A, val: B, hc: Hash, h: Hash) =
  1106. rawInsertImpl()
  1107. data[h].next = -1
  1108. if t.first < 0: t.first = h
  1109. if t.last >= 0: data[t.last].next = h
  1110. t.last = h
  1111. proc enlarge[A, B](t: var OrderedTable[A, B]) =
  1112. var n: OrderedKeyValuePairSeq[A, B]
  1113. newSeq(n, len(t.data) * growthFactor)
  1114. var h = t.first
  1115. t.first = -1
  1116. t.last = -1
  1117. swap(t.data, n)
  1118. while h >= 0:
  1119. var nxt = n[h].next
  1120. let eh = n[h].hcode
  1121. if isFilled(eh):
  1122. var j: Hash = eh and maxHash(t)
  1123. while isFilled(t.data[j].hcode):
  1124. j = nextTry(j, maxHash(t))
  1125. rawInsert(t, t.data, n[h].key, n[h].val, n[h].hcode, j)
  1126. h = nxt
  1127. template forAllOrderedPairs(yieldStmt: untyped) {.dirty.} =
  1128. if t.counter > 0:
  1129. var h = t.first
  1130. while h >= 0:
  1131. var nxt = t.data[h].next
  1132. if isFilled(t.data[h].hcode):
  1133. yieldStmt
  1134. h = nxt
  1135. # ----------------------------------------------------------------------
  1136. proc initOrderedTable*[A, B](initialSize = defaultInitialSize): OrderedTable[A, B] =
  1137. ## Creates a new ordered hash table that is empty.
  1138. ##
  1139. ## ``initialSize`` must be a power of two (default: 64).
  1140. ## If you need to accept runtime values for this you could use the
  1141. ## `nextPowerOfTwo proc<math.html#nextPowerOfTwo,int>`_ from the
  1142. ## `math module<math.html>`_ or the `rightSize proc<#rightSize,Natural>`_
  1143. ## from this module.
  1144. ##
  1145. ## Starting from Nim v0.20, tables are initialized by default and it is
  1146. ## not necessary to call this function explicitly.
  1147. ##
  1148. ## See also:
  1149. ## * `toOrderedTable proc<#toOrderedTable,openArray[]>`_
  1150. ## * `newOrderedTable proc<#newOrderedTable,int>`_ for creating an
  1151. ## `OrderedTableRef`
  1152. runnableExamples:
  1153. let
  1154. a = initOrderedTable[int, string]()
  1155. b = initOrderedTable[char, seq[int]]()
  1156. initImpl(result, initialSize)
  1157. proc `[]=`*[A, B](t: var OrderedTable[A, B], key: A, val: B) =
  1158. ## Inserts a ``(key, value)`` pair into ``t``.
  1159. ##
  1160. ## See also:
  1161. ## * `[] proc<#[],OrderedTable[A,B],A>`_ for retrieving a value of a key
  1162. ## * `hasKeyOrPut proc<#hasKeyOrPut,OrderedTable[A,B],A,B>`_
  1163. ## * `mgetOrPut proc<#mgetOrPut,OrderedTable[A,B],A,B>`_
  1164. ## * `del proc<#del,OrderedTable[A,B],A>`_ for removing a key from the table
  1165. runnableExamples:
  1166. var a = initOrderedTable[char, int]()
  1167. a['x'] = 7
  1168. a['y'] = 33
  1169. doAssert a == {'x': 7, 'y': 33}.toOrderedTable
  1170. putImpl(enlarge)
  1171. proc toOrderedTable*[A, B](pairs: openArray[(A, B)]): OrderedTable[A, B] =
  1172. ## Creates a new ordered hash table that contains the given ``pairs``.
  1173. ##
  1174. ## ``pairs`` is a container consisting of ``(key, value)`` tuples.
  1175. ##
  1176. ## See also:
  1177. ## * `initOrderedTable proc<#initOrderedTable,int>`_
  1178. ## * `newOrderedTable proc<#newOrderedTable,openArray[]>`_ for an
  1179. ## `OrderedTableRef` version
  1180. runnableExamples:
  1181. let a = [('a', 5), ('b', 9)]
  1182. let b = toOrderedTable(a)
  1183. assert b == {'a': 5, 'b': 9}.toOrderedTable
  1184. result = initOrderedTable[A, B](rightSize(pairs.len))
  1185. for key, val in items(pairs): result[key] = val
  1186. proc `[]`*[A, B](t: OrderedTable[A, B], key: A): B =
  1187. ## Retrieves the value at ``t[key]``.
  1188. ##
  1189. ## If ``key`` is not in ``t``, the ``KeyError`` exception is raised.
  1190. ## One can check with `hasKey proc<#hasKey,OrderedTable[A,B],A>`_ whether
  1191. ## the key exists.
  1192. ##
  1193. ## See also:
  1194. ## * `getOrDefault proc<#getOrDefault,OrderedTable[A,B],A>`_ to return
  1195. ## a default value (e.g. zero for int) if the key doesn't exist
  1196. ## * `getOrDefault proc<#getOrDefault,OrderedTable[A,B],A,B>`_ to return
  1197. ## a custom value if the key doesn't exist
  1198. ## * `[]= proc<#[]=,OrderedTable[A,B],A,B>`_ for inserting a new
  1199. ## (key, value) pair in the table
  1200. ## * `hasKey proc<#hasKey,OrderedTable[A,B],A>`_ for checking if a
  1201. ## key is in the table
  1202. runnableExamples:
  1203. let a = {'a': 5, 'b': 9}.toOrderedTable
  1204. doAssert a['a'] == 5
  1205. doAssertRaises(KeyError):
  1206. echo a['z']
  1207. get(t, key)
  1208. proc `[]`*[A, B](t: var OrderedTable[A, B], key: A): var B =
  1209. ## Retrieves the value at ``t[key]``. The value can be modified.
  1210. ##
  1211. ## If ``key`` is not in ``t``, the ``KeyError`` exception is raised.
  1212. ##
  1213. ## See also:
  1214. ## * `getOrDefault proc<#getOrDefault,OrderedTable[A,B],A>`_ to return
  1215. ## a default value (e.g. zero for int) if the key doesn't exist
  1216. ## * `getOrDefault proc<#getOrDefault,OrderedTable[A,B],A,B>`_ to return
  1217. ## a custom value if the key doesn't exist
  1218. ## * `[]= proc<#[]=,OrderedTable[A,B],A,B>`_ for inserting a new
  1219. ## (key, value) pair in the table
  1220. ## * `hasKey proc<#hasKey,OrderedTable[A,B],A>`_ for checking if a
  1221. ## key is in the table
  1222. get(t, key)
  1223. proc hasKey*[A, B](t: OrderedTable[A, B], key: A): bool =
  1224. ## Returns true if ``key`` is in the table ``t``.
  1225. ##
  1226. ## See also:
  1227. ## * `contains proc<#contains,OrderedTable[A,B],A>`_ for use with the `in`
  1228. ## operator
  1229. ## * `[] proc<#[],OrderedTable[A,B],A>`_ for retrieving a value of a key
  1230. ## * `getOrDefault proc<#getOrDefault,OrderedTable[A,B],A>`_ to return
  1231. ## a default value (e.g. zero for int) if the key doesn't exist
  1232. ## * `getOrDefault proc<#getOrDefault,OrderedTable[A,B],A,B>`_ to return
  1233. ## a custom value if the key doesn't exist
  1234. runnableExamples:
  1235. let a = {'a': 5, 'b': 9}.toOrderedTable
  1236. doAssert a.hasKey('a') == true
  1237. doAssert a.hasKey('z') == false
  1238. var hc: Hash
  1239. result = rawGet(t, key, hc) >= 0
  1240. proc contains*[A, B](t: OrderedTable[A, B], key: A): bool =
  1241. ## Alias of `hasKey proc<#hasKey,OrderedTable[A,B],A>`_ for use with
  1242. ## the ``in`` operator.
  1243. runnableExamples:
  1244. let a = {'a': 5, 'b': 9}.toOrderedTable
  1245. doAssert 'b' in a == true
  1246. doAssert a.contains('z') == false
  1247. return hasKey[A, B](t, key)
  1248. proc hasKeyOrPut*[A, B](t: var OrderedTable[A, B], key: A, val: B): bool =
  1249. ## Returns true if ``key`` is in the table, otherwise inserts ``value``.
  1250. ##
  1251. ## See also:
  1252. ## * `hasKey proc<#hasKey,OrderedTable[A,B],A>`_
  1253. ## * `[] proc<#[],OrderedTable[A,B],A>`_ for retrieving a value of a key
  1254. ## * `getOrDefault proc<#getOrDefault,OrderedTable[A,B],A>`_ to return
  1255. ## a default value (e.g. zero for int) if the key doesn't exist
  1256. ## * `getOrDefault proc<#getOrDefault,OrderedTable[A,B],A,B>`_ to return
  1257. ## a custom value if the key doesn't exist
  1258. runnableExamples:
  1259. var a = {'a': 5, 'b': 9}.toOrderedTable
  1260. if a.hasKeyOrPut('a', 50):
  1261. a['a'] = 99
  1262. if a.hasKeyOrPut('z', 50):
  1263. a['z'] = 99
  1264. doAssert a == {'a': 99, 'b': 9, 'z': 50}.toOrderedTable
  1265. hasKeyOrPutImpl(enlarge)
  1266. proc getOrDefault*[A, B](t: OrderedTable[A, B], key: A): B =
  1267. ## Retrieves the value at ``t[key]`` if ``key`` is in ``t``. Otherwise, the
  1268. ## default initialization value for type ``B`` is returned (e.g. 0 for any
  1269. ## integer type).
  1270. ##
  1271. ## See also:
  1272. ## * `[] proc<#[],OrderedTable[A,B],A>`_ for retrieving a value of a key
  1273. ## * `hasKey proc<#hasKey,OrderedTable[A,B],A>`_
  1274. ## * `hasKeyOrPut proc<#hasKeyOrPut,OrderedTable[A,B],A,B>`_
  1275. ## * `mgetOrPut proc<#mgetOrPut,OrderedTable[A,B],A,B>`_
  1276. ## * `getOrDefault proc<#getOrDefault,OrderedTable[A,B],A,B>`_ to return
  1277. ## a custom value if the key doesn't exist
  1278. runnableExamples:
  1279. let a = {'a': 5, 'b': 9}.toOrderedTable
  1280. doAssert a.getOrDefault('a') == 5
  1281. doAssert a.getOrDefault('z') == 0
  1282. getOrDefaultImpl(t, key)
  1283. proc getOrDefault*[A, B](t: OrderedTable[A, B], key: A, default: B): B =
  1284. ## Retrieves the value at ``t[key]`` if ``key`` is in ``t``.
  1285. ## Otherwise, ``default`` is returned.
  1286. ##
  1287. ## See also:
  1288. ## * `[] proc<#[],OrderedTable[A,B],A>`_ for retrieving a value of a key
  1289. ## * `hasKey proc<#hasKey,OrderedTable[A,B],A>`_
  1290. ## * `hasKeyOrPut proc<#hasKeyOrPut,OrderedTable[A,B],A,B>`_
  1291. ## * `mgetOrPut proc<#mgetOrPut,OrderedTable[A,B],A,B>`_
  1292. ## * `getOrDefault proc<#getOrDefault,OrderedTable[A,B],A>`_ to return
  1293. ## a default value (e.g. zero for int) if the key doesn't exist
  1294. runnableExamples:
  1295. let a = {'a': 5, 'b': 9}.toOrderedTable
  1296. doAssert a.getOrDefault('a', 99) == 5
  1297. doAssert a.getOrDefault('z', 99) == 99
  1298. getOrDefaultImpl(t, key, default)
  1299. proc mgetOrPut*[A, B](t: var OrderedTable[A, B], key: A, val: B): var B =
  1300. ## Retrieves value at ``t[key]`` or puts ``val`` if not present, either way
  1301. ## returning a value which can be modified.
  1302. ##
  1303. ## See also:
  1304. ## * `[] proc<#[],OrderedTable[A,B],A>`_ for retrieving a value of a key
  1305. ## * `hasKey proc<#hasKey,OrderedTable[A,B],A>`_
  1306. ## * `hasKeyOrPut proc<#hasKeyOrPut,OrderedTable[A,B],A,B>`_
  1307. ## * `getOrDefault proc<#getOrDefault,OrderedTable[A,B],A>`_ to return
  1308. ## a default value (e.g. zero for int) if the key doesn't exist
  1309. ## * `getOrDefault proc<#getOrDefault,OrderedTable[A,B],A,B>`_ to return
  1310. ## a custom value if the key doesn't exist
  1311. runnableExamples:
  1312. var a = {'a': 5, 'b': 9}.toOrderedTable
  1313. doAssert a.mgetOrPut('a', 99) == 5
  1314. doAssert a.mgetOrPut('z', 99) == 99
  1315. doAssert a == {'a': 5, 'b': 9, 'z': 99}.toOrderedTable
  1316. mgetOrPutImpl(enlarge)
  1317. proc len*[A, B](t: OrderedTable[A, B]): int {.inline.} =
  1318. ## Returns the number of keys in ``t``.
  1319. runnableExamples:
  1320. let a = {'a': 5, 'b': 9}.toOrderedTable
  1321. doAssert len(a) == 2
  1322. result = t.counter
  1323. proc add*[A, B](t: var OrderedTable[A, B], key: A, val: B) =
  1324. ## Puts a new ``(key, value)`` pair into ``t`` even if ``t[key]`` already exists.
  1325. ##
  1326. ## **This can introduce duplicate keys into the table!**
  1327. ##
  1328. ## Use `[]= proc<#[]=,OrderedTable[A,B],A,B>`_ for inserting a new
  1329. ## (key, value) pair in the table without introducing duplicates.
  1330. addImpl(enlarge)
  1331. proc del*[A, B](t: var OrderedTable[A, B], key: A) =
  1332. ## Deletes ``key`` from hash table ``t``. Does nothing if the key does not exist.
  1333. ##
  1334. ## O(n) complexity.
  1335. ##
  1336. ## See also:
  1337. ## * `clear proc<#clear,OrderedTable[A,B]>`_ to empty the whole table
  1338. runnableExamples:
  1339. var a = {'a': 5, 'b': 9, 'c': 13}.toOrderedTable
  1340. a.del('a')
  1341. doAssert a == {'b': 9, 'c': 13}.toOrderedTable
  1342. a.del('z')
  1343. doAssert a == {'b': 9, 'c': 13}.toOrderedTable
  1344. if t.counter == 0: return
  1345. var n: OrderedKeyValuePairSeq[A, B]
  1346. newSeq(n, len(t.data))
  1347. var h = t.first
  1348. t.first = -1
  1349. t.last = -1
  1350. swap(t.data, n)
  1351. let hc = genHash(key)
  1352. while h >= 0:
  1353. var nxt = n[h].next
  1354. if isFilled(n[h].hcode):
  1355. if n[h].hcode == hc and n[h].key == key:
  1356. dec t.counter
  1357. else:
  1358. var j = -1 - rawGetKnownHC(t, n[h].key, n[h].hcode)
  1359. rawInsert(t, t.data, n[h].key, n[h].val, n[h].hcode, j)
  1360. h = nxt
  1361. proc clear*[A, B](t: var OrderedTable[A, B]) =
  1362. ## Resets the table so that it is empty.
  1363. ##
  1364. ## See also:
  1365. ## * `del proc<#del,OrderedTable[A,B],A>`_
  1366. runnableExamples:
  1367. var a = {'a': 5, 'b': 9, 'c': 13}.toOrderedTable
  1368. doAssert len(a) == 3
  1369. clear(a)
  1370. doAssert len(a) == 0
  1371. clearImpl()
  1372. t.first = -1
  1373. t.last = -1
  1374. proc sort*[A, B](t: var OrderedTable[A, B], cmp: proc (x, y: (A, B)): int,
  1375. order = SortOrder.Ascending) =
  1376. ## Sorts ``t`` according to the function ``cmp``.
  1377. ##
  1378. ## This modifies the internal list
  1379. ## that kept the insertion order, so insertion order is lost after this
  1380. ## call but key lookup and insertions remain possible after ``sort`` (in
  1381. ## contrast to the `sort proc<#sort,CountTable[A]>`_ for count tables).
  1382. runnableExamples:
  1383. import algorithm
  1384. var a = initOrderedTable[char, int]()
  1385. for i, c in "cab":
  1386. a[c] = 10*i
  1387. doAssert a == {'c': 0, 'a': 10, 'b': 20}.toOrderedTable
  1388. a.sort(system.cmp)
  1389. doAssert a == {'a': 10, 'b': 20, 'c': 0}.toOrderedTable
  1390. a.sort(system.cmp, order = SortOrder.Descending)
  1391. doAssert a == {'c': 0, 'b': 20, 'a': 10}.toOrderedTable
  1392. var list = t.first
  1393. var
  1394. p, q, e, tail, oldhead: int
  1395. nmerges, psize, qsize, i: int
  1396. if t.counter == 0: return
  1397. var insize = 1
  1398. while true:
  1399. p = list; oldhead = list
  1400. list = -1; tail = -1; nmerges = 0
  1401. while p >= 0:
  1402. inc(nmerges)
  1403. q = p
  1404. psize = 0
  1405. i = 0
  1406. while i < insize:
  1407. inc(psize)
  1408. q = t.data[q].next
  1409. if q < 0: break
  1410. inc(i)
  1411. qsize = insize
  1412. while psize > 0 or (qsize > 0 and q >= 0):
  1413. if psize == 0:
  1414. e = q; q = t.data[q].next; dec(qsize)
  1415. elif qsize == 0 or q < 0:
  1416. e = p; p = t.data[p].next; dec(psize)
  1417. elif cmp((t.data[p].key, t.data[p].val),
  1418. (t.data[q].key, t.data[q].val)) * order <= 0:
  1419. e = p; p = t.data[p].next; dec(psize)
  1420. else:
  1421. e = q; q = t.data[q].next; dec(qsize)
  1422. if tail >= 0: t.data[tail].next = e
  1423. else: list = e
  1424. tail = e
  1425. p = q
  1426. t.data[tail].next = -1
  1427. if nmerges <= 1: break
  1428. insize = insize * 2
  1429. t.first = list
  1430. t.last = tail
  1431. proc `$`*[A, B](t: OrderedTable[A, B]): string =
  1432. ## The ``$`` operator for ordered hash tables. Used internally when calling
  1433. ## `echo` on a table.
  1434. dollarImpl()
  1435. proc `==`*[A, B](s, t: OrderedTable[A, B]): bool =
  1436. ## The ``==`` operator for ordered hash tables. Returns ``true`` if both the
  1437. ## content and the order are equal.
  1438. runnableExamples:
  1439. let
  1440. a = {'a': 5, 'b': 9, 'c': 13}.toOrderedTable
  1441. b = {'b': 9, 'c': 13, 'a': 5}.toOrderedTable
  1442. doAssert a != b
  1443. if s.counter != t.counter:
  1444. return false
  1445. var ht = t.first
  1446. var hs = s.first
  1447. while ht >= 0 and hs >= 0:
  1448. var nxtt = t.data[ht].next
  1449. var nxts = s.data[hs].next
  1450. if isFilled(t.data[ht].hcode) and isFilled(s.data[hs].hcode):
  1451. if (s.data[hs].key != t.data[ht].key) or (s.data[hs].val != t.data[ht].val):
  1452. return false
  1453. ht = nxtt
  1454. hs = nxts
  1455. return true
  1456. iterator pairs*[A, B](t: OrderedTable[A, B]): (A, B) =
  1457. ## Iterates over any ``(key, value)`` pair in the table ``t`` in insertion
  1458. ## order.
  1459. ##
  1460. ## See also:
  1461. ## * `mpairs iterator<#mpairs.i,OrderedTable[A,B]>`_
  1462. ## * `keys iterator<#keys.i,OrderedTable[A,B]>`_
  1463. ## * `values iterator<#values.i,OrderedTable[A,B]>`_
  1464. ##
  1465. ## **Examples:**
  1466. ##
  1467. ## .. code-block::
  1468. ## let a = {
  1469. ## 'o': [1, 5, 7, 9],
  1470. ## 'e': [2, 4, 6, 8]
  1471. ## }.toOrderedTable
  1472. ##
  1473. ## for k, v in a.pairs:
  1474. ## echo "key: ", k
  1475. ## echo "value: ", v
  1476. ##
  1477. ## # key: o
  1478. ## # value: [1, 5, 7, 9]
  1479. ## # key: e
  1480. ## # value: [2, 4, 6, 8]
  1481. let L = len(t)
  1482. forAllOrderedPairs:
  1483. yield (t.data[h].key, t.data[h].val)
  1484. assert(len(t) == L, "the length of the table changed while iterating over it")
  1485. iterator mpairs*[A, B](t: var OrderedTable[A, B]): (A, var B) =
  1486. ## Iterates over any ``(key, value)`` pair in the table ``t`` (must be
  1487. ## declared as `var`) in insertion order. The values can be modified.
  1488. ##
  1489. ## See also:
  1490. ## * `pairs iterator<#pairs.i,OrderedTable[A,B]>`_
  1491. ## * `mvalues iterator<#mvalues.i,OrderedTable[A,B]>`_
  1492. runnableExamples:
  1493. var a = {
  1494. 'o': @[1, 5, 7, 9],
  1495. 'e': @[2, 4, 6, 8]
  1496. }.toOrderedTable
  1497. for k, v in a.mpairs:
  1498. v.add(v[0] + 10)
  1499. doAssert a == {'o': @[1, 5, 7, 9, 11],
  1500. 'e': @[2, 4, 6, 8, 12]}.toOrderedTable
  1501. let L = len(t)
  1502. forAllOrderedPairs:
  1503. yield (t.data[h].key, t.data[h].val)
  1504. assert(len(t) == L, "the length of the table changed while iterating over it")
  1505. iterator keys*[A, B](t: OrderedTable[A, B]): A =
  1506. ## Iterates over any key in the table ``t`` in insertion order.
  1507. ##
  1508. ## See also:
  1509. ## * `pairs iterator<#pairs.i,OrderedTable[A,B]>`_
  1510. ## * `values iterator<#values.i,OrderedTable[A,B]>`_
  1511. runnableExamples:
  1512. var a = {
  1513. 'o': @[1, 5, 7, 9],
  1514. 'e': @[2, 4, 6, 8]
  1515. }.toOrderedTable
  1516. for k in a.keys:
  1517. a[k].add(99)
  1518. doAssert a == {'o': @[1, 5, 7, 9, 99],
  1519. 'e': @[2, 4, 6, 8, 99]}.toOrderedTable
  1520. let L = len(t)
  1521. forAllOrderedPairs:
  1522. yield t.data[h].key
  1523. assert(len(t) == L, "the length of the table changed while iterating over it")
  1524. iterator values*[A, B](t: OrderedTable[A, B]): B =
  1525. ## Iterates over any value in the table ``t`` in insertion order.
  1526. ##
  1527. ## See also:
  1528. ## * `pairs iterator<#pairs.i,OrderedTable[A,B]>`_
  1529. ## * `keys iterator<#keys.i,OrderedTable[A,B]>`_
  1530. ## * `mvalues iterator<#mvalues.i,OrderedTable[A,B]>`_
  1531. runnableExamples:
  1532. let a = {
  1533. 'o': @[1, 5, 7, 9],
  1534. 'e': @[2, 4, 6, 8]
  1535. }.toOrderedTable
  1536. for v in a.values:
  1537. doAssert v.len == 4
  1538. let L = len(t)
  1539. forAllOrderedPairs:
  1540. yield t.data[h].val
  1541. assert(len(t) == L, "the length of the table changed while iterating over it")
  1542. iterator mvalues*[A, B](t: var OrderedTable[A, B]): var B =
  1543. ## Iterates over any value in the table ``t`` (must be
  1544. ## declared as `var`) in insertion order. The values
  1545. ## can be modified.
  1546. ##
  1547. ## See also:
  1548. ## * `mpairs iterator<#mpairs.i,OrderedTable[A,B]>`_
  1549. ## * `values iterator<#values.i,OrderedTable[A,B]>`_
  1550. runnableExamples:
  1551. var a = {
  1552. 'o': @[1, 5, 7, 9],
  1553. 'e': @[2, 4, 6, 8]
  1554. }.toOrderedTable
  1555. for v in a.mvalues:
  1556. v.add(99)
  1557. doAssert a == {'o': @[1, 5, 7, 9, 99],
  1558. 'e': @[2, 4, 6, 8, 99]}.toOrderedTable
  1559. let L = len(t)
  1560. forAllOrderedPairs:
  1561. yield t.data[h].val
  1562. assert(len(t) == L, "the length of the table changed while iterating over it")
  1563. # ---------------------------------------------------------------------------
  1564. # --------------------------- OrderedTableRef -------------------------------
  1565. # ---------------------------------------------------------------------------
  1566. proc newOrderedTable*[A, B](initialSize = defaultInitialSize): <//>OrderedTableRef[A, B] =
  1567. ## Creates a new ordered ref hash table that is empty.
  1568. ##
  1569. ## ``initialSize`` must be a power of two (default: 64).
  1570. ## If you need to accept runtime values for this you could use the
  1571. ## `nextPowerOfTwo proc<math.html#nextPowerOfTwo,int>`_ from the
  1572. ## `math module<math.html>`_ or the `rightSize proc<#rightSize,Natural>`_
  1573. ## from this module.
  1574. ##
  1575. ## See also:
  1576. ## * `newOrderedTable proc<#newOrderedTable,openArray[]>`_ for creating
  1577. ## an `OrderedTableRef` from a collection of `(key, value)` pairs
  1578. ## * `initOrderedTable proc<#initOrderedTable,int>`_ for creating an
  1579. ## `OrderedTable`
  1580. runnableExamples:
  1581. let
  1582. a = newOrderedTable[int, string]()
  1583. b = newOrderedTable[char, seq[int]]()
  1584. new(result)
  1585. result[] = initOrderedTable[A, B](initialSize)
  1586. proc newOrderedTable*[A, B](pairs: openArray[(A, B)]): <//>OrderedTableRef[A, B] =
  1587. ## Creates a new ordered ref hash table that contains the given ``pairs``.
  1588. ##
  1589. ## ``pairs`` is a container consisting of ``(key, value)`` tuples.
  1590. ##
  1591. ## See also:
  1592. ## * `newOrderedTable proc<#newOrderedTable,int>`_
  1593. ## * `toOrderedTable proc<#toOrderedTable,openArray[]>`_ for an
  1594. ## `OrderedTable` version
  1595. runnableExamples:
  1596. let a = [('a', 5), ('b', 9)]
  1597. let b = newOrderedTable(a)
  1598. assert b == {'a': 5, 'b': 9}.newOrderedTable
  1599. result = newOrderedTable[A, B](rightSize(pairs.len))
  1600. for key, val in items(pairs): result.add(key, val)
  1601. proc `[]`*[A, B](t: OrderedTableRef[A, B], key: A): var B =
  1602. ## Retrieves the value at ``t[key]``.
  1603. ##
  1604. ## If ``key`` is not in ``t``, the ``KeyError`` exception is raised.
  1605. ## One can check with `hasKey proc<#hasKey,OrderedTableRef[A,B],A>`_ whether
  1606. ## the key exists.
  1607. ##
  1608. ## See also:
  1609. ## * `getOrDefault proc<#getOrDefault,OrderedTableRef[A,B],A>`_ to return
  1610. ## a default value (e.g. zero for int) if the key doesn't exist
  1611. ## * `getOrDefault proc<#getOrDefault,OrderedTableRef[A,B],A,B>`_ to return
  1612. ## a custom value if the key doesn't exist
  1613. ## * `[]= proc<#[]=,OrderedTableRef[A,B],A,B>`_ for inserting a new
  1614. ## (key, value) pair in the table
  1615. ## * `hasKey proc<#hasKey,OrderedTableRef[A,B],A>`_ for checking if
  1616. ## a key is in the table
  1617. runnableExamples:
  1618. let a = {'a': 5, 'b': 9}.newOrderedTable
  1619. doAssert a['a'] == 5
  1620. doAssertRaises(KeyError):
  1621. echo a['z']
  1622. result = t[][key]
  1623. proc `[]=`*[A, B](t: OrderedTableRef[A, B], key: A, val: B) =
  1624. ## Inserts a ``(key, value)`` pair into ``t``.
  1625. ##
  1626. ## See also:
  1627. ## * `[] proc<#[],OrderedTableRef[A,B],A>`_ for retrieving a value of a key
  1628. ## * `hasKeyOrPut proc<#hasKeyOrPut,OrderedTableRef[A,B],A,B>`_
  1629. ## * `mgetOrPut proc<#mgetOrPut,OrderedTableRef[A,B],A,B>`_
  1630. ## * `del proc<#del,OrderedTableRef[A,B],A>`_ for removing a key from the table
  1631. runnableExamples:
  1632. var a = newOrderedTable[char, int]()
  1633. a['x'] = 7
  1634. a['y'] = 33
  1635. doAssert a == {'x': 7, 'y': 33}.newOrderedTable
  1636. t[][key] = val
  1637. proc hasKey*[A, B](t: OrderedTableRef[A, B], key: A): bool =
  1638. ## Returns true if ``key`` is in the table ``t``.
  1639. ##
  1640. ## See also:
  1641. ## * `contains proc<#contains,OrderedTableRef[A,B],A>`_ for use with the `in`
  1642. ## operator
  1643. ## * `[] proc<#[],OrderedTableRef[A,B],A>`_ for retrieving a value of a key
  1644. ## * `getOrDefault proc<#getOrDefault,OrderedTableRef[A,B],A>`_ to return
  1645. ## a default value (e.g. zero for int) if the key doesn't exist
  1646. ## * `getOrDefault proc<#getOrDefault,OrderedTableRef[A,B],A,B>`_ to return
  1647. ## a custom value if the key doesn't exist
  1648. runnableExamples:
  1649. let a = {'a': 5, 'b': 9}.newOrderedTable
  1650. doAssert a.hasKey('a') == true
  1651. doAssert a.hasKey('z') == false
  1652. result = t[].hasKey(key)
  1653. proc contains*[A, B](t: OrderedTableRef[A, B], key: A): bool =
  1654. ## Alias of `hasKey proc<#hasKey,OrderedTableRef[A,B],A>`_ for use with
  1655. ## the ``in`` operator.
  1656. runnableExamples:
  1657. let a = {'a': 5, 'b': 9}.newOrderedTable
  1658. doAssert 'b' in a == true
  1659. doAssert a.contains('z') == false
  1660. return hasKey[A, B](t, key)
  1661. proc hasKeyOrPut*[A, B](t: var OrderedTableRef[A, B], key: A, val: B): bool =
  1662. ## Returns true if ``key`` is in the table, otherwise inserts ``value``.
  1663. ##
  1664. ## See also:
  1665. ## * `hasKey proc<#hasKey,OrderedTableRef[A,B],A>`_
  1666. ## * `[] proc<#[],OrderedTableRef[A,B],A>`_ for retrieving a value of a key
  1667. ## * `getOrDefault proc<#getOrDefault,OrderedTableRef[A,B],A>`_ to return
  1668. ## a default value (e.g. zero for int) if the key doesn't exist
  1669. ## * `getOrDefault proc<#getOrDefault,OrderedTableRef[A,B],A,B>`_ to return
  1670. ## a custom value if the key doesn't exist
  1671. runnableExamples:
  1672. var a = {'a': 5, 'b': 9}.newOrderedTable
  1673. if a.hasKeyOrPut('a', 50):
  1674. a['a'] = 99
  1675. if a.hasKeyOrPut('z', 50):
  1676. a['z'] = 99
  1677. doAssert a == {'a': 99, 'b': 9, 'z': 50}.newOrderedTable
  1678. result = t[].hasKeyOrPut(key, val)
  1679. proc getOrDefault*[A, B](t: OrderedTableRef[A, B], key: A): B =
  1680. ## Retrieves the value at ``t[key]`` if ``key`` is in ``t``. Otherwise, the
  1681. ## default initialization value for type ``B`` is returned (e.g. 0 for any
  1682. ## integer type).
  1683. ##
  1684. ## See also:
  1685. ## * `[] proc<#[],OrderedTableRef[A,B],A>`_ for retrieving a value of a key
  1686. ## * `hasKey proc<#hasKey,OrderedTableRef[A,B],A>`_
  1687. ## * `hasKeyOrPut proc<#hasKeyOrPut,OrderedTableRef[A,B],A,B>`_
  1688. ## * `mgetOrPut proc<#mgetOrPut,OrderedTableRef[A,B],A,B>`_
  1689. ## * `getOrDefault proc<#getOrDefault,OrderedTableRef[A,B],A,B>`_ to return
  1690. ## a custom value if the key doesn't exist
  1691. runnableExamples:
  1692. let a = {'a': 5, 'b': 9}.newOrderedTable
  1693. doAssert a.getOrDefault('a') == 5
  1694. doAssert a.getOrDefault('z') == 0
  1695. getOrDefault(t[], key)
  1696. proc getOrDefault*[A, B](t: OrderedTableRef[A, B], key: A, default: B): B =
  1697. ## Retrieves the value at ``t[key]`` if ``key`` is in ``t``.
  1698. ## Otherwise, ``default`` is returned.
  1699. ##
  1700. ## See also:
  1701. ## * `[] proc<#[],OrderedTableRef[A,B],A>`_ for retrieving a value of a key
  1702. ## * `hasKey proc<#hasKey,OrderedTableRef[A,B],A>`_
  1703. ## * `hasKeyOrPut proc<#hasKeyOrPut,OrderedTableRef[A,B],A,B>`_
  1704. ## * `mgetOrPut proc<#mgetOrPut,OrderedTableRef[A,B],A,B>`_
  1705. ## * `getOrDefault proc<#getOrDefault,OrderedTableRef[A,B],A>`_ to return
  1706. ## a default value (e.g. zero for int) if the key doesn't exist
  1707. runnableExamples:
  1708. let a = {'a': 5, 'b': 9}.newOrderedTable
  1709. doAssert a.getOrDefault('a', 99) == 5
  1710. doAssert a.getOrDefault('z', 99) == 99
  1711. getOrDefault(t[], key, default)
  1712. proc mgetOrPut*[A, B](t: OrderedTableRef[A, B], key: A, val: B): var B =
  1713. ## Retrieves value at ``t[key]`` or puts ``val`` if not present, either way
  1714. ## returning a value which can be modified.
  1715. ##
  1716. ## See also:
  1717. ## * `[] proc<#[],OrderedTableRef[A,B],A>`_ for retrieving a value of a key
  1718. ## * `hasKey proc<#hasKey,OrderedTableRef[A,B],A>`_
  1719. ## * `hasKeyOrPut proc<#hasKeyOrPut,OrderedTableRef[A,B],A,B>`_
  1720. ## * `getOrDefault proc<#getOrDefault,OrderedTableRef[A,B],A>`_ to return
  1721. ## a default value (e.g. zero for int) if the key doesn't exist
  1722. ## * `getOrDefault proc<#getOrDefault,OrderedTableRef[A,B],A,B>`_ to return
  1723. ## a custom value if the key doesn't exist
  1724. runnableExamples:
  1725. var a = {'a': 5, 'b': 9}.newOrderedTable
  1726. doAssert a.mgetOrPut('a', 99) == 5
  1727. doAssert a.mgetOrPut('z', 99) == 99
  1728. doAssert a == {'a': 5, 'b': 9, 'z': 99}.newOrderedTable
  1729. result = t[].mgetOrPut(key, val)
  1730. proc len*[A, B](t: OrderedTableRef[A, B]): int {.inline.} =
  1731. ## Returns the number of keys in ``t``.
  1732. runnableExamples:
  1733. let a = {'a': 5, 'b': 9}.newOrderedTable
  1734. doAssert len(a) == 2
  1735. result = t.counter
  1736. proc add*[A, B](t: OrderedTableRef[A, B], key: A, val: B) =
  1737. ## Puts a new ``(key, value)`` pair into ``t`` even if ``t[key]`` already exists.
  1738. ##
  1739. ## **This can introduce duplicate keys into the table!**
  1740. ##
  1741. ## Use `[]= proc<#[]=,OrderedTableRef[A,B],A,B>`_ for inserting a new
  1742. ## (key, value) pair in the table without introducing duplicates.
  1743. t[].add(key, val)
  1744. proc del*[A, B](t: var OrderedTableRef[A, B], key: A) =
  1745. ## Deletes ``key`` from hash table ``t``. Does nothing if the key does not exist.
  1746. ##
  1747. ## See also:
  1748. ## * `clear proc<#clear,OrderedTableRef[A,B]>`_ to empty the whole table
  1749. runnableExamples:
  1750. var a = {'a': 5, 'b': 9, 'c': 13}.newOrderedTable
  1751. a.del('a')
  1752. doAssert a == {'b': 9, 'c': 13}.newOrderedTable
  1753. a.del('z')
  1754. doAssert a == {'b': 9, 'c': 13}.newOrderedTable
  1755. t[].del(key)
  1756. proc clear*[A, B](t: var OrderedTableRef[A, B]) =
  1757. ## Resets the table so that it is empty.
  1758. ##
  1759. ## See also:
  1760. ## * `del proc<#del,OrderedTable[A,B],A>`_
  1761. runnableExamples:
  1762. var a = {'a': 5, 'b': 9, 'c': 13}.newOrderedTable
  1763. doAssert len(a) == 3
  1764. clear(a)
  1765. doAssert len(a) == 0
  1766. clear(t[])
  1767. proc sort*[A, B](t: OrderedTableRef[A, B], cmp: proc (x, y: (A, B)): int,
  1768. order = SortOrder.Ascending) =
  1769. ## Sorts ``t`` according to the function ``cmp``.
  1770. ##
  1771. ## This modifies the internal list
  1772. ## that kept the insertion order, so insertion order is lost after this
  1773. ## call but key lookup and insertions remain possible after ``sort`` (in
  1774. ## contrast to the `sort proc<#sort,CountTableRef[A]>`_ for count tables).
  1775. runnableExamples:
  1776. import algorithm
  1777. var a = newOrderedTable[char, int]()
  1778. for i, c in "cab":
  1779. a[c] = 10*i
  1780. doAssert a == {'c': 0, 'a': 10, 'b': 20}.newOrderedTable
  1781. a.sort(system.cmp)
  1782. doAssert a == {'a': 10, 'b': 20, 'c': 0}.newOrderedTable
  1783. a.sort(system.cmp, order = SortOrder.Descending)
  1784. doAssert a == {'c': 0, 'b': 20, 'a': 10}.newOrderedTable
  1785. t[].sort(cmp, order = order)
  1786. proc `$`*[A, B](t: OrderedTableRef[A, B]): string =
  1787. ## The ``$`` operator for hash tables. Used internally when calling `echo`
  1788. ## on a table.
  1789. dollarImpl()
  1790. proc `==`*[A, B](s, t: OrderedTableRef[A, B]): bool =
  1791. ## The ``==`` operator for ordered hash tables. Returns true if either both
  1792. ## tables are ``nil``, or neither is ``nil`` and the content and the order of
  1793. ## both are equal.
  1794. runnableExamples:
  1795. let
  1796. a = {'a': 5, 'b': 9, 'c': 13}.newOrderedTable
  1797. b = {'b': 9, 'c': 13, 'a': 5}.newOrderedTable
  1798. doAssert a != b
  1799. if isNil(s): result = isNil(t)
  1800. elif isNil(t): result = false
  1801. else: result = s[] == t[]
  1802. iterator pairs*[A, B](t: OrderedTableRef[A, B]): (A, B) =
  1803. ## Iterates over any ``(key, value)`` pair in the table ``t`` in insertion
  1804. ## order.
  1805. ##
  1806. ## See also:
  1807. ## * `mpairs iterator<#mpairs.i,OrderedTableRef[A,B]>`_
  1808. ## * `keys iterator<#keys.i,OrderedTableRef[A,B]>`_
  1809. ## * `values iterator<#values.i,OrderedTableRef[A,B]>`_
  1810. ##
  1811. ## **Examples:**
  1812. ##
  1813. ## .. code-block::
  1814. ## let a = {
  1815. ## 'o': [1, 5, 7, 9],
  1816. ## 'e': [2, 4, 6, 8]
  1817. ## }.newOrderedTable
  1818. ##
  1819. ## for k, v in a.pairs:
  1820. ## echo "key: ", k
  1821. ## echo "value: ", v
  1822. ##
  1823. ## # key: o
  1824. ## # value: [1, 5, 7, 9]
  1825. ## # key: e
  1826. ## # value: [2, 4, 6, 8]
  1827. let L = len(t)
  1828. forAllOrderedPairs:
  1829. yield (t.data[h].key, t.data[h].val)
  1830. assert(len(t) == L, "the length of the table changed while iterating over it")
  1831. iterator mpairs*[A, B](t: OrderedTableRef[A, B]): (A, var B) =
  1832. ## Iterates over any ``(key, value)`` pair in the table ``t`` in insertion
  1833. ## order. The values can be modified.
  1834. ##
  1835. ## See also:
  1836. ## * `pairs iterator<#pairs.i,OrderedTableRef[A,B]>`_
  1837. ## * `mvalues iterator<#mvalues.i,OrderedTableRef[A,B]>`_
  1838. runnableExamples:
  1839. let a = {
  1840. 'o': @[1, 5, 7, 9],
  1841. 'e': @[2, 4, 6, 8]
  1842. }.newOrderedTable
  1843. for k, v in a.mpairs:
  1844. v.add(v[0] + 10)
  1845. doAssert a == {'o': @[1, 5, 7, 9, 11],
  1846. 'e': @[2, 4, 6, 8, 12]}.newOrderedTable
  1847. let L = len(t)
  1848. forAllOrderedPairs:
  1849. yield (t.data[h].key, t.data[h].val)
  1850. assert(len(t) == L, "the length of the table changed while iterating over it")
  1851. iterator keys*[A, B](t: OrderedTableRef[A, B]): A =
  1852. ## Iterates over any key in the table ``t`` in insertion order.
  1853. ##
  1854. ## See also:
  1855. ## * `pairs iterator<#pairs.i,OrderedTableRef[A,B]>`_
  1856. ## * `values iterator<#values.i,OrderedTableRef[A,B]>`_
  1857. runnableExamples:
  1858. let a = {
  1859. 'o': @[1, 5, 7, 9],
  1860. 'e': @[2, 4, 6, 8]
  1861. }.newOrderedTable
  1862. for k in a.keys:
  1863. a[k].add(99)
  1864. doAssert a == {'o': @[1, 5, 7, 9, 99], 'e': @[2, 4, 6, 8,
  1865. 99]}.newOrderedTable
  1866. let L = len(t)
  1867. forAllOrderedPairs:
  1868. yield t.data[h].key
  1869. assert(len(t) == L, "the length of the table changed while iterating over it")
  1870. iterator values*[A, B](t: OrderedTableRef[A, B]): B =
  1871. ## Iterates over any value in the table ``t`` in insertion order.
  1872. ##
  1873. ## See also:
  1874. ## * `pairs iterator<#pairs.i,OrderedTableRef[A,B]>`_
  1875. ## * `keys iterator<#keys.i,OrderedTableRef[A,B]>`_
  1876. ## * `mvalues iterator<#mvalues.i,OrderedTableRef[A,B]>`_
  1877. runnableExamples:
  1878. let a = {
  1879. 'o': @[1, 5, 7, 9],
  1880. 'e': @[2, 4, 6, 8]
  1881. }.newOrderedTable
  1882. for v in a.values:
  1883. doAssert v.len == 4
  1884. let L = len(t)
  1885. forAllOrderedPairs:
  1886. yield t.data[h].val
  1887. assert(len(t) == L, "the length of the table changed while iterating over it")
  1888. iterator mvalues*[A, B](t: OrderedTableRef[A, B]): var B =
  1889. ## Iterates over any value in the table ``t`` in insertion order. The values
  1890. ## can be modified.
  1891. ##
  1892. ## See also:
  1893. ## * `mpairs iterator<#mpairs.i,OrderedTableRef[A,B]>`_
  1894. ## * `values iterator<#values.i,OrderedTableRef[A,B]>`_
  1895. runnableExamples:
  1896. let a = {
  1897. 'o': @[1, 5, 7, 9],
  1898. 'e': @[2, 4, 6, 8]
  1899. }.newOrderedTable
  1900. for v in a.mvalues:
  1901. v.add(99)
  1902. doAssert a == {'o': @[1, 5, 7, 9, 99],
  1903. 'e': @[2, 4, 6, 8, 99]}.newOrderedTable
  1904. let L = len(t)
  1905. forAllOrderedPairs:
  1906. yield t.data[h].val
  1907. assert(len(t) == L, "the length of the table changed while iterating over it")
  1908. # -------------------------------------------------------------------------
  1909. # ------------------------------ CountTable -------------------------------
  1910. # -------------------------------------------------------------------------
  1911. type
  1912. CountTable*[A] = object
  1913. ## Hash table that counts the number of each key.
  1914. ##
  1915. ## For creating an empty CountTable, use `initCountTable proc
  1916. ## <#initCountTable,int>`_.
  1917. data: seq[tuple[key: A, val: int]]
  1918. counter: int
  1919. isSorted: bool
  1920. CountTableRef*[A] = ref CountTable[A] ## Ref version of
  1921. ## `CountTable<#CountTable>`_.
  1922. ##
  1923. ## For creating a new empty CountTableRef, use `newCountTable proc
  1924. ## <#newCountTable,int>`_.
  1925. # ------------------------------ helpers ---------------------------------
  1926. proc ctRawInsert[A](t: CountTable[A], data: var seq[tuple[key: A, val: int]],
  1927. key: A, val: int) =
  1928. var h: Hash = hash(key) and high(data)
  1929. while data[h].val != 0: h = nextTry(h, high(data))
  1930. data[h].key = key
  1931. data[h].val = val
  1932. proc enlarge[A](t: var CountTable[A]) =
  1933. var n: seq[tuple[key: A, val: int]]
  1934. newSeq(n, len(t.data) * growthFactor)
  1935. for i in countup(0, high(t.data)):
  1936. if t.data[i].val != 0: ctRawInsert(t, n, t.data[i].key, t.data[i].val)
  1937. swap(t.data, n)
  1938. proc remove[A](t: var CountTable[A], key: A) =
  1939. var n: seq[tuple[key: A, val: int]]
  1940. newSeq(n, len(t.data))
  1941. var removed: bool
  1942. for i in countup(0, high(t.data)):
  1943. if t.data[i].val != 0:
  1944. if t.data[i].key != key:
  1945. ctRawInsert(t, n, t.data[i].key, t.data[i].val)
  1946. else:
  1947. removed = true
  1948. swap(t.data, n)
  1949. if removed: dec(t.counter)
  1950. proc rawGet[A](t: CountTable[A], key: A): int =
  1951. if t.data.len == 0:
  1952. return -1
  1953. var h: Hash = hash(key) and high(t.data) # start with real hash value
  1954. while t.data[h].val != 0:
  1955. if t.data[h].key == key: return h
  1956. h = nextTry(h, high(t.data))
  1957. result = -1 - h # < 0 => MISSING; insert idx = -1 - result
  1958. template ctget(t, key, default: untyped): untyped =
  1959. var index = rawGet(t, key)
  1960. result = if index >= 0: t.data[index].val else: default
  1961. proc inc*[A](t: var CountTable[A], key: A, val: Positive = 1)
  1962. # ----------------------------------------------------------------------
  1963. proc initCountTable*[A](initialSize = defaultInitialSize): CountTable[A] =
  1964. ## Creates a new count table that is empty.
  1965. ##
  1966. ## ``initialSize`` must be a power of two (default: 64).
  1967. ## If you need to accept runtime values for this you could use the
  1968. ## `nextPowerOfTwo proc<math.html#nextPowerOfTwo,int>`_ from the
  1969. ## `math module<math.html>`_ or the `rightSize proc<#rightSize,Natural>`_
  1970. ## from this module.
  1971. ##
  1972. ## Starting from Nim v0.20, tables are initialized by default and it is
  1973. ## not necessary to call this function explicitly.
  1974. ##
  1975. ## See also:
  1976. ## * `toCountTable proc<#toCountTable,openArray[A]>`_
  1977. ## * `newCountTable proc<#newCountTable,int>`_ for creating a
  1978. ## `CountTableRef`
  1979. initImpl(result, initialSize)
  1980. proc toCountTable*[A](keys: openArray[A]): CountTable[A] =
  1981. ## Creates a new count table with every member of a container ``keys``
  1982. ## having a count of how many times it occurs in that container.
  1983. result = initCountTable[A](rightSize(keys.len))
  1984. for key in items(keys): result.inc(key)
  1985. proc `[]`*[A](t: CountTable[A], key: A): int =
  1986. ## Retrieves the value at ``t[key]`` if ``key`` is in ``t``.
  1987. ## Otherwise ``0`` is returned.
  1988. ##
  1989. ## See also:
  1990. ## * `getOrDefault<#getOrDefault,CountTable[A],A,int>`_ to return
  1991. ## a custom value if the key doesn't exist
  1992. ## * `mget proc<#mget,CountTable[A],A>`_
  1993. ## * `[]= proc<#[]%3D,CountTable[A],A,int>`_ for inserting a new
  1994. ## (key, value) pair in the table
  1995. ## * `hasKey proc<#hasKey,CountTable[A],A>`_ for checking if a key
  1996. ## is in the table
  1997. assert(not t.isSorted, "CountTable must not be used after sorting")
  1998. ctget(t, key, 0)
  1999. proc `[]=`*[A](t: var CountTable[A], key: A, val: int) =
  2000. ## Inserts a ``(key, value)`` pair into ``t``.
  2001. ##
  2002. ## See also:
  2003. ## * `[] proc<#[],CountTable[A],A>`_ for retrieving a value of a key
  2004. ## * `inc proc<#inc,CountTable[A],A,Positive>`_ for incrementing a
  2005. ## value of a key
  2006. assert(not t.isSorted, "CountTable must not be used after sorting")
  2007. assert val >= 0
  2008. if val == 0:
  2009. t.remove(key)
  2010. else:
  2011. let h = rawGet(t, key)
  2012. if h >= 0:
  2013. t.data[h].val = val
  2014. else:
  2015. insertImpl()
  2016. proc inc*[A](t: var CountTable[A], key: A, val: Positive = 1) =
  2017. ## Increments ``t[key]`` by ``val`` (default: 1).
  2018. ##
  2019. ## ``val`` must be a positive number. If you need to decrement a value,
  2020. ## use a regular ``Table`` instead.
  2021. runnableExamples:
  2022. var a = toCountTable("aab")
  2023. a.inc('a')
  2024. a.inc('b', 10)
  2025. doAssert a == toCountTable("aaabbbbbbbbbbb")
  2026. assert(not t.isSorted, "CountTable must not be used after sorting")
  2027. var index = rawGet(t, key)
  2028. if index >= 0:
  2029. inc(t.data[index].val, val)
  2030. if t.data[index].val == 0: dec(t.counter)
  2031. else:
  2032. insertImpl()
  2033. proc smallest*[A](t: CountTable[A]): tuple[key: A, val: int] =
  2034. ## Returns the ``(key, value)`` pair with the smallest ``val``. Efficiency: O(n)
  2035. ##
  2036. ## See also:
  2037. ## * `largest proc<#largest,CountTable[A]>`_
  2038. assert t.len > 0
  2039. var minIdx = -1
  2040. for h in 0 .. high(t.data):
  2041. if t.data[h].val > 0 and (minIdx == -1 or t.data[minIdx].val > t.data[h].val):
  2042. minIdx = h
  2043. result.key = t.data[minIdx].key
  2044. result.val = t.data[minIdx].val
  2045. proc largest*[A](t: CountTable[A]): tuple[key: A, val: int] =
  2046. ## Returns the ``(key, value)`` pair with the largest ``val``. Efficiency: O(n)
  2047. ##
  2048. ## See also:
  2049. ## * `smallest proc<#smallest,CountTable[A]>`_
  2050. assert t.len > 0
  2051. var maxIdx = 0
  2052. for h in 1 .. high(t.data):
  2053. if t.data[maxIdx].val < t.data[h].val: maxIdx = h
  2054. result.key = t.data[maxIdx].key
  2055. result.val = t.data[maxIdx].val
  2056. proc hasKey*[A](t: CountTable[A], key: A): bool =
  2057. ## Returns true if ``key`` is in the table ``t``.
  2058. ##
  2059. ## See also:
  2060. ## * `contains proc<#contains,CountTable[A],A>`_ for use with the `in`
  2061. ## operator
  2062. ## * `[] proc<#[],CountTable[A],A>`_ for retrieving a value of a key
  2063. ## * `getOrDefault proc<#getOrDefault,CountTable[A],A,int>`_ to return
  2064. ## a custom value if the key doesn't exist
  2065. assert(not t.isSorted, "CountTable must not be used after sorting")
  2066. result = rawGet(t, key) >= 0
  2067. proc contains*[A](t: CountTable[A], key: A): bool =
  2068. ## Alias of `hasKey proc<#hasKey,CountTable[A],A>`_ for use with
  2069. ## the ``in`` operator.
  2070. return hasKey[A](t, key)
  2071. proc getOrDefault*[A](t: CountTable[A], key: A; default: int = 0): int =
  2072. ## Retrieves the value at ``t[key]`` if``key`` is in ``t``. Otherwise, the
  2073. ## integer value of ``default`` is returned.
  2074. ##
  2075. ## See also:
  2076. ## * `[] proc<#[],CountTable[A],A>`_ for retrieving a value of a key
  2077. ## * `hasKey proc<#hasKey,CountTable[A],A>`_ for checking if a key
  2078. ## is in the table
  2079. ctget(t, key, default)
  2080. proc len*[A](t: CountTable[A]): int =
  2081. ## Returns the number of keys in ``t``.
  2082. result = t.counter
  2083. proc clear*[A](t: var CountTable[A]) =
  2084. ## Resets the table so that it is empty.
  2085. clearImpl()
  2086. t.isSorted = false
  2087. func ctCmp[T](a, b: tuple[key: T, val: int]): int =
  2088. result = system.cmp(a.val, b.val)
  2089. proc sort*[A](t: var CountTable[A], order = SortOrder.Descending) =
  2090. ## Sorts the count table so that, by default, the entry with the
  2091. ## highest counter comes first.
  2092. ##
  2093. ## **WARNING:** This is destructive! Once sorted, you must not modify ``t`` afterwards!
  2094. ##
  2095. ## You can use the iterators `pairs<#pairs.i,CountTable[A]>`_,
  2096. ## `keys<#keys.i,CountTable[A]>`_, and `values<#values.i,CountTable[A]>`_
  2097. ## to iterate over ``t`` in the sorted order.
  2098. runnableExamples:
  2099. import algorithm, sequtils
  2100. var a = toCountTable("abracadabra")
  2101. doAssert a == "aaaaabbrrcd".toCountTable
  2102. a.sort()
  2103. doAssert toSeq(a.values) == @[5, 2, 2, 1, 1]
  2104. a.sort(SortOrder.Ascending)
  2105. doAssert toSeq(a.values) == @[1, 1, 2, 2, 5]
  2106. t.data.sort(cmp = ctCmp, order = order)
  2107. t.isSorted = true
  2108. proc merge*[A](s: var CountTable[A], t: CountTable[A]) =
  2109. ## Merges the second table into the first one (must be declared as `var`).
  2110. runnableExamples:
  2111. var a = toCountTable("aaabbc")
  2112. let b = toCountTable("bcc")
  2113. a.merge(b)
  2114. doAssert a == toCountTable("aaabbbccc")
  2115. assert(not s.isSorted, "CountTable must not be used after sorting")
  2116. for key, value in t:
  2117. s.inc(key, value)
  2118. proc merge*[A](s, t: CountTable[A]): CountTable[A] =
  2119. ## Merges the two tables into a new one.
  2120. runnableExamples:
  2121. let
  2122. a = toCountTable("aaabbc")
  2123. b = toCountTable("bcc")
  2124. doAssert merge(a, b) == toCountTable("aaabbbccc")
  2125. result = initCountTable[A](nextPowerOfTwo(max(s.len, t.len)))
  2126. for table in @[s, t]:
  2127. for key, value in table:
  2128. result.inc(key, value)
  2129. proc `$`*[A](t: CountTable[A]): string =
  2130. ## The ``$`` operator for count tables. Used internally when calling `echo`
  2131. ## on a table.
  2132. dollarImpl()
  2133. proc `==`*[A](s, t: CountTable[A]): bool =
  2134. ## The ``==`` operator for count tables. Returns ``true`` if both tables
  2135. ## contain the same keys with the same count. Insert order does not matter.
  2136. equalsImpl(s, t)
  2137. iterator pairs*[A](t: CountTable[A]): (A, int) =
  2138. ## Iterates over any ``(key, value)`` pair in the table ``t``.
  2139. ##
  2140. ## See also:
  2141. ## * `mpairs iterator<#mpairs.i,CountTable[A]>`_
  2142. ## * `keys iterator<#keys.i,CountTable[A]>`_
  2143. ## * `values iterator<#values.i,CountTable[A]>`_
  2144. ##
  2145. ## **Examples:**
  2146. ##
  2147. ## .. code-block::
  2148. ## let a = toCountTable("abracadabra")
  2149. ##
  2150. ## for k, v in pairs(a):
  2151. ## echo "key: ", k
  2152. ## echo "value: ", v
  2153. ##
  2154. ## # key: a
  2155. ## # value: 5
  2156. ## # key: b
  2157. ## # value: 2
  2158. ## # key: c
  2159. ## # value: 1
  2160. ## # key: d
  2161. ## # value: 1
  2162. ## # key: r
  2163. ## # value: 2
  2164. let L = len(t)
  2165. for h in 0 .. high(t.data):
  2166. if t.data[h].val != 0:
  2167. yield (t.data[h].key, t.data[h].val)
  2168. assert(len(t) == L, "the length of the table changed while iterating over it")
  2169. iterator mpairs*[A](t: var CountTable[A]): (A, var int) =
  2170. ## Iterates over any ``(key, value)`` pair in the table ``t`` (must be
  2171. ## declared as `var`). The values can be modified.
  2172. ##
  2173. ## See also:
  2174. ## * `pairs iterator<#pairs.i,CountTable[A]>`_
  2175. ## * `mvalues iterator<#mvalues.i,CountTable[A]>`_
  2176. runnableExamples:
  2177. var a = toCountTable("abracadabra")
  2178. for k, v in mpairs(a):
  2179. v = 2
  2180. doAssert a == toCountTable("aabbccddrr")
  2181. let L = len(t)
  2182. for h in 0 .. high(t.data):
  2183. if t.data[h].val != 0:
  2184. yield (t.data[h].key, t.data[h].val)
  2185. assert(len(t) == L, "the length of the table changed while iterating over it")
  2186. iterator keys*[A](t: CountTable[A]): A =
  2187. ## Iterates over any key in the table ``t``.
  2188. ##
  2189. ## See also:
  2190. ## * `pairs iterator<#pairs.i,CountTable[A]>`_
  2191. ## * `values iterator<#values.i,CountTable[A]>`_
  2192. runnableExamples:
  2193. var a = toCountTable("abracadabra")
  2194. for k in keys(a):
  2195. a[k] = 2
  2196. doAssert a == toCountTable("aabbccddrr")
  2197. let L = len(t)
  2198. for h in 0 .. high(t.data):
  2199. if t.data[h].val != 0:
  2200. yield t.data[h].key
  2201. assert(len(t) == L, "the length of the table changed while iterating over it")
  2202. iterator values*[A](t: CountTable[A]): int =
  2203. ## Iterates over any value in the table ``t``.
  2204. ##
  2205. ## See also:
  2206. ## * `pairs iterator<#pairs.i,CountTable[A]>`_
  2207. ## * `keys iterator<#keys.i,CountTable[A]>`_
  2208. ## * `mvalues iterator<#mvalues.i,CountTable[A]>`_
  2209. runnableExamples:
  2210. let a = toCountTable("abracadabra")
  2211. for v in values(a):
  2212. assert v < 10
  2213. let L = len(t)
  2214. for h in 0 .. high(t.data):
  2215. if t.data[h].val != 0:
  2216. yield t.data[h].val
  2217. assert(len(t) == L, "the length of the table changed while iterating over it")
  2218. iterator mvalues*[A](t: var CountTable[A]): var int =
  2219. ## Iterates over any value in the table ``t`` (must be
  2220. ## declared as `var`). The values can be modified.
  2221. ##
  2222. ## See also:
  2223. ## * `mpairs iterator<#mpairs.i,CountTable[A]>`_
  2224. ## * `values iterator<#values.i,CountTable[A]>`_
  2225. runnableExamples:
  2226. var a = toCountTable("abracadabra")
  2227. for v in mvalues(a):
  2228. v = 2
  2229. doAssert a == toCountTable("aabbccddrr")
  2230. let L = len(t)
  2231. for h in 0 .. high(t.data):
  2232. if t.data[h].val != 0:
  2233. yield t.data[h].val
  2234. assert(len(t) == L, "the length of the table changed while iterating over it")
  2235. # ---------------------------------------------------------------------------
  2236. # ---------------------------- CountTableRef --------------------------------
  2237. # ---------------------------------------------------------------------------
  2238. proc inc*[A](t: CountTableRef[A], key: A, val = 1)
  2239. proc newCountTable*[A](initialSize = defaultInitialSize): <//>CountTableRef[A] =
  2240. ## Creates a new ref count table that is empty.
  2241. ##
  2242. ## ``initialSize`` must be a power of two (default: 64).
  2243. ## If you need to accept runtime values for this you could use the
  2244. ## `nextPowerOfTwo proc<math.html#nextPowerOfTwo,int>`_ from the
  2245. ## `math module<math.html>`_ or the `rightSize proc<#rightSize,Natural>`_
  2246. ## from this module.
  2247. ##
  2248. ## See also:
  2249. ## * `newCountTable proc<#newCountTable,openArray[A]>`_ for creating
  2250. ## a `CountTableRef` from a collection
  2251. ## * `initCountTable proc<#initCountTable,int>`_ for creating a
  2252. ## `CountTable`
  2253. new(result)
  2254. result[] = initCountTable[A](initialSize)
  2255. proc newCountTable*[A](keys: openArray[A]): <//>CountTableRef[A] =
  2256. ## Creates a new ref count table with every member of a container ``keys``
  2257. ## having a count of how many times it occurs in that container.
  2258. result = newCountTable[A](rightSize(keys.len))
  2259. for key in items(keys): result.inc(key)
  2260. proc `[]`*[A](t: CountTableRef[A], key: A): int =
  2261. ## Retrieves the value at ``t[key]`` if ``key`` is in ``t``.
  2262. ## Otherwise ``0`` is returned.
  2263. ##
  2264. ## See also:
  2265. ## * `getOrDefault<#getOrDefault,CountTableRef[A],A,int>`_ to return
  2266. ## a custom value if the key doesn't exist
  2267. ## * `inc proc<#inc,CountTableRef[A],A>`_ to inc even if missing
  2268. ## * `[]= proc<#[]%3D,CountTableRef[A],A,int>`_ for inserting a new
  2269. ## (key, value) pair in the table
  2270. ## * `hasKey proc<#hasKey,CountTableRef[A],A>`_ for checking if a key
  2271. ## is in the table
  2272. result = t[][key]
  2273. proc `[]=`*[A](t: CountTableRef[A], key: A, val: int) =
  2274. ## Inserts a ``(key, value)`` pair into ``t``.
  2275. ##
  2276. ## See also:
  2277. ## * `[] proc<#[],CountTableRef[A],A>`_ for retrieving a value of a key
  2278. ## * `inc proc<#inc,CountTableRef[A],A,int>`_ for incrementing a
  2279. ## value of a key
  2280. assert val > 0
  2281. t[][key] = val
  2282. proc inc*[A](t: CountTableRef[A], key: A, val = 1) =
  2283. ## Increments ``t[key]`` by ``val`` (default: 1).
  2284. runnableExamples:
  2285. var a = newCountTable("aab")
  2286. a.inc('a')
  2287. a.inc('b', 10)
  2288. doAssert a == newCountTable("aaabbbbbbbbbbb")
  2289. t[].inc(key, val)
  2290. proc smallest*[A](t: CountTableRef[A]): (A, int) =
  2291. ## Returns the ``(key, value)`` pair with the smallest ``val``. Efficiency: O(n)
  2292. ##
  2293. ## See also:
  2294. ## * `largest proc<#largest,CountTableRef[A]>`_
  2295. t[].smallest
  2296. proc largest*[A](t: CountTableRef[A]): (A, int) =
  2297. ## Returns the ``(key, value)`` pair with the largest ``val``. Efficiency: O(n)
  2298. ##
  2299. ## See also:
  2300. ## * `smallest proc<#smallest,CountTable[A]>`_
  2301. t[].largest
  2302. proc hasKey*[A](t: CountTableRef[A], key: A): bool =
  2303. ## Returns true if ``key`` is in the table ``t``.
  2304. ##
  2305. ## See also:
  2306. ## * `contains proc<#contains,CountTableRef[A],A>`_ for use with the `in`
  2307. ## operator
  2308. ## * `[] proc<#[],CountTableRef[A],A>`_ for retrieving a value of a key
  2309. ## * `getOrDefault proc<#getOrDefault,CountTableRef[A],A,int>`_ to return
  2310. ## a custom value if the key doesn't exist
  2311. result = t[].hasKey(key)
  2312. proc contains*[A](t: CountTableRef[A], key: A): bool =
  2313. ## Alias of `hasKey proc<#hasKey,CountTableRef[A],A>`_ for use with
  2314. ## the ``in`` operator.
  2315. return hasKey[A](t, key)
  2316. proc getOrDefault*[A](t: CountTableRef[A], key: A, default: int): int =
  2317. ## Retrieves the value at ``t[key]`` if``key`` is in ``t``. Otherwise, the
  2318. ## integer value of ``default`` is returned.
  2319. ##
  2320. ## See also:
  2321. ## * `[] proc<#[],CountTableRef[A],A>`_ for retrieving a value of a key
  2322. ## * `hasKey proc<#hasKey,CountTableRef[A],A>`_ for checking if a key
  2323. ## is in the table
  2324. result = t[].getOrDefault(key, default)
  2325. proc len*[A](t: CountTableRef[A]): int =
  2326. ## Returns the number of keys in ``t``.
  2327. result = t.counter
  2328. proc clear*[A](t: CountTableRef[A]) =
  2329. ## Resets the table so that it is empty.
  2330. clearImpl()
  2331. proc sort*[A](t: CountTableRef[A], order = SortOrder.Descending) =
  2332. ## Sorts the count table so that, by default, the entry with the
  2333. ## highest counter comes first.
  2334. ##
  2335. ## **This is destructive! You must not modify `t` afterwards!**
  2336. ##
  2337. ## You can use the iterators `pairs<#pairs.i,CountTableRef[A]>`_,
  2338. ## `keys<#keys.i,CountTableRef[A]>`_, and `values<#values.i,CountTableRef[A]>`_
  2339. ## to iterate over ``t`` in the sorted order.
  2340. t[].sort(order = order)
  2341. proc merge*[A](s, t: CountTableRef[A]) =
  2342. ## Merges the second table into the first one.
  2343. runnableExamples:
  2344. let
  2345. a = newCountTable("aaabbc")
  2346. b = newCountTable("bcc")
  2347. a.merge(b)
  2348. doAssert a == newCountTable("aaabbbccc")
  2349. s[].merge(t[])
  2350. proc `$`*[A](t: CountTableRef[A]): string =
  2351. ## The ``$`` operator for count tables. Used internally when calling `echo`
  2352. ## on a table.
  2353. dollarImpl()
  2354. proc `==`*[A](s, t: CountTableRef[A]): bool =
  2355. ## The ``==`` operator for count tables. Returns ``true`` if either both tables
  2356. ## are ``nil``, or neither is ``nil`` and both contain the same keys with the same
  2357. ## count. Insert order does not matter.
  2358. if isNil(s): result = isNil(t)
  2359. elif isNil(t): result = false
  2360. else: result = s[] == t[]
  2361. iterator pairs*[A](t: CountTableRef[A]): (A, int) =
  2362. ## Iterates over any ``(key, value)`` pair in the table ``t``.
  2363. ##
  2364. ## See also:
  2365. ## * `mpairs iterator<#mpairs.i,CountTableRef[A]>`_
  2366. ## * `keys iterator<#keys.i,CountTableRef[A]>`_
  2367. ## * `values iterator<#values.i,CountTableRef[A]>`_
  2368. ##
  2369. ## **Examples:**
  2370. ##
  2371. ## .. code-block::
  2372. ## let a = newCountTable("abracadabra")
  2373. ##
  2374. ## for k, v in pairs(a):
  2375. ## echo "key: ", k
  2376. ## echo "value: ", v
  2377. ##
  2378. ## # key: a
  2379. ## # value: 5
  2380. ## # key: b
  2381. ## # value: 2
  2382. ## # key: c
  2383. ## # value: 1
  2384. ## # key: d
  2385. ## # value: 1
  2386. ## # key: r
  2387. ## # value: 2
  2388. let L = len(t)
  2389. for h in 0 .. high(t.data):
  2390. if t.data[h].val != 0:
  2391. yield (t.data[h].key, t.data[h].val)
  2392. assert(len(t) == L, "the length of the table changed while iterating over it")
  2393. iterator mpairs*[A](t: CountTableRef[A]): (A, var int) =
  2394. ## Iterates over any ``(key, value)`` pair in the table ``t``. The values can
  2395. ## be modified.
  2396. ##
  2397. ## See also:
  2398. ## * `pairs iterator<#pairs.i,CountTableRef[A]>`_
  2399. ## * `mvalues iterator<#mvalues.i,CountTableRef[A]>`_
  2400. runnableExamples:
  2401. let a = newCountTable("abracadabra")
  2402. for k, v in mpairs(a):
  2403. v = 2
  2404. doAssert a == newCountTable("aabbccddrr")
  2405. let L = len(t)
  2406. for h in 0 .. high(t.data):
  2407. if t.data[h].val != 0:
  2408. yield (t.data[h].key, t.data[h].val)
  2409. assert(len(t) == L, "table modified while iterating over it")
  2410. iterator keys*[A](t: CountTableRef[A]): A =
  2411. ## Iterates over any key in the table ``t``.
  2412. ##
  2413. ## See also:
  2414. ## * `pairs iterator<#pairs.i,CountTable[A]>`_
  2415. ## * `values iterator<#values.i,CountTable[A]>`_
  2416. runnableExamples:
  2417. let a = newCountTable("abracadabra")
  2418. for k in keys(a):
  2419. a[k] = 2
  2420. doAssert a == newCountTable("aabbccddrr")
  2421. let L = len(t)
  2422. for h in 0 .. high(t.data):
  2423. if t.data[h].val != 0:
  2424. yield t.data[h].key
  2425. assert(len(t) == L, "the length of the table changed while iterating over it")
  2426. iterator values*[A](t: CountTableRef[A]): int =
  2427. ## Iterates over any value in the table ``t``.
  2428. ##
  2429. ## See also:
  2430. ## * `pairs iterator<#pairs.i,CountTableRef[A]>`_
  2431. ## * `keys iterator<#keys.i,CountTableRef[A]>`_
  2432. ## * `mvalues iterator<#mvalues.i,CountTableRef[A]>`_
  2433. runnableExamples:
  2434. let a = newCountTable("abracadabra")
  2435. for v in values(a):
  2436. assert v < 10
  2437. let L = len(t)
  2438. for h in 0 .. high(t.data):
  2439. if t.data[h].val != 0:
  2440. yield t.data[h].val
  2441. assert(len(t) == L, "the length of the table changed while iterating over it")
  2442. iterator mvalues*[A](t: CountTableRef[A]): var int =
  2443. ## Iterates over any value in the table ``t``. The values can be modified.
  2444. ##
  2445. ## See also:
  2446. ## * `mpairs iterator<#mpairs.i,CountTableRef[A]>`_
  2447. ## * `values iterator<#values.i,CountTableRef[A]>`_
  2448. runnableExamples:
  2449. var a = newCountTable("abracadabra")
  2450. for v in mvalues(a):
  2451. v = 2
  2452. doAssert a == newCountTable("aabbccddrr")
  2453. let L = len(t)
  2454. for h in 0 .. high(t.data):
  2455. if t.data[h].val != 0:
  2456. yield t.data[h].val
  2457. assert(len(t) == L, "the length of the table changed while iterating over it")
  2458. when isMainModule:
  2459. type
  2460. Person = object
  2461. firstName, lastName: string
  2462. proc hash(x: Person): Hash =
  2463. ## Piggyback on the already available string hash proc.
  2464. ##
  2465. ## Without this proc nothing works!
  2466. result = x.firstName.hash !& x.lastName.hash
  2467. result = !$result
  2468. var
  2469. salaries = initTable[Person, int]()
  2470. p1, p2: Person
  2471. p1.firstName = "Jon"
  2472. p1.lastName = "Ross"
  2473. salaries[p1] = 30_000
  2474. p2.firstName = "소진"
  2475. p2.lastName = "박"
  2476. salaries[p2] = 45_000
  2477. var
  2478. s2 = initOrderedTable[Person, int]()
  2479. s3 = initCountTable[Person]()
  2480. s2[p1] = 30_000
  2481. s2[p2] = 45_000
  2482. s3[p1] = 30_000
  2483. s3[p2] = 45_000
  2484. block: # Ordered table should preserve order after deletion
  2485. var
  2486. s4 = initOrderedTable[int, int]()
  2487. s4[1] = 1
  2488. s4[2] = 2
  2489. s4[3] = 3
  2490. var prev = 0
  2491. for i in s4.values:
  2492. doAssert(prev < i)
  2493. prev = i
  2494. s4.del(2)
  2495. doAssert(2 notin s4)
  2496. doAssert(s4.len == 2)
  2497. prev = 0
  2498. for i in s4.values:
  2499. doAssert(prev < i)
  2500. prev = i
  2501. block: # Deletion from OrderedTable should account for collision groups. See issue #5057.
  2502. # The bug is reproducible only with exact keys
  2503. const key1 = "boy_jackpot.inGamma"
  2504. const key2 = "boy_jackpot.outBlack"
  2505. var t = {
  2506. key1: 0,
  2507. key2: 0
  2508. }.toOrderedTable()
  2509. t.del(key1)
  2510. assert(t.len == 1)
  2511. assert(key2 in t)
  2512. var
  2513. t1 = initCountTable[string]()
  2514. t2 = initCountTable[string]()
  2515. t1.inc("foo")
  2516. t1.inc("bar", 2)
  2517. t1.inc("baz", 3)
  2518. t2.inc("foo", 4)
  2519. t2.inc("bar")
  2520. t2.inc("baz", 11)
  2521. merge(t1, t2)
  2522. assert(t1["foo"] == 5)
  2523. assert(t1["bar"] == 3)
  2524. assert(t1["baz"] == 14)
  2525. let
  2526. t1r = newCountTable[string]()
  2527. t2r = newCountTable[string]()
  2528. t1r.inc("foo")
  2529. t1r.inc("bar", 2)
  2530. t1r.inc("baz", 3)
  2531. t2r.inc("foo", 4)
  2532. t2r.inc("bar")
  2533. t2r.inc("baz", 11)
  2534. merge(t1r, t2r)
  2535. assert(t1r["foo"] == 5)
  2536. assert(t1r["bar"] == 3)
  2537. assert(t1r["baz"] == 14)
  2538. var
  2539. t1l = initCountTable[string]()
  2540. t2l = initCountTable[string]()
  2541. t1l.inc("foo")
  2542. t1l.inc("bar", 2)
  2543. t1l.inc("baz", 3)
  2544. t2l.inc("foo", 4)
  2545. t2l.inc("bar")
  2546. t2l.inc("baz", 11)
  2547. let
  2548. t1merging = t1l
  2549. t2merging = t2l
  2550. let merged = merge(t1merging, t2merging)
  2551. assert(merged["foo"] == 5)
  2552. assert(merged["bar"] == 3)
  2553. assert(merged["baz"] == 14)
  2554. block:
  2555. const testKey = "TESTKEY"
  2556. let t: CountTableRef[string] = newCountTable[string]()
  2557. # Before, does not compile with error message:
  2558. #test_counttable.nim(7, 43) template/generic instantiation from here
  2559. #lib/pure/collections/tables.nim(117, 21) template/generic instantiation from here
  2560. #lib/pure/collections/tableimpl.nim(32, 27) Error: undeclared field: 'hcode
  2561. doAssert 0 == t[testKey]
  2562. t.inc(testKey, 3)
  2563. doAssert 3 == t[testKey]
  2564. block:
  2565. # Clear tests
  2566. var clearTable = newTable[int, string]()
  2567. clearTable[42] = "asd"
  2568. clearTable[123123] = "piuyqwb "
  2569. doAssert clearTable[42] == "asd"
  2570. clearTable.clear()
  2571. doAssert(not clearTable.hasKey(123123))
  2572. doAssert clearTable.getOrDefault(42) == ""
  2573. block: #5482
  2574. var a = [("wrong?", "foo"), ("wrong?", "foo2")].newOrderedTable()
  2575. var b = newOrderedTable[string, string](initialSize = 2)
  2576. b.add("wrong?", "foo")
  2577. b.add("wrong?", "foo2")
  2578. assert a == b
  2579. block: #5482
  2580. var a = {"wrong?": "foo", "wrong?": "foo2"}.newOrderedTable()
  2581. var b = newOrderedTable[string, string](initialSize = 2)
  2582. b.add("wrong?", "foo")
  2583. b.add("wrong?", "foo2")
  2584. assert a == b
  2585. block: #5487
  2586. var a = {"wrong?": "foo", "wrong?": "foo2"}.newOrderedTable()
  2587. var b = newOrderedTable[string, string]() # notice, default size!
  2588. b.add("wrong?", "foo")
  2589. b.add("wrong?", "foo2")
  2590. assert a == b
  2591. block: #5487
  2592. var a = [("wrong?", "foo"), ("wrong?", "foo2")].newOrderedTable()
  2593. var b = newOrderedTable[string, string]() # notice, default size!
  2594. b.add("wrong?", "foo")
  2595. b.add("wrong?", "foo2")
  2596. assert a == b
  2597. block:
  2598. var a = {"wrong?": "foo", "wrong?": "foo2"}.newOrderedTable()
  2599. var b = [("wrong?", "foo"), ("wrong?", "foo2")].newOrderedTable()
  2600. var c = newOrderedTable[string, string]() # notice, default size!
  2601. c.add("wrong?", "foo")
  2602. c.add("wrong?", "foo2")
  2603. assert a == b
  2604. assert a == c
  2605. block: #6250
  2606. let
  2607. a = {3: 1}.toOrderedTable
  2608. b = {3: 2}.toOrderedTable
  2609. assert((a == b) == false)
  2610. assert((b == a) == false)
  2611. block: #6250
  2612. let
  2613. a = {3: 2}.toOrderedTable
  2614. b = {3: 2}.toOrderedTable
  2615. assert((a == b) == true)
  2616. assert((b == a) == true)
  2617. block: # CountTable.smallest
  2618. let t = toCountTable([0, 0, 5, 5, 5])
  2619. doAssert t.smallest == (0, 2)
  2620. block: #10065
  2621. let t = toCountTable("abracadabra")
  2622. doAssert t['z'] == 0
  2623. var t_mut = toCountTable("abracadabra")
  2624. doAssert t_mut['z'] == 0
  2625. # the previous read may not have modified the table.
  2626. doAssert t_mut.hasKey('z') == false
  2627. t_mut['z'] = 1
  2628. doAssert t_mut['z'] == 1
  2629. doAssert t_mut.hasKey('z') == true
  2630. block: #12813 #13079
  2631. var t = toCountTable("abracadabra")
  2632. doAssert len(t) == 5
  2633. t['a'] = 0 # remove a key
  2634. doAssert len(t) == 4
  2635. block:
  2636. var tp: Table[string, string] = initTable[string, string]()
  2637. doAssert "test1" == tp.getOrDefault("test1", "test1")
  2638. tp["test2"] = "test2"
  2639. doAssert "test2" == tp.getOrDefault("test2", "test1")
  2640. var tr: TableRef[string, string] = newTable[string, string]()
  2641. doAssert "test1" == tr.getOrDefault("test1", "test1")
  2642. tr["test2"] = "test2"
  2643. doAssert "test2" == tr.getOrDefault("test2", "test1")
  2644. var op: OrderedTable[string, string] = initOrderedTable[string, string]()
  2645. doAssert "test1" == op.getOrDefault("test1", "test1")
  2646. op["test2"] = "test2"
  2647. doAssert "test2" == op.getOrDefault("test2", "test1")
  2648. var orf: OrderedTableRef[string, string] = newOrderedTable[string, string]()
  2649. doAssert "test1" == orf.getOrDefault("test1", "test1")
  2650. orf["test2"] = "test2"
  2651. doAssert "test2" == orf.getOrDefault("test2", "test1")
  2652. block tableWithoutInit:
  2653. var
  2654. a: Table[string, int]
  2655. b: Table[string, int]
  2656. c: Table[string, int]
  2657. d: Table[string, int]
  2658. e: Table[string, int]
  2659. a["a"] = 7
  2660. doAssert a.hasKey("a")
  2661. doAssert a.len == 1
  2662. doAssert a["a"] == 7
  2663. a["a"] = 9
  2664. doAssert a.len == 1
  2665. doAssert a["a"] == 9
  2666. doAssert b.hasKeyOrPut("b", 5) == false
  2667. doAssert b.hasKey("b")
  2668. doAssert b.hasKeyOrPut("b", 8)
  2669. doAssert b["b"] == 5
  2670. doAssert c.getOrDefault("a") == 0
  2671. doAssert c.getOrDefault("a", 3) == 3
  2672. c["a"] = 6
  2673. doAssert c.getOrDefault("a", 3) == 6
  2674. doAssert d.mgetOrPut("a", 3) == 3
  2675. doAssert d.mgetOrPut("a", 6) == 3
  2676. var x = 99
  2677. doAssert e.take("a", x) == false
  2678. doAssert x == 99
  2679. e["a"] = 77
  2680. doAssert e.take("a", x)
  2681. doAssert x == 77
  2682. block orderedTableWithoutInit:
  2683. var
  2684. a: OrderedTable[string, int]
  2685. b: OrderedTable[string, int]
  2686. c: OrderedTable[string, int]
  2687. d: OrderedTable[string, int]
  2688. a["a"] = 7
  2689. doAssert a.hasKey("a")
  2690. doAssert a.len == 1
  2691. doAssert a["a"] == 7
  2692. a["a"] = 9
  2693. doAssert a.len == 1
  2694. doAssert a["a"] == 9
  2695. doAssert b.hasKeyOrPut("b", 5) == false
  2696. doAssert b.hasKey("b")
  2697. doAssert b.hasKeyOrPut("b", 8)
  2698. doAssert b["b"] == 5
  2699. doAssert c.getOrDefault("a") == 0
  2700. doAssert c.getOrDefault("a", 3) == 3
  2701. c["a"] = 6
  2702. doAssert c.getOrDefault("a", 3) == 6
  2703. doAssert d.mgetOrPut("a", 3) == 3
  2704. doAssert d.mgetOrPut("a", 6) == 3
  2705. block countTableWithoutInit:
  2706. var
  2707. a: CountTable[string]
  2708. b: CountTable[string]
  2709. c: CountTable[string]
  2710. d: CountTable[string]
  2711. e: CountTable[string]
  2712. a["a"] = 7
  2713. doAssert a.hasKey("a")
  2714. doAssert a.len == 1
  2715. doAssert a["a"] == 7
  2716. a["a"] = 9
  2717. doAssert a.len == 1
  2718. doAssert a["a"] == 9
  2719. doAssert b["b"] == 0
  2720. b.inc("b")
  2721. doAssert b["b"] == 1
  2722. doAssert c.getOrDefault("a") == 0
  2723. doAssert c.getOrDefault("a", 3) == 3
  2724. c["a"] = 6
  2725. doAssert c.getOrDefault("a", 3) == 6
  2726. e["f"] = 3
  2727. merge(d, e)
  2728. doAssert d.hasKey("f")
  2729. d.inc("f")
  2730. merge(d, e)
  2731. doAssert d["f"] == 7