tables.nim 102 KB

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