tables.nim 94 KB

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