tables.nim 96 KB

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