tables.nim 94 KB

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