tables.nim 94 KB

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