12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894 |
- #
- #
- # Nim's Runtime Library
- # (c) Copyright 2015 Andreas Rumpf
- #
- # See the file "copying.txt", included in this
- # distribution, for details about the copyright.
- #
- ## The `tables` module implements variants of an efficient `hash table`:idx:
- ## (also often named `dictionary`:idx: in other programming languages) that is
- ## a mapping from keys to values.
- ##
- ## There are several different types of hash tables available:
- ## * `Table<#Table>`_ is the usual hash table,
- ## * `OrderedTable<#OrderedTable>`_ is like `Table` but remembers insertion order,
- ## * `CountTable<#CountTable>`_ is a mapping from a key to its number of occurrences
- ##
- ## For consistency with every other data type in Nim these have **value**
- ## semantics, this means that `=` performs a copy of the hash table.
- ##
- ## For `ref semantics<manual.html#types-reference-and-pointer-types>`_
- ## use their `Ref` variants: `TableRef<#TableRef>`_,
- ## `OrderedTableRef<#OrderedTableRef>`_, and `CountTableRef<#CountTableRef>`_.
- ##
- ## To give an example, when `a` is a `Table`, then `var b = a` gives `b`
- ## as a new independent table. `b` is initialised with the contents of `a`.
- ## Changing `b` does not affect `a` and vice versa:
- runnableExamples:
- var
- a = {1: "one", 2: "two"}.toTable # creates a Table
- b = a
- assert a == b
- b[3] = "three"
- assert 3 notin a
- assert 3 in b
- assert a != b
- ## On the other hand, when `a` is a `TableRef` instead, then changes to `b`
- ## also affect `a`. Both `a` and `b` **ref** the same data structure:
- runnableExamples:
- var
- a = {1: "one", 2: "two"}.newTable # creates a TableRef
- b = a
- assert a == b
- b[3] = "three"
- assert 3 in a
- assert 3 in b
- assert a == b
- ##
- ## ----
- ##
- ## # Basic usage
- ## ## Table
- runnableExamples:
- from std/sequtils import zip
- let
- names = ["John", "Paul", "George", "Ringo"]
- years = [1940, 1942, 1943, 1940]
- var beatles = initTable[string, int]()
- for pairs in zip(names, years):
- let (name, birthYear) = pairs
- beatles[name] = birthYear
- assert beatles == {"George": 1943, "Ringo": 1940, "Paul": 1942, "John": 1940}.toTable
- var beatlesByYear = initTable[int, seq[string]]()
- for pairs in zip(years, names):
- let (birthYear, name) = pairs
- if not beatlesByYear.hasKey(birthYear):
- # if a key doesn't exist, we create one with an empty sequence
- # before we can add elements to it
- beatlesByYear[birthYear] = @[]
- beatlesByYear[birthYear].add(name)
- assert beatlesByYear == {1940: @["John", "Ringo"], 1942: @["Paul"], 1943: @["George"]}.toTable
- ## ## OrderedTable
- ## `OrderedTable<#OrderedTable>`_ is used when it is important to preserve
- ## the insertion order of keys.
- runnableExamples:
- let
- a = [('z', 1), ('y', 2), ('x', 3)]
- ot = a.toOrderedTable # ordered tables
- assert $ot == """{'z': 1, 'y': 2, 'x': 3}"""
- ## ## CountTable
- ## `CountTable<#CountTable>`_ is useful for counting number of items of some
- ## container (e.g. string, sequence or array), as it is a mapping where the
- ## items are the keys, and their number of occurrences are the values.
- ## For that purpose `toCountTable proc<#toCountTable,openArray[A]>`_
- ## comes handy:
- runnableExamples:
- let myString = "abracadabra"
- let letterFrequencies = toCountTable(myString)
- assert $letterFrequencies == "{'a': 5, 'd': 1, 'b': 2, 'r': 2, 'c': 1}"
- ## The same could have been achieved by manually iterating over a container
- ## and increasing each key's value with `inc proc
- ## <#inc,CountTable[A],A,int>`_:
- runnableExamples:
- let myString = "abracadabra"
- var letterFrequencies = initCountTable[char]()
- for c in myString:
- letterFrequencies.inc(c)
- assert $letterFrequencies == "{'d': 1, 'r': 2, 'c': 1, 'a': 5, 'b': 2}"
- ##
- ## ----
- ##
- ## ## Hashing
- ##
- ## If you are using simple standard types like `int` or `string` for the
- ## keys of the table you won't have any problems, but as soon as you try to use
- ## a more complex object as a key you will be greeted by a strange compiler
- ## error:
- ##
- ## .. code::
- ##
- ## Error: type mismatch: got (Person)
- ## but expected one of:
- ## hashes.hash(x: openArray[A]): Hash
- ## hashes.hash(x: int): Hash
- ## hashes.hash(x: float): Hash
- ## …
- ##
- ## What is happening here is that the types used for table keys require to have
- ## a `hash()` proc which will convert them to a `Hash <hashes.html#Hash>`_
- ## value, and the compiler is listing all the hash functions it knows.
- ## Additionally there has to be a `==` operator that provides the same
- ## semantics as its corresponding `hash` proc.
- ##
- ## After you add `hash` and `==` for your custom type everything will work.
- ## Currently, however, `hash` for objects is not defined, whereas
- ## `system.==` for objects does exist and performs a "deep" comparison (every
- ## field is compared) which is usually what you want. So in the following
- ## example implementing only `hash` suffices:
- runnableExamples:
- import std/hashes
- type
- Person = object
- firstName, lastName: string
- proc hash(x: Person): Hash =
- ## Piggyback on the already available string hash proc.
- ##
- ## Without this proc nothing works!
- result = x.firstName.hash !& x.lastName.hash
- result = !$result
- var
- salaries = initTable[Person, int]()
- p1, p2: Person
- p1.firstName = "Jon"
- p1.lastName = "Ross"
- salaries[p1] = 30_000
- p2.firstName = "소진"
- p2.lastName = "박"
- salaries[p2] = 45_000
- ##
- ## ----
- ##
- ## # See also
- ##
- ## * `json module<json.html>`_ for table-like structure which allows
- ## heterogeneous members
- ## * `sharedtables module<sharedtables.html>`_ for shared hash table support
- ## * `strtabs module<strtabs.html>`_ for efficient hash tables
- ## mapping from strings to strings
- ## * `hashes module<hashes.html>`_ for helper functions for hashing
- import std/private/since
- import hashes, math, algorithm
- type
- KeyValuePair[A, B] = tuple[hcode: Hash, key: A, val: B]
- KeyValuePairSeq[A, B] = seq[KeyValuePair[A, B]]
- Table*[A, B] = object
- ## Generic hash table, consisting of a key-value pair.
- ##
- ## `data` and `counter` are internal implementation details which
- ## can't be accessed.
- ##
- ## For creating an empty Table, use `initTable proc<#initTable>`_.
- data: KeyValuePairSeq[A, B]
- counter: int
- TableRef*[A, B] = ref Table[A, B] ## Ref version of `Table<#Table>`_.
- ##
- ## For creating a new empty TableRef, use `newTable proc
- ## <#newTable>`_.
- const
- defaultInitialSize* = 32
- # ------------------------------ helpers ---------------------------------
- # Do NOT move these to tableimpl.nim, because sharedtables uses that
- # file and has its own implementation.
- template maxHash(t): untyped = high(t.data)
- template dataLen(t): untyped = len(t.data)
- include tableimpl
- proc raiseKeyError[T](key: T) {.noinline, noreturn.} =
- when compiles($key):
- raise newException(KeyError, "key not found: " & $key)
- else:
- raise newException(KeyError, "key not found")
- template get(t, key): untyped =
- ## retrieves the value at `t[key]`. The value can be modified.
- ## If `key` is not in `t`, the `KeyError` exception is raised.
- mixin rawGet
- var hc: Hash
- var index = rawGet(t, key, hc)
- if index >= 0: result = t.data[index].val
- else:
- raiseKeyError(key)
- proc enlarge[A, B](t: var Table[A, B]) =
- var n: KeyValuePairSeq[A, B]
- newSeq(n, len(t.data) * growthFactor)
- swap(t.data, n)
- for i in countup(0, high(n)):
- let eh = n[i].hcode
- if isFilled(eh):
- var j: Hash = eh and maxHash(t)
- while isFilled(t.data[j].hcode):
- j = nextTry(j, maxHash(t))
- when defined(js):
- rawInsert(t, t.data, n[i].key, n[i].val, eh, j)
- else:
- rawInsert(t, t.data, move n[i].key, move n[i].val, eh, j)
- # -------------------------------------------------------------------
- # ------------------------------ Table ------------------------------
- # -------------------------------------------------------------------
- proc initTable*[A, B](initialSize = defaultInitialSize): Table[A, B] =
- ## Creates a new hash table that is empty.
- ##
- ## Starting from Nim v0.20, tables are initialized by default and it is
- ## not necessary to call this function explicitly.
- ##
- ## See also:
- ## * `toTable proc<#toTable,openArray[]>`_
- ## * `newTable proc<#newTable>`_ for creating a `TableRef`
- runnableExamples:
- let
- a = initTable[int, string]()
- b = initTable[char, seq[int]]()
- initImpl(result, initialSize)
- proc `[]=`*[A, B](t: var Table[A, B], key: A, val: sink B) =
- ## Inserts a `(key, value)` pair into `t`.
- ##
- ## See also:
- ## * `[] proc<#[],Table[A,B],A>`_ for retrieving a value of a key
- ## * `hasKeyOrPut proc<#hasKeyOrPut,Table[A,B],A,B>`_
- ## * `mgetOrPut proc<#mgetOrPut,Table[A,B],A,B>`_
- ## * `del proc<#del,Table[A,B],A>`_ for removing a key from the table
- runnableExamples:
- var a = initTable[char, int]()
- a['x'] = 7
- a['y'] = 33
- doAssert a == {'x': 7, 'y': 33}.toTable
- putImpl(enlarge)
- proc toTable*[A, B](pairs: openArray[(A, B)]): Table[A, B] =
- ## Creates a new hash table that contains the given `pairs`.
- ##
- ## `pairs` is a container consisting of `(key, value)` tuples.
- ##
- ## See also:
- ## * `initTable proc<#initTable>`_
- ## * `newTable proc<#newTable,openArray[]>`_ for a `TableRef` version
- runnableExamples:
- let a = [('a', 5), ('b', 9)]
- let b = toTable(a)
- assert b == {'a': 5, 'b': 9}.toTable
- result = initTable[A, B](pairs.len)
- for key, val in items(pairs): result[key] = val
- proc `[]`*[A, B](t: Table[A, B], key: A): B =
- ## Retrieves the value at `t[key]`.
- ##
- ## If `key` is not in `t`, the `KeyError` exception is raised.
- ## One can check with `hasKey proc<#hasKey,Table[A,B],A>`_ whether
- ## the key exists.
- ##
- ## See also:
- ## * `getOrDefault proc<#getOrDefault,Table[A,B],A>`_ to return
- ## a default value (e.g. zero for int) if the key doesn't exist
- ## * `getOrDefault proc<#getOrDefault,Table[A,B],A,B>`_ to return
- ## a custom value if the key doesn't exist
- ## * `[]= proc<#[]=,Table[A,B],A,sinkB>`_ for inserting a new
- ## (key, value) pair in the table
- ## * `hasKey proc<#hasKey,Table[A,B],A>`_ for checking if a key is in
- ## the table
- runnableExamples:
- let a = {'a': 5, 'b': 9}.toTable
- doAssert a['a'] == 5
- doAssertRaises(KeyError):
- echo a['z']
- get(t, key)
- proc `[]`*[A, B](t: var Table[A, B], key: A): var B =
- ## Retrieves the value at `t[key]`. The value can be modified.
- ##
- ## If `key` is not in `t`, the `KeyError` exception is raised.
- ##
- ## See also:
- ## * `getOrDefault proc<#getOrDefault,Table[A,B],A>`_ to return
- ## a default value (e.g. zero for int) if the key doesn't exist
- ## * `getOrDefault proc<#getOrDefault,Table[A,B],A,B>`_ to return
- ## a custom value if the key doesn't exist
- ## * `[]= proc<#[]=,Table[A,B],A,sinkB>`_ for inserting a new
- ## (key, value) pair in the table
- ## * `hasKey proc<#hasKey,Table[A,B],A>`_ for checking if a key is in
- ## the table
- get(t, key)
- proc hasKey*[A, B](t: Table[A, B], key: A): bool =
- ## Returns true if `key` is in the table `t`.
- ##
- ## See also:
- ## * `contains proc<#contains,Table[A,B],A>`_ for use with the `in` operator
- ## * `[] proc<#[],Table[A,B],A>`_ for retrieving a value of a key
- ## * `getOrDefault proc<#getOrDefault,Table[A,B],A>`_ to return
- ## a default value (e.g. zero for int) if the key doesn't exist
- ## * `getOrDefault proc<#getOrDefault,Table[A,B],A,B>`_ to return
- ## a custom value if the key doesn't exist
- runnableExamples:
- let a = {'a': 5, 'b': 9}.toTable
- doAssert a.hasKey('a') == true
- doAssert a.hasKey('z') == false
- var hc: Hash
- result = rawGet(t, key, hc) >= 0
- proc contains*[A, B](t: Table[A, B], key: A): bool =
- ## Alias of `hasKey proc<#hasKey,Table[A,B],A>`_ for use with
- ## the `in` operator.
- runnableExamples:
- let a = {'a': 5, 'b': 9}.toTable
- doAssert 'b' in a == true
- doAssert a.contains('z') == false
- return hasKey[A, B](t, key)
- proc hasKeyOrPut*[A, B](t: var Table[A, B], key: A, val: B): bool =
- ## Returns true if `key` is in the table, otherwise inserts `value`.
- ##
- ## See also:
- ## * `hasKey proc<#hasKey,Table[A,B],A>`_
- ## * `[] proc<#[],Table[A,B],A>`_ for retrieving a value of a key
- ## * `getOrDefault proc<#getOrDefault,Table[A,B],A>`_ to return
- ## a default value (e.g. zero for int) if the key doesn't exist
- ## * `getOrDefault proc<#getOrDefault,Table[A,B],A,B>`_ to return
- ## a custom value if the key doesn't exist
- runnableExamples:
- var a = {'a': 5, 'b': 9}.toTable
- if a.hasKeyOrPut('a', 50):
- a['a'] = 99
- if a.hasKeyOrPut('z', 50):
- a['z'] = 99
- doAssert a == {'a': 99, 'b': 9, 'z': 50}.toTable
- hasKeyOrPutImpl(enlarge)
- proc getOrDefault*[A, B](t: Table[A, B], key: A): B =
- ## Retrieves the value at `t[key]` if `key` is in `t`. Otherwise, the
- ## default initialization value for type `B` is returned (e.g. 0 for any
- ## integer type).
- ##
- ## See also:
- ## * `[] proc<#[],Table[A,B],A>`_ for retrieving a value of a key
- ## * `hasKey proc<#hasKey,Table[A,B],A>`_
- ## * `hasKeyOrPut proc<#hasKeyOrPut,Table[A,B],A,B>`_
- ## * `mgetOrPut proc<#mgetOrPut,Table[A,B],A,B>`_
- ## * `getOrDefault proc<#getOrDefault,Table[A,B],A,B>`_ to return
- ## a custom value if the key doesn't exist
- runnableExamples:
- let a = {'a': 5, 'b': 9}.toTable
- doAssert a.getOrDefault('a') == 5
- doAssert a.getOrDefault('z') == 0
- getOrDefaultImpl(t, key)
- proc getOrDefault*[A, B](t: Table[A, B], key: A, default: B): B =
- ## Retrieves the value at `t[key]` if `key` is in `t`.
- ## Otherwise, `default` is returned.
- ##
- ## See also:
- ## * `[] proc<#[],Table[A,B],A>`_ for retrieving a value of a key
- ## * `hasKey proc<#hasKey,Table[A,B],A>`_
- ## * `hasKeyOrPut proc<#hasKeyOrPut,Table[A,B],A,B>`_
- ## * `mgetOrPut proc<#mgetOrPut,Table[A,B],A,B>`_
- ## * `getOrDefault proc<#getOrDefault,Table[A,B],A>`_ to return
- ## a default value (e.g. zero for int) if the key doesn't exist
- runnableExamples:
- let a = {'a': 5, 'b': 9}.toTable
- doAssert a.getOrDefault('a', 99) == 5
- doAssert a.getOrDefault('z', 99) == 99
- getOrDefaultImpl(t, key, default)
- proc mgetOrPut*[A, B](t: var Table[A, B], key: A, val: B): var B =
- ## Retrieves value at `t[key]` or puts `val` if not present, either way
- ## returning a value which can be modified.
- ##
- ##
- ## Note that while the value returned is of type `var B`,
- ## it is easy to accidentally create an copy of the value at `t[key]`.
- ## Remember that seqs and strings are value types, and therefore
- ## cannot be copied into a separate variable for modification.
- ## See the example below.
- ##
- ## See also:
- ## * `[] proc<#[],Table[A,B],A>`_ for retrieving a value of a key
- ## * `hasKey proc<#hasKey,Table[A,B],A>`_
- ## * `hasKeyOrPut proc<#hasKeyOrPut,Table[A,B],A,B>`_
- ## * `getOrDefault proc<#getOrDefault,Table[A,B],A>`_ to return
- ## a default value (e.g. zero for int) if the key doesn't exist
- ## * `getOrDefault proc<#getOrDefault,Table[A,B],A,B>`_ to return
- ## a custom value if the key doesn't exist
- runnableExamples:
- var a = {'a': 5, 'b': 9}.toTable
- doAssert a.mgetOrPut('a', 99) == 5
- doAssert a.mgetOrPut('z', 99) == 99
- doAssert a == {'a': 5, 'b': 9, 'z': 99}.toTable
- # An example of accidentally creating a copy
- var t = initTable[int, seq[int]]()
- # In this example, we expect t[10] to be modified,
- # but it is not.
- var copiedSeq = t.mgetOrPut(10, @[10])
- copiedSeq.add(20)
- doAssert t[10] == @[10]
- # Correct
- t.mgetOrPut(25, @[25]).add(35)
- doAssert t[25] == @[25, 35]
- mgetOrPutImpl(enlarge)
- proc len*[A, B](t: Table[A, B]): int =
- ## Returns the number of keys in `t`.
- runnableExamples:
- let a = {'a': 5, 'b': 9}.toTable
- doAssert len(a) == 2
- result = t.counter
- proc add*[A, B](t: var Table[A, B], key: A, val: sink B) {.deprecated:
- "Deprecated since v1.4; it was more confusing than useful, use `[]=`".} =
- ## Puts a new `(key, value)` pair into `t` even if `t[key]` already exists.
- ##
- ## **This can introduce duplicate keys into the table!**
- ##
- ## Use `[]= proc<#[]=,Table[A,B],A,sinkB>`_ for inserting a new
- ## (key, value) pair in the table without introducing duplicates.
- addImpl(enlarge)
- template tabMakeEmpty(i) = t.data[i].hcode = 0
- template tabCellEmpty(i) = isEmpty(t.data[i].hcode)
- template tabCellHash(i) = t.data[i].hcode
- proc del*[A, B](t: var Table[A, B], key: A) =
- ## Deletes `key` from hash table `t`. Does nothing if the key does not exist.
- ##
- ## .. warning:: If duplicate keys were added (via the now deprecated `add` proc),
- ## this may need to be called multiple times.
- ##
- ## See also:
- ## * `pop proc<#pop,Table[A,B],A,B>`_
- ## * `clear proc<#clear,Table[A,B]>`_ to empty the whole table
- runnableExamples:
- var a = {'a': 5, 'b': 9, 'c': 13}.toTable
- a.del('a')
- doAssert a == {'b': 9, 'c': 13}.toTable
- a.del('z')
- doAssert a == {'b': 9, 'c': 13}.toTable
- delImpl(tabMakeEmpty, tabCellEmpty, tabCellHash)
- proc pop*[A, B](t: var Table[A, B], key: A, val: var B): bool =
- ## Deletes the `key` from the table.
- ## Returns `true`, if the `key` existed, and sets `val` to the
- ## mapping of the key. Otherwise, returns `false`, and the `val` is
- ## unchanged.
- ##
- ## .. warning:: If duplicate keys were added (via the now deprecated `add` proc),
- ## this may need to be called multiple times.
- ##
- ## See also:
- ## * `del proc<#del,Table[A,B],A>`_
- ## * `clear proc<#clear,Table[A,B]>`_ to empty the whole table
- runnableExamples:
- var
- a = {'a': 5, 'b': 9, 'c': 13}.toTable
- i: int
- doAssert a.pop('b', i) == true
- doAssert a == {'a': 5, 'c': 13}.toTable
- doAssert i == 9
- i = 0
- doAssert a.pop('z', i) == false
- doAssert a == {'a': 5, 'c': 13}.toTable
- doAssert i == 0
- var hc: Hash
- var index = rawGet(t, key, hc)
- result = index >= 0
- if result:
- val = move(t.data[index].val)
- delImplIdx(t, index, tabMakeEmpty, tabCellEmpty, tabCellHash)
- proc take*[A, B](t: var Table[A, B], key: A, val: var B): bool {.inline.} =
- ## Alias for:
- ## * `pop proc<#pop,Table[A,B],A,B>`_
- pop(t, key, val)
- proc clear*[A, B](t: var Table[A, B]) =
- ## Resets the table so that it is empty.
- ##
- ## See also:
- ## * `del proc<#del,Table[A,B],A>`_
- ## * `pop proc<#pop,Table[A,B],A,B>`_
- runnableExamples:
- var a = {'a': 5, 'b': 9, 'c': 13}.toTable
- doAssert len(a) == 3
- clear(a)
- doAssert len(a) == 0
- clearImpl()
- proc `$`*[A, B](t: Table[A, B]): string =
- ## The `$` operator for hash tables. Used internally when calling `echo`
- ## on a table.
- dollarImpl()
- proc `==`*[A, B](s, t: Table[A, B]): bool =
- ## The `==` operator for hash tables. Returns `true` if the content of both
- ## tables contains the same key-value pairs. Insert order does not matter.
- runnableExamples:
- let
- a = {'a': 5, 'b': 9, 'c': 13}.toTable
- b = {'b': 9, 'c': 13, 'a': 5}.toTable
- doAssert a == b
- equalsImpl(s, t)
- proc indexBy*[A, B, C](collection: A, index: proc(x: B): C): Table[C, B] =
- ## Index the collection with the proc provided.
- # TODO: As soon as supported, change collection: A to collection: A[B]
- result = initTable[C, B]()
- for item in collection:
- result[index(item)] = item
- template withValue*[A, B](t: var Table[A, B], key: A, value, body: untyped) =
- ## Retrieves the value at `t[key]`.
- ##
- ## `value` can be modified in the scope of the `withValue` call.
- runnableExamples:
- type
- User = object
- name: string
- uid: int
- var t = initTable[int, User]()
- let u = User(name: "Hello", uid: 99)
- t[1] = u
- t.withValue(1, value):
- # block is executed only if `key` in `t`
- value.name = "Nim"
- value.uid = 1314
- t.withValue(2, value):
- value.name = "No"
- value.uid = 521
- assert t[1].name == "Nim"
- assert t[1].uid == 1314
- mixin rawGet
- var hc: Hash
- var index = rawGet(t, key, hc)
- let hasKey = index >= 0
- if hasKey:
- var value {.inject.} = addr(t.data[index].val)
- body
- template withValue*[A, B](t: var Table[A, B], key: A,
- value, body1, body2: untyped) =
- ## Retrieves the value at `t[key]`.
- ##
- ## `value` can be modified in the scope of the `withValue` call.
- runnableExamples:
- type
- User = object
- name: string
- uid: int
- var t = initTable[int, User]()
- let u = User(name: "Hello", uid: 99)
- t[1] = u
- t.withValue(1, value):
- # block is executed only if `key` in `t`
- value.name = "Nim"
- value.uid = 1314
- t.withValue(521, value):
- doAssert false
- do:
- # block is executed when `key` not in `t`
- t[1314] = User(name: "exist", uid: 521)
- assert t[1].name == "Nim"
- assert t[1].uid == 1314
- assert t[1314].name == "exist"
- assert t[1314].uid == 521
- mixin rawGet
- var hc: Hash
- var index = rawGet(t, key, hc)
- let hasKey = index >= 0
- if hasKey:
- var value {.inject.} = addr(t.data[index].val)
- body1
- else:
- body2
- iterator pairs*[A, B](t: Table[A, B]): (A, B) =
- ## Iterates over any `(key, value)` pair in the table `t`.
- ##
- ## See also:
- ## * `mpairs iterator<#mpairs.i,Table[A,B]>`_
- ## * `keys iterator<#keys.i,Table[A,B]>`_
- ## * `values iterator<#values.i,Table[A,B]>`_
- ##
- ## **Examples:**
- ##
- ## .. code-block::
- ## let a = {
- ## 'o': [1, 5, 7, 9],
- ## 'e': [2, 4, 6, 8]
- ## }.toTable
- ##
- ## for k, v in a.pairs:
- ## echo "key: ", k
- ## echo "value: ", v
- ##
- ## # key: e
- ## # value: [2, 4, 6, 8]
- ## # key: o
- ## # value: [1, 5, 7, 9]
- let L = len(t)
- for h in 0 .. high(t.data):
- if isFilled(t.data[h].hcode):
- yield (t.data[h].key, t.data[h].val)
- assert(len(t) == L, "the length of the table changed while iterating over it")
- iterator mpairs*[A, B](t: var Table[A, B]): (A, var B) =
- ## Iterates over any `(key, value)` pair in the table `t` (must be
- ## declared as `var`). The values can be modified.
- ##
- ## See also:
- ## * `pairs iterator<#pairs.i,Table[A,B]>`_
- ## * `mvalues iterator<#mvalues.i,Table[A,B]>`_
- runnableExamples:
- var a = {
- 'o': @[1, 5, 7, 9],
- 'e': @[2, 4, 6, 8]
- }.toTable
- for k, v in a.mpairs:
- v.add(v[0] + 10)
- doAssert a == {'e': @[2, 4, 6, 8, 12], 'o': @[1, 5, 7, 9, 11]}.toTable
- let L = len(t)
- for h in 0 .. high(t.data):
- if isFilled(t.data[h].hcode):
- yield (t.data[h].key, t.data[h].val)
- assert(len(t) == L, "the length of the table changed while iterating over it")
- iterator keys*[A, B](t: Table[A, B]): lent A =
- ## Iterates over any key in the table `t`.
- ##
- ## See also:
- ## * `pairs iterator<#pairs.i,Table[A,B]>`_
- ## * `values iterator<#values.i,Table[A,B]>`_
- runnableExamples:
- var a = {
- 'o': @[1, 5, 7, 9],
- 'e': @[2, 4, 6, 8]
- }.toTable
- for k in a.keys:
- a[k].add(99)
- doAssert a == {'e': @[2, 4, 6, 8, 99], 'o': @[1, 5, 7, 9, 99]}.toTable
- let L = len(t)
- for h in 0 .. high(t.data):
- if isFilled(t.data[h].hcode):
- yield t.data[h].key
- assert(len(t) == L, "the length of the table changed while iterating over it")
- iterator values*[A, B](t: Table[A, B]): lent B =
- ## Iterates over any value in the table `t`.
- ##
- ## See also:
- ## * `pairs iterator<#pairs.i,Table[A,B]>`_
- ## * `keys iterator<#keys.i,Table[A,B]>`_
- ## * `mvalues iterator<#mvalues.i,Table[A,B]>`_
- runnableExamples:
- let a = {
- 'o': @[1, 5, 7, 9],
- 'e': @[2, 4, 6, 8]
- }.toTable
- for v in a.values:
- doAssert v.len == 4
- let L = len(t)
- for h in 0 .. high(t.data):
- if isFilled(t.data[h].hcode):
- yield t.data[h].val
- assert(len(t) == L, "the length of the table changed while iterating over it")
- iterator mvalues*[A, B](t: var Table[A, B]): var B =
- ## Iterates over any value in the table `t` (must be
- ## declared as `var`). The values can be modified.
- ##
- ## See also:
- ## * `mpairs iterator<#mpairs.i,Table[A,B]>`_
- ## * `values iterator<#values.i,Table[A,B]>`_
- runnableExamples:
- var a = {
- 'o': @[1, 5, 7, 9],
- 'e': @[2, 4, 6, 8]
- }.toTable
- for v in a.mvalues:
- v.add(99)
- doAssert a == {'e': @[2, 4, 6, 8, 99], 'o': @[1, 5, 7, 9, 99]}.toTable
- let L = len(t)
- for h in 0 .. high(t.data):
- if isFilled(t.data[h].hcode):
- yield t.data[h].val
- assert(len(t) == L, "the length of the table changed while iterating over it")
- iterator allValues*[A, B](t: Table[A, B]; key: A): B {.deprecated:
- "Deprecated since v1.4; tables with duplicated keys are deprecated".} =
- ## Iterates over any value in the table `t` that belongs to the given `key`.
- ##
- ## Used if you have a table with duplicate keys (as a result of using
- ## `add proc<#add,Table[A,B],A,sinkB>`_).
- ##
- runnableExamples:
- import std/[sequtils, algorithm]
- var a = {'a': 3, 'b': 5}.toTable
- for i in 1..3: a.add('z', 10*i)
- doAssert toSeq(a.pairs).sorted == @[('a', 3), ('b', 5), ('z', 10), ('z', 20), ('z', 30)]
- doAssert sorted(toSeq(a.allValues('z'))) == @[10, 20, 30]
- var h: Hash = genHash(key) and high(t.data)
- let L = len(t)
- while isFilled(t.data[h].hcode):
- if t.data[h].key == key:
- yield t.data[h].val
- assert(len(t) == L, "the length of the table changed while iterating over it")
- h = nextTry(h, high(t.data))
- # -------------------------------------------------------------------
- # ---------------------------- TableRef -----------------------------
- # -------------------------------------------------------------------
- proc newTable*[A, B](initialSize = defaultInitialSize): TableRef[A, B] =
- ## Creates a new ref hash table that is empty.
- ##
- ## See also:
- ## * `newTable proc<#newTable,openArray[]>`_ for creating a `TableRef`
- ## from a collection of `(key, value)` pairs
- ## * `initTable proc<#initTable>`_ for creating a `Table`
- runnableExamples:
- let
- a = newTable[int, string]()
- b = newTable[char, seq[int]]()
- new(result)
- result[] = initTable[A, B](initialSize)
- proc newTable*[A, B](pairs: openArray[(A, B)]): TableRef[A, B] =
- ## Creates a new ref hash table that contains the given `pairs`.
- ##
- ## `pairs` is a container consisting of `(key, value)` tuples.
- ##
- ## See also:
- ## * `newTable proc<#newTable>`_
- ## * `toTable proc<#toTable,openArray[]>`_ for a `Table` version
- runnableExamples:
- let a = [('a', 5), ('b', 9)]
- let b = newTable(a)
- assert b == {'a': 5, 'b': 9}.newTable
- new(result)
- result[] = toTable[A, B](pairs)
- proc newTableFrom*[A, B, C](collection: A, index: proc(x: B): C): TableRef[C, B] =
- ## Index the collection with the proc provided.
- # TODO: As soon as supported, change collection: A to collection: A[B]
- result = newTable[C, B]()
- for item in collection:
- result[index(item)] = item
- proc `[]`*[A, B](t: TableRef[A, B], key: A): var B =
- ## Retrieves the value at `t[key]`.
- ##
- ## If `key` is not in `t`, the `KeyError` exception is raised.
- ## One can check with `hasKey proc<#hasKey,TableRef[A,B],A>`_ whether
- ## the key exists.
- ##
- ## See also:
- ## * `getOrDefault proc<#getOrDefault,TableRef[A,B],A>`_ to return
- ## a default value (e.g. zero for int) if the key doesn't exist
- ## * `getOrDefault proc<#getOrDefault,TableRef[A,B],A,B>`_ to return
- ## a custom value if the key doesn't exist
- ## * `[]= proc<#[]=,TableRef[A,B],A,sinkB>`_ for inserting a new
- ## (key, value) pair in the table
- ## * `hasKey proc<#hasKey,TableRef[A,B],A>`_ for checking if a key is in
- ## the table
- runnableExamples:
- let a = {'a': 5, 'b': 9}.newTable
- doAssert a['a'] == 5
- doAssertRaises(KeyError):
- echo a['z']
- result = t[][key]
- proc `[]=`*[A, B](t: TableRef[A, B], key: A, val: sink B) =
- ## Inserts a `(key, value)` pair into `t`.
- ##
- ## See also:
- ## * `[] proc<#[],TableRef[A,B],A>`_ for retrieving a value of a key
- ## * `hasKeyOrPut proc<#hasKeyOrPut,TableRef[A,B],A,B>`_
- ## * `mgetOrPut proc<#mgetOrPut,TableRef[A,B],A,B>`_
- ## * `del proc<#del,TableRef[A,B],A>`_ for removing a key from the table
- runnableExamples:
- var a = newTable[char, int]()
- a['x'] = 7
- a['y'] = 33
- doAssert a == {'x': 7, 'y': 33}.newTable
- t[][key] = val
- proc hasKey*[A, B](t: TableRef[A, B], key: A): bool =
- ## Returns true if `key` is in the table `t`.
- ##
- ## See also:
- ## * `contains proc<#contains,TableRef[A,B],A>`_ for use with the `in`
- ## operator
- ## * `[] proc<#[],TableRef[A,B],A>`_ for retrieving a value of a key
- ## * `getOrDefault proc<#getOrDefault,TableRef[A,B],A>`_ to return
- ## a default value (e.g. zero for int) if the key doesn't exist
- ## * `getOrDefault proc<#getOrDefault,TableRef[A,B],A,B>`_ to return
- ## a custom value if the key doesn't exist
- runnableExamples:
- let a = {'a': 5, 'b': 9}.newTable
- doAssert a.hasKey('a') == true
- doAssert a.hasKey('z') == false
- result = t[].hasKey(key)
- proc contains*[A, B](t: TableRef[A, B], key: A): bool =
- ## Alias of `hasKey proc<#hasKey,TableRef[A,B],A>`_ for use with
- ## the `in` operator.
- runnableExamples:
- let a = {'a': 5, 'b': 9}.newTable
- doAssert 'b' in a == true
- doAssert a.contains('z') == false
- return hasKey[A, B](t, key)
- proc hasKeyOrPut*[A, B](t: var TableRef[A, B], key: A, val: B): bool =
- ## Returns true if `key` is in the table, otherwise inserts `value`.
- ##
- ## See also:
- ## * `hasKey proc<#hasKey,TableRef[A,B],A>`_
- ## * `[] proc<#[],TableRef[A,B],A>`_ for retrieving a value of a key
- ## * `getOrDefault proc<#getOrDefault,TableRef[A,B],A>`_ to return
- ## a default value (e.g. zero for int) if the key doesn't exist
- ## * `getOrDefault proc<#getOrDefault,TableRef[A,B],A,B>`_ to return
- ## a custom value if the key doesn't exist
- runnableExamples:
- var a = {'a': 5, 'b': 9}.newTable
- if a.hasKeyOrPut('a', 50):
- a['a'] = 99
- if a.hasKeyOrPut('z', 50):
- a['z'] = 99
- doAssert a == {'a': 99, 'b': 9, 'z': 50}.newTable
- t[].hasKeyOrPut(key, val)
- proc getOrDefault*[A, B](t: TableRef[A, B], key: A): B =
- ## Retrieves the value at `t[key]` if `key` is in `t`. Otherwise, the
- ## default initialization value for type `B` is returned (e.g. 0 for any
- ## integer type).
- ##
- ## See also:
- ## * `[] proc<#[],TableRef[A,B],A>`_ for retrieving a value of a key
- ## * `hasKey proc<#hasKey,TableRef[A,B],A>`_
- ## * `hasKeyOrPut proc<#hasKeyOrPut,TableRef[A,B],A,B>`_
- ## * `mgetOrPut proc<#mgetOrPut,TableRef[A,B],A,B>`_
- ## * `getOrDefault proc<#getOrDefault,TableRef[A,B],A,B>`_ to return
- ## a custom value if the key doesn't exist
- runnableExamples:
- let a = {'a': 5, 'b': 9}.newTable
- doAssert a.getOrDefault('a') == 5
- doAssert a.getOrDefault('z') == 0
- getOrDefault(t[], key)
- proc getOrDefault*[A, B](t: TableRef[A, B], key: A, default: B): B =
- ## Retrieves the value at `t[key]` if `key` is in `t`.
- ## Otherwise, `default` is returned.
- ##
- ## See also:
- ## * `[] proc<#[],TableRef[A,B],A>`_ for retrieving a value of a key
- ## * `hasKey proc<#hasKey,TableRef[A,B],A>`_
- ## * `hasKeyOrPut proc<#hasKeyOrPut,TableRef[A,B],A,B>`_
- ## * `mgetOrPut proc<#mgetOrPut,TableRef[A,B],A,B>`_
- ## * `getOrDefault proc<#getOrDefault,TableRef[A,B],A>`_ to return
- ## a default value (e.g. zero for int) if the key doesn't exist
- runnableExamples:
- let a = {'a': 5, 'b': 9}.newTable
- doAssert a.getOrDefault('a', 99) == 5
- doAssert a.getOrDefault('z', 99) == 99
- getOrDefault(t[], key, default)
- proc mgetOrPut*[A, B](t: TableRef[A, B], key: A, val: B): var B =
- ## Retrieves value at `t[key]` or puts `val` if not present, either way
- ## returning a value which can be modified.
- ##
- ## Note that while the value returned is of type `var B`,
- ## it is easy to accidentally create an copy of the value at `t[key]`.
- ## Remember that seqs and strings are value types, and therefore
- ## cannot be copied into a separate variable for modification.
- ## See the example below.
- ##
- ## See also:
- ## * `[] proc<#[],TableRef[A,B],A>`_ for retrieving a value of a key
- ## * `hasKey proc<#hasKey,TableRef[A,B],A>`_
- ## * `hasKeyOrPut proc<#hasKeyOrPut,TableRef[A,B],A,B>`_
- ## * `getOrDefault proc<#getOrDefault,TableRef[A,B],A>`_ to return
- ## a default value (e.g. zero for int) if the key doesn't exist
- ## * `getOrDefault proc<#getOrDefault,TableRef[A,B],A,B>`_ to return
- ## a custom value if the key doesn't exist
- runnableExamples:
- var a = {'a': 5, 'b': 9}.newTable
- doAssert a.mgetOrPut('a', 99) == 5
- doAssert a.mgetOrPut('z', 99) == 99
- doAssert a == {'a': 5, 'b': 9, 'z': 99}.newTable
- # An example of accidentally creating a copy
- var t = newTable[int, seq[int]]()
- # In this example, we expect t[10] to be modified,
- # but it is not.
- var copiedSeq = t.mgetOrPut(10, @[10])
- copiedSeq.add(20)
- doAssert t[10] == @[10]
- # Correct
- t.mgetOrPut(25, @[25]).add(35)
- doAssert t[25] == @[25, 35]
- t[].mgetOrPut(key, val)
- proc len*[A, B](t: TableRef[A, B]): int =
- ## Returns the number of keys in `t`.
- runnableExamples:
- let a = {'a': 5, 'b': 9}.newTable
- doAssert len(a) == 2
- result = t.counter
- proc add*[A, B](t: TableRef[A, B], key: A, val: sink B) {.deprecated:
- "Deprecated since v1.4; it was more confusing than useful, use `[]=`".} =
- ## Puts a new `(key, value)` pair into `t` even if `t[key]` already exists.
- ##
- ## **This can introduce duplicate keys into the table!**
- ##
- ## Use `[]= proc<#[]=,TableRef[A,B],A,sinkB>`_ for inserting a new
- ## (key, value) pair in the table without introducing duplicates.
- t[].add(key, val)
- proc del*[A, B](t: TableRef[A, B], key: A) =
- ## Deletes `key` from hash table `t`. Does nothing if the key does not exist.
- ##
- ## .. warning:: If duplicate keys were added (via the now deprecated `add` proc),
- ## this may need to be called multiple times.
- ##
- ## See also:
- ## * `pop proc<#pop,TableRef[A,B],A,B>`_
- ## * `clear proc<#clear,TableRef[A,B]>`_ to empty the whole table
- runnableExamples:
- var a = {'a': 5, 'b': 9, 'c': 13}.newTable
- a.del('a')
- doAssert a == {'b': 9, 'c': 13}.newTable
- a.del('z')
- doAssert a == {'b': 9, 'c': 13}.newTable
- t[].del(key)
- proc pop*[A, B](t: TableRef[A, B], key: A, val: var B): bool =
- ## Deletes the `key` from the table.
- ## Returns `true`, if the `key` existed, and sets `val` to the
- ## mapping of the key. Otherwise, returns `false`, and the `val` is
- ## unchanged.
- ##
- ## .. warning:: If duplicate keys were added (via the now deprecated `add` proc),
- ## this may need to be called multiple times.
- ##
- ## See also:
- ## * `del proc<#del,TableRef[A,B],A>`_
- ## * `clear proc<#clear,TableRef[A,B]>`_ to empty the whole table
- runnableExamples:
- var
- a = {'a': 5, 'b': 9, 'c': 13}.newTable
- i: int
- doAssert a.pop('b', i) == true
- doAssert a == {'a': 5, 'c': 13}.newTable
- doAssert i == 9
- i = 0
- doAssert a.pop('z', i) == false
- doAssert a == {'a': 5, 'c': 13}.newTable
- doAssert i == 0
- result = t[].pop(key, val)
- proc take*[A, B](t: TableRef[A, B], key: A, val: var B): bool {.inline.} =
- ## Alias for:
- ## * `pop proc<#pop,TableRef[A,B],A,B>`_
- pop(t, key, val)
- proc clear*[A, B](t: TableRef[A, B]) =
- ## Resets the table so that it is empty.
- ##
- ## See also:
- ## * `del proc<#del,Table[A,B],A>`_
- ## * `pop proc<#pop,Table[A,B],A,B>`_
- runnableExamples:
- var a = {'a': 5, 'b': 9, 'c': 13}.newTable
- doAssert len(a) == 3
- clear(a)
- doAssert len(a) == 0
- clearImpl()
- proc `$`*[A, B](t: TableRef[A, B]): string =
- ## The `$` operator for hash tables. Used internally when calling `echo`
- ## on a table.
- dollarImpl()
- proc `==`*[A, B](s, t: TableRef[A, B]): bool =
- ## The `==` operator for hash tables. Returns `true` if either both tables
- ## are `nil`, or neither is `nil` and the content of both tables contains the
- ## same key-value pairs. Insert order does not matter.
- runnableExamples:
- let
- a = {'a': 5, 'b': 9, 'c': 13}.newTable
- b = {'b': 9, 'c': 13, 'a': 5}.newTable
- doAssert a == b
- if isNil(s): result = isNil(t)
- elif isNil(t): result = false
- else: equalsImpl(s[], t[])
- iterator pairs*[A, B](t: TableRef[A, B]): (A, B) =
- ## Iterates over any `(key, value)` pair in the table `t`.
- ##
- ## See also:
- ## * `mpairs iterator<#mpairs.i,TableRef[A,B]>`_
- ## * `keys iterator<#keys.i,TableRef[A,B]>`_
- ## * `values iterator<#values.i,TableRef[A,B]>`_
- ##
- ## **Examples:**
- ##
- ## .. code-block::
- ## let a = {
- ## 'o': [1, 5, 7, 9],
- ## 'e': [2, 4, 6, 8]
- ## }.newTable
- ##
- ## for k, v in a.pairs:
- ## echo "key: ", k
- ## echo "value: ", v
- ##
- ## # key: e
- ## # value: [2, 4, 6, 8]
- ## # key: o
- ## # value: [1, 5, 7, 9]
- let L = len(t)
- for h in 0 .. high(t.data):
- if isFilled(t.data[h].hcode):
- yield (t.data[h].key, t.data[h].val)
- assert(len(t) == L, "the length of the table changed while iterating over it")
- iterator mpairs*[A, B](t: TableRef[A, B]): (A, var B) =
- ## Iterates over any `(key, value)` pair in the table `t`. The values
- ## can be modified.
- ##
- ## See also:
- ## * `pairs iterator<#pairs.i,TableRef[A,B]>`_
- ## * `mvalues iterator<#mvalues.i,TableRef[A,B]>`_
- runnableExamples:
- let a = {
- 'o': @[1, 5, 7, 9],
- 'e': @[2, 4, 6, 8]
- }.newTable
- for k, v in a.mpairs:
- v.add(v[0] + 10)
- doAssert a == {'e': @[2, 4, 6, 8, 12], 'o': @[1, 5, 7, 9, 11]}.newTable
- let L = len(t)
- for h in 0 .. high(t.data):
- if isFilled(t.data[h].hcode):
- yield (t.data[h].key, t.data[h].val)
- assert(len(t) == L, "the length of the table changed while iterating over it")
- iterator keys*[A, B](t: TableRef[A, B]): lent A =
- ## Iterates over any key in the table `t`.
- ##
- ## See also:
- ## * `pairs iterator<#pairs.i,TableRef[A,B]>`_
- ## * `values iterator<#values.i,TableRef[A,B]>`_
- runnableExamples:
- let a = {
- 'o': @[1, 5, 7, 9],
- 'e': @[2, 4, 6, 8]
- }.newTable
- for k in a.keys:
- a[k].add(99)
- doAssert a == {'e': @[2, 4, 6, 8, 99], 'o': @[1, 5, 7, 9, 99]}.newTable
- let L = len(t)
- for h in 0 .. high(t.data):
- if isFilled(t.data[h].hcode):
- yield t.data[h].key
- assert(len(t) == L, "the length of the table changed while iterating over it")
- iterator values*[A, B](t: TableRef[A, B]): lent B =
- ## Iterates over any value in the table `t`.
- ##
- ## See also:
- ## * `pairs iterator<#pairs.i,TableRef[A,B]>`_
- ## * `keys iterator<#keys.i,TableRef[A,B]>`_
- ## * `mvalues iterator<#mvalues.i,TableRef[A,B]>`_
- runnableExamples:
- let a = {
- 'o': @[1, 5, 7, 9],
- 'e': @[2, 4, 6, 8]
- }.newTable
- for v in a.values:
- doAssert v.len == 4
- let L = len(t)
- for h in 0 .. high(t.data):
- if isFilled(t.data[h].hcode):
- yield t.data[h].val
- assert(len(t) == L, "the length of the table changed while iterating over it")
- iterator mvalues*[A, B](t: TableRef[A, B]): var B =
- ## Iterates over any value in the table `t`. The values can be modified.
- ##
- ## See also:
- ## * `mpairs iterator<#mpairs.i,TableRef[A,B]>`_
- ## * `values iterator<#values.i,TableRef[A,B]>`_
- runnableExamples:
- let a = {
- 'o': @[1, 5, 7, 9],
- 'e': @[2, 4, 6, 8]
- }.newTable
- for v in a.mvalues:
- v.add(99)
- doAssert a == {'e': @[2, 4, 6, 8, 99], 'o': @[1, 5, 7, 9, 99]}.newTable
- let L = len(t)
- for h in 0 .. high(t.data):
- if isFilled(t.data[h].hcode):
- yield t.data[h].val
- assert(len(t) == L, "the length of the table changed while iterating over it")
- # ---------------------------------------------------------------------------
- # ------------------------------ OrderedTable -------------------------------
- # ---------------------------------------------------------------------------
- type
- OrderedKeyValuePair[A, B] = tuple[
- hcode: Hash, next: int, key: A, val: B]
- OrderedKeyValuePairSeq[A, B] = seq[OrderedKeyValuePair[A, B]]
- OrderedTable*[A, B] = object
- ## Hash table that remembers insertion order.
- ##
- ## For creating an empty OrderedTable, use `initOrderedTable proc
- ## <#initOrderedTable>`_.
- data: OrderedKeyValuePairSeq[A, B]
- counter, first, last: int
- OrderedTableRef*[A, B] = ref OrderedTable[A, B] ## Ref version of
- ## `OrderedTable<#OrderedTable>`_.
- ##
- ## For creating a new empty OrderedTableRef, use `newOrderedTable proc
- ## <#newOrderedTable>`_.
- # ------------------------------ helpers ---------------------------------
- proc rawGetKnownHC[A, B](t: OrderedTable[A, B], key: A, hc: Hash): int =
- rawGetKnownHCImpl()
- proc rawGetDeep[A, B](t: OrderedTable[A, B], key: A, hc: var Hash): int {.inline.} =
- rawGetDeepImpl()
- proc rawGet[A, B](t: OrderedTable[A, B], key: A, hc: var Hash): int =
- rawGetImpl()
- proc rawInsert[A, B](t: var OrderedTable[A, B],
- data: var OrderedKeyValuePairSeq[A, B],
- key: A, val: sink B, hc: Hash, h: Hash) =
- rawInsertImpl()
- data[h].next = -1
- if t.first < 0: t.first = h
- if t.last >= 0: data[t.last].next = h
- t.last = h
- proc enlarge[A, B](t: var OrderedTable[A, B]) =
- var n: OrderedKeyValuePairSeq[A, B]
- newSeq(n, len(t.data) * growthFactor)
- var h = t.first
- t.first = -1
- t.last = -1
- swap(t.data, n)
- while h >= 0:
- var nxt = n[h].next
- let eh = n[h].hcode
- if isFilled(eh):
- var j: Hash = eh and maxHash(t)
- while isFilled(t.data[j].hcode):
- j = nextTry(j, maxHash(t))
- rawInsert(t, t.data, move n[h].key, move n[h].val, n[h].hcode, j)
- h = nxt
- template forAllOrderedPairs(yieldStmt: untyped) {.dirty.} =
- if t.counter > 0:
- var h = t.first
- while h >= 0:
- var nxt = t.data[h].next
- if isFilled(t.data[h].hcode):
- yieldStmt
- h = nxt
- # ----------------------------------------------------------------------
- proc initOrderedTable*[A, B](initialSize = defaultInitialSize): OrderedTable[A, B] =
- ## Creates a new ordered hash table that is empty.
- ##
- ## Starting from Nim v0.20, tables are initialized by default and it is
- ## not necessary to call this function explicitly.
- ##
- ## See also:
- ## * `toOrderedTable proc<#toOrderedTable,openArray[]>`_
- ## * `newOrderedTable proc<#newOrderedTable>`_ for creating an
- ## `OrderedTableRef`
- runnableExamples:
- let
- a = initOrderedTable[int, string]()
- b = initOrderedTable[char, seq[int]]()
- initImpl(result, initialSize)
- proc `[]=`*[A, B](t: var OrderedTable[A, B], key: A, val: sink B) =
- ## Inserts a `(key, value)` pair into `t`.
- ##
- ## See also:
- ## * `[] proc<#[],OrderedTable[A,B],A>`_ for retrieving a value of a key
- ## * `hasKeyOrPut proc<#hasKeyOrPut,OrderedTable[A,B],A,B>`_
- ## * `mgetOrPut proc<#mgetOrPut,OrderedTable[A,B],A,B>`_
- ## * `del proc<#del,OrderedTable[A,B],A>`_ for removing a key from the table
- runnableExamples:
- var a = initOrderedTable[char, int]()
- a['x'] = 7
- a['y'] = 33
- doAssert a == {'x': 7, 'y': 33}.toOrderedTable
- putImpl(enlarge)
- proc toOrderedTable*[A, B](pairs: openArray[(A, B)]): OrderedTable[A, B] =
- ## Creates a new ordered hash table that contains the given `pairs`.
- ##
- ## `pairs` is a container consisting of `(key, value)` tuples.
- ##
- ## See also:
- ## * `initOrderedTable proc<#initOrderedTable>`_
- ## * `newOrderedTable proc<#newOrderedTable,openArray[]>`_ for an
- ## `OrderedTableRef` version
- runnableExamples:
- let a = [('a', 5), ('b', 9)]
- let b = toOrderedTable(a)
- assert b == {'a': 5, 'b': 9}.toOrderedTable
- result = initOrderedTable[A, B](pairs.len)
- for key, val in items(pairs): result[key] = val
- proc `[]`*[A, B](t: OrderedTable[A, B], key: A): B =
- ## Retrieves the value at `t[key]`.
- ##
- ## If `key` is not in `t`, the `KeyError` exception is raised.
- ## One can check with `hasKey proc<#hasKey,OrderedTable[A,B],A>`_ whether
- ## the key exists.
- ##
- ## See also:
- ## * `getOrDefault proc<#getOrDefault,OrderedTable[A,B],A>`_ to return
- ## a default value (e.g. zero for int) if the key doesn't exist
- ## * `getOrDefault proc<#getOrDefault,OrderedTable[A,B],A,B>`_ to return
- ## a custom value if the key doesn't exist
- ## * `[]= proc<#[]=,OrderedTable[A,B],A,sinkB>`_ for inserting a new
- ## (key, value) pair in the table
- ## * `hasKey proc<#hasKey,OrderedTable[A,B],A>`_ for checking if a
- ## key is in the table
- runnableExamples:
- let a = {'a': 5, 'b': 9}.toOrderedTable
- doAssert a['a'] == 5
- doAssertRaises(KeyError):
- echo a['z']
- get(t, key)
- proc `[]`*[A, B](t: var OrderedTable[A, B], key: A): var B =
- ## Retrieves the value at `t[key]`. The value can be modified.
- ##
- ## If `key` is not in `t`, the `KeyError` exception is raised.
- ##
- ## See also:
- ## * `getOrDefault proc<#getOrDefault,OrderedTable[A,B],A>`_ to return
- ## a default value (e.g. zero for int) if the key doesn't exist
- ## * `getOrDefault proc<#getOrDefault,OrderedTable[A,B],A,B>`_ to return
- ## a custom value if the key doesn't exist
- ## * `[]= proc<#[]=,OrderedTable[A,B],A,sinkB>`_ for inserting a new
- ## (key, value) pair in the table
- ## * `hasKey proc<#hasKey,OrderedTable[A,B],A>`_ for checking if a
- ## key is in the table
- get(t, key)
- proc hasKey*[A, B](t: OrderedTable[A, B], key: A): bool =
- ## Returns true if `key` is in the table `t`.
- ##
- ## See also:
- ## * `contains proc<#contains,OrderedTable[A,B],A>`_ for use with the `in`
- ## operator
- ## * `[] proc<#[],OrderedTable[A,B],A>`_ for retrieving a value of a key
- ## * `getOrDefault proc<#getOrDefault,OrderedTable[A,B],A>`_ to return
- ## a default value (e.g. zero for int) if the key doesn't exist
- ## * `getOrDefault proc<#getOrDefault,OrderedTable[A,B],A,B>`_ to return
- ## a custom value if the key doesn't exist
- runnableExamples:
- let a = {'a': 5, 'b': 9}.toOrderedTable
- doAssert a.hasKey('a') == true
- doAssert a.hasKey('z') == false
- var hc: Hash
- result = rawGet(t, key, hc) >= 0
- proc contains*[A, B](t: OrderedTable[A, B], key: A): bool =
- ## Alias of `hasKey proc<#hasKey,OrderedTable[A,B],A>`_ for use with
- ## the `in` operator.
- runnableExamples:
- let a = {'a': 5, 'b': 9}.toOrderedTable
- doAssert 'b' in a == true
- doAssert a.contains('z') == false
- return hasKey[A, B](t, key)
- proc hasKeyOrPut*[A, B](t: var OrderedTable[A, B], key: A, val: B): bool =
- ## Returns true if `key` is in the table, otherwise inserts `value`.
- ##
- ## See also:
- ## * `hasKey proc<#hasKey,OrderedTable[A,B],A>`_
- ## * `[] proc<#[],OrderedTable[A,B],A>`_ for retrieving a value of a key
- ## * `getOrDefault proc<#getOrDefault,OrderedTable[A,B],A>`_ to return
- ## a default value (e.g. zero for int) if the key doesn't exist
- ## * `getOrDefault proc<#getOrDefault,OrderedTable[A,B],A,B>`_ to return
- ## a custom value if the key doesn't exist
- runnableExamples:
- var a = {'a': 5, 'b': 9}.toOrderedTable
- if a.hasKeyOrPut('a', 50):
- a['a'] = 99
- if a.hasKeyOrPut('z', 50):
- a['z'] = 99
- doAssert a == {'a': 99, 'b': 9, 'z': 50}.toOrderedTable
- hasKeyOrPutImpl(enlarge)
- proc getOrDefault*[A, B](t: OrderedTable[A, B], key: A): B =
- ## Retrieves the value at `t[key]` if `key` is in `t`. Otherwise, the
- ## default initialization value for type `B` is returned (e.g. 0 for any
- ## integer type).
- ##
- ## See also:
- ## * `[] proc<#[],OrderedTable[A,B],A>`_ for retrieving a value of a key
- ## * `hasKey proc<#hasKey,OrderedTable[A,B],A>`_
- ## * `hasKeyOrPut proc<#hasKeyOrPut,OrderedTable[A,B],A,B>`_
- ## * `mgetOrPut proc<#mgetOrPut,OrderedTable[A,B],A,B>`_
- ## * `getOrDefault proc<#getOrDefault,OrderedTable[A,B],A,B>`_ to return
- ## a custom value if the key doesn't exist
- runnableExamples:
- let a = {'a': 5, 'b': 9}.toOrderedTable
- doAssert a.getOrDefault('a') == 5
- doAssert a.getOrDefault('z') == 0
- getOrDefaultImpl(t, key)
- proc getOrDefault*[A, B](t: OrderedTable[A, B], key: A, default: B): B =
- ## Retrieves the value at `t[key]` if `key` is in `t`.
- ## Otherwise, `default` is returned.
- ##
- ## See also:
- ## * `[] proc<#[],OrderedTable[A,B],A>`_ for retrieving a value of a key
- ## * `hasKey proc<#hasKey,OrderedTable[A,B],A>`_
- ## * `hasKeyOrPut proc<#hasKeyOrPut,OrderedTable[A,B],A,B>`_
- ## * `mgetOrPut proc<#mgetOrPut,OrderedTable[A,B],A,B>`_
- ## * `getOrDefault proc<#getOrDefault,OrderedTable[A,B],A>`_ to return
- ## a default value (e.g. zero for int) if the key doesn't exist
- runnableExamples:
- let a = {'a': 5, 'b': 9}.toOrderedTable
- doAssert a.getOrDefault('a', 99) == 5
- doAssert a.getOrDefault('z', 99) == 99
- getOrDefaultImpl(t, key, default)
- proc mgetOrPut*[A, B](t: var OrderedTable[A, B], key: A, val: B): var B =
- ## Retrieves value at `t[key]` or puts `val` if not present, either way
- ## returning a value which can be modified.
- ##
- ## See also:
- ## * `[] proc<#[],OrderedTable[A,B],A>`_ for retrieving a value of a key
- ## * `hasKey proc<#hasKey,OrderedTable[A,B],A>`_
- ## * `hasKeyOrPut proc<#hasKeyOrPut,OrderedTable[A,B],A,B>`_
- ## * `getOrDefault proc<#getOrDefault,OrderedTable[A,B],A>`_ to return
- ## a default value (e.g. zero for int) if the key doesn't exist
- ## * `getOrDefault proc<#getOrDefault,OrderedTable[A,B],A,B>`_ to return
- ## a custom value if the key doesn't exist
- runnableExamples:
- var a = {'a': 5, 'b': 9}.toOrderedTable
- doAssert a.mgetOrPut('a', 99) == 5
- doAssert a.mgetOrPut('z', 99) == 99
- doAssert a == {'a': 5, 'b': 9, 'z': 99}.toOrderedTable
- mgetOrPutImpl(enlarge)
- proc len*[A, B](t: OrderedTable[A, B]): int {.inline.} =
- ## Returns the number of keys in `t`.
- runnableExamples:
- let a = {'a': 5, 'b': 9}.toOrderedTable
- doAssert len(a) == 2
- result = t.counter
- proc add*[A, B](t: var OrderedTable[A, B], key: A, val: sink B) {.deprecated:
- "Deprecated since v1.4; it was more confusing than useful, use `[]=`".} =
- ## Puts a new `(key, value)` pair into `t` even if `t[key]` already exists.
- ##
- ## **This can introduce duplicate keys into the table!**
- ##
- ## Use `[]= proc<#[]=,OrderedTable[A,B],A,sinkB>`_ for inserting a new
- ## (key, value) pair in the table without introducing duplicates.
- addImpl(enlarge)
- proc del*[A, B](t: var OrderedTable[A, B], key: A) =
- ## Deletes `key` from hash table `t`. Does nothing if the key does not exist.
- ##
- ## O(n) complexity.
- ##
- ## See also:
- ## * `pop proc<#pop,OrderedTable[A,B],A,B>`_
- ## * `clear proc<#clear,OrderedTable[A,B]>`_ to empty the whole table
- runnableExamples:
- var a = {'a': 5, 'b': 9, 'c': 13}.toOrderedTable
- a.del('a')
- doAssert a == {'b': 9, 'c': 13}.toOrderedTable
- a.del('z')
- doAssert a == {'b': 9, 'c': 13}.toOrderedTable
- if t.counter == 0: return
- var n: OrderedKeyValuePairSeq[A, B]
- newSeq(n, len(t.data))
- var h = t.first
- t.first = -1
- t.last = -1
- swap(t.data, n)
- let hc = genHash(key)
- while h >= 0:
- var nxt = n[h].next
- if isFilled(n[h].hcode):
- if n[h].hcode == hc and n[h].key == key:
- dec t.counter
- else:
- var j = -1 - rawGetKnownHC(t, n[h].key, n[h].hcode)
- rawInsert(t, t.data, move n[h].key, move n[h].val, n[h].hcode, j)
- h = nxt
- proc pop*[A, B](t: var OrderedTable[A, B], key: A, val: var B): bool {.since: (1, 1).} =
- ## Deletes the `key` from the table.
- ## Returns `true`, if the `key` existed, and sets `val` to the
- ## mapping of the key. Otherwise, returns `false`, and the `val` is
- ## unchanged.
- ##
- ## O(n) complexity.
- ##
- ## See also:
- ## * `del proc<#del,OrderedTable[A,B],A>`_
- ## * `clear proc<#clear,OrderedTable[A,B]>`_ to empty the whole table
- runnableExamples:
- var
- a = {'c': 5, 'b': 9, 'a': 13}.toOrderedTable
- i: int
- doAssert a.pop('b', i) == true
- doAssert a == {'c': 5, 'a': 13}.toOrderedTable
- doAssert i == 9
- i = 0
- doAssert a.pop('z', i) == false
- doAssert a == {'c': 5, 'a': 13}.toOrderedTable
- doAssert i == 0
- var hc: Hash
- var index = rawGet(t, key, hc)
- result = index >= 0
- if result:
- val = move(t.data[index].val)
- del(t, key)
- proc clear*[A, B](t: var OrderedTable[A, B]) =
- ## Resets the table so that it is empty.
- ##
- ## See also:
- ## * `del proc<#del,OrderedTable[A,B],A>`_
- ## * `pop proc<#pop,OrderedTable[A,B],A,B>`_
- runnableExamples:
- var a = {'a': 5, 'b': 9, 'c': 13}.toOrderedTable
- doAssert len(a) == 3
- clear(a)
- doAssert len(a) == 0
- clearImpl()
- t.first = -1
- t.last = -1
- proc sort*[A, B](t: var OrderedTable[A, B], cmp: proc (x, y: (A, B)): int,
- order = SortOrder.Ascending) =
- ## Sorts `t` according to the function `cmp`.
- ##
- ## This modifies the internal list
- ## that kept the insertion order, so insertion order is lost after this
- ## call but key lookup and insertions remain possible after `sort` (in
- ## contrast to the `sort proc<#sort,CountTable[A]>`_ for count tables).
- runnableExamples:
- import std/[algorithm]
- var a = initOrderedTable[char, int]()
- for i, c in "cab":
- a[c] = 10*i
- doAssert a == {'c': 0, 'a': 10, 'b': 20}.toOrderedTable
- a.sort(system.cmp)
- doAssert a == {'a': 10, 'b': 20, 'c': 0}.toOrderedTable
- a.sort(system.cmp, order = SortOrder.Descending)
- doAssert a == {'c': 0, 'b': 20, 'a': 10}.toOrderedTable
- var list = t.first
- var
- p, q, e, tail, oldhead: int
- nmerges, psize, qsize, i: int
- if t.counter == 0: return
- var insize = 1
- while true:
- p = list; oldhead = list
- list = -1; tail = -1; nmerges = 0
- while p >= 0:
- inc(nmerges)
- q = p
- psize = 0
- i = 0
- while i < insize:
- inc(psize)
- q = t.data[q].next
- if q < 0: break
- inc(i)
- qsize = insize
- while psize > 0 or (qsize > 0 and q >= 0):
- if psize == 0:
- e = q; q = t.data[q].next; dec(qsize)
- elif qsize == 0 or q < 0:
- e = p; p = t.data[p].next; dec(psize)
- elif cmp((t.data[p].key, t.data[p].val),
- (t.data[q].key, t.data[q].val)) * order <= 0:
- e = p; p = t.data[p].next; dec(psize)
- else:
- e = q; q = t.data[q].next; dec(qsize)
- if tail >= 0: t.data[tail].next = e
- else: list = e
- tail = e
- p = q
- t.data[tail].next = -1
- if nmerges <= 1: break
- insize = insize * 2
- t.first = list
- t.last = tail
- proc `$`*[A, B](t: OrderedTable[A, B]): string =
- ## The `$` operator for ordered hash tables. Used internally when calling
- ## `echo` on a table.
- dollarImpl()
- proc `==`*[A, B](s, t: OrderedTable[A, B]): bool =
- ## The `==` operator for ordered hash tables. Returns `true` if both the
- ## content and the order are equal.
- runnableExamples:
- let
- a = {'a': 5, 'b': 9, 'c': 13}.toOrderedTable
- b = {'b': 9, 'c': 13, 'a': 5}.toOrderedTable
- doAssert a != b
- if s.counter != t.counter:
- return false
- if s.counter == 0 and t.counter == 0:
- return true
- var ht = t.first
- var hs = s.first
- while ht >= 0 and hs >= 0:
- var nxtt = t.data[ht].next
- var nxts = s.data[hs].next
- if isFilled(t.data[ht].hcode) and isFilled(s.data[hs].hcode):
- if (s.data[hs].key != t.data[ht].key) or (s.data[hs].val != t.data[ht].val):
- return false
- ht = nxtt
- hs = nxts
- return true
- iterator pairs*[A, B](t: OrderedTable[A, B]): (A, B) =
- ## Iterates over any `(key, value)` pair in the table `t` in insertion
- ## order.
- ##
- ## See also:
- ## * `mpairs iterator<#mpairs.i,OrderedTable[A,B]>`_
- ## * `keys iterator<#keys.i,OrderedTable[A,B]>`_
- ## * `values iterator<#values.i,OrderedTable[A,B]>`_
- ##
- ## **Examples:**
- ##
- ## .. code-block::
- ## let a = {
- ## 'o': [1, 5, 7, 9],
- ## 'e': [2, 4, 6, 8]
- ## }.toOrderedTable
- ##
- ## for k, v in a.pairs:
- ## echo "key: ", k
- ## echo "value: ", v
- ##
- ## # key: o
- ## # value: [1, 5, 7, 9]
- ## # key: e
- ## # value: [2, 4, 6, 8]
- let L = len(t)
- forAllOrderedPairs:
- yield (t.data[h].key, t.data[h].val)
- assert(len(t) == L, "the length of the table changed while iterating over it")
- iterator mpairs*[A, B](t: var OrderedTable[A, B]): (A, var B) =
- ## Iterates over any `(key, value)` pair in the table `t` (must be
- ## declared as `var`) in insertion order. The values can be modified.
- ##
- ## See also:
- ## * `pairs iterator<#pairs.i,OrderedTable[A,B]>`_
- ## * `mvalues iterator<#mvalues.i,OrderedTable[A,B]>`_
- runnableExamples:
- var a = {
- 'o': @[1, 5, 7, 9],
- 'e': @[2, 4, 6, 8]
- }.toOrderedTable
- for k, v in a.mpairs:
- v.add(v[0] + 10)
- doAssert a == {'o': @[1, 5, 7, 9, 11],
- 'e': @[2, 4, 6, 8, 12]}.toOrderedTable
- let L = len(t)
- forAllOrderedPairs:
- yield (t.data[h].key, t.data[h].val)
- assert(len(t) == L, "the length of the table changed while iterating over it")
- iterator keys*[A, B](t: OrderedTable[A, B]): lent A =
- ## Iterates over any key in the table `t` in insertion order.
- ##
- ## See also:
- ## * `pairs iterator<#pairs.i,OrderedTable[A,B]>`_
- ## * `values iterator<#values.i,OrderedTable[A,B]>`_
- runnableExamples:
- var a = {
- 'o': @[1, 5, 7, 9],
- 'e': @[2, 4, 6, 8]
- }.toOrderedTable
- for k in a.keys:
- a[k].add(99)
- doAssert a == {'o': @[1, 5, 7, 9, 99],
- 'e': @[2, 4, 6, 8, 99]}.toOrderedTable
- let L = len(t)
- forAllOrderedPairs:
- yield t.data[h].key
- assert(len(t) == L, "the length of the table changed while iterating over it")
- iterator values*[A, B](t: OrderedTable[A, B]): lent B =
- ## Iterates over any value in the table `t` in insertion order.
- ##
- ## See also:
- ## * `pairs iterator<#pairs.i,OrderedTable[A,B]>`_
- ## * `keys iterator<#keys.i,OrderedTable[A,B]>`_
- ## * `mvalues iterator<#mvalues.i,OrderedTable[A,B]>`_
- runnableExamples:
- let a = {
- 'o': @[1, 5, 7, 9],
- 'e': @[2, 4, 6, 8]
- }.toOrderedTable
- for v in a.values:
- doAssert v.len == 4
- let L = len(t)
- forAllOrderedPairs:
- yield t.data[h].val
- assert(len(t) == L, "the length of the table changed while iterating over it")
- iterator mvalues*[A, B](t: var OrderedTable[A, B]): var B =
- ## Iterates over any value in the table `t` (must be
- ## declared as `var`) in insertion order. The values
- ## can be modified.
- ##
- ## See also:
- ## * `mpairs iterator<#mpairs.i,OrderedTable[A,B]>`_
- ## * `values iterator<#values.i,OrderedTable[A,B]>`_
- runnableExamples:
- var a = {
- 'o': @[1, 5, 7, 9],
- 'e': @[2, 4, 6, 8]
- }.toOrderedTable
- for v in a.mvalues:
- v.add(99)
- doAssert a == {'o': @[1, 5, 7, 9, 99],
- 'e': @[2, 4, 6, 8, 99]}.toOrderedTable
- let L = len(t)
- forAllOrderedPairs:
- yield t.data[h].val
- assert(len(t) == L, "the length of the table changed while iterating over it")
- # ---------------------------------------------------------------------------
- # --------------------------- OrderedTableRef -------------------------------
- # ---------------------------------------------------------------------------
- proc newOrderedTable*[A, B](initialSize = defaultInitialSize): OrderedTableRef[A, B] =
- ## Creates a new ordered ref hash table that is empty.
- ##
- ## See also:
- ## * `newOrderedTable proc<#newOrderedTable,openArray[]>`_ for creating
- ## an `OrderedTableRef` from a collection of `(key, value)` pairs
- ## * `initOrderedTable proc<#initOrderedTable>`_ for creating an
- ## `OrderedTable`
- runnableExamples:
- let
- a = newOrderedTable[int, string]()
- b = newOrderedTable[char, seq[int]]()
- new(result)
- result[] = initOrderedTable[A, B](initialSize)
- proc newOrderedTable*[A, B](pairs: openArray[(A, B)]): OrderedTableRef[A, B] =
- ## Creates a new ordered ref hash table that contains the given `pairs`.
- ##
- ## `pairs` is a container consisting of `(key, value)` tuples.
- ##
- ## See also:
- ## * `newOrderedTable proc<#newOrderedTable>`_
- ## * `toOrderedTable proc<#toOrderedTable,openArray[]>`_ for an
- ## `OrderedTable` version
- runnableExamples:
- let a = [('a', 5), ('b', 9)]
- let b = newOrderedTable(a)
- assert b == {'a': 5, 'b': 9}.newOrderedTable
- result = newOrderedTable[A, B](pairs.len)
- for key, val in items(pairs): result[key] = val
- proc `[]`*[A, B](t: OrderedTableRef[A, B], key: A): var B =
- ## Retrieves the value at `t[key]`.
- ##
- ## If `key` is not in `t`, the `KeyError` exception is raised.
- ## One can check with `hasKey proc<#hasKey,OrderedTableRef[A,B],A>`_ whether
- ## the key exists.
- ##
- ## See also:
- ## * `getOrDefault proc<#getOrDefault,OrderedTableRef[A,B],A>`_ to return
- ## a default value (e.g. zero for int) if the key doesn't exist
- ## * `getOrDefault proc<#getOrDefault,OrderedTableRef[A,B],A,B>`_ to return
- ## a custom value if the key doesn't exist
- ## * `[]= proc<#[]=,OrderedTableRef[A,B],A,sinkB>`_ for inserting a new
- ## (key, value) pair in the table
- ## * `hasKey proc<#hasKey,OrderedTableRef[A,B],A>`_ for checking if
- ## a key is in the table
- runnableExamples:
- let a = {'a': 5, 'b': 9}.newOrderedTable
- doAssert a['a'] == 5
- doAssertRaises(KeyError):
- echo a['z']
- result = t[][key]
- proc `[]=`*[A, B](t: OrderedTableRef[A, B], key: A, val: sink B) =
- ## Inserts a `(key, value)` pair into `t`.
- ##
- ## See also:
- ## * `[] proc<#[],OrderedTableRef[A,B],A>`_ for retrieving a value of a key
- ## * `hasKeyOrPut proc<#hasKeyOrPut,OrderedTableRef[A,B],A,B>`_
- ## * `mgetOrPut proc<#mgetOrPut,OrderedTableRef[A,B],A,B>`_
- ## * `del proc<#del,OrderedTableRef[A,B],A>`_ for removing a key from the table
- runnableExamples:
- var a = newOrderedTable[char, int]()
- a['x'] = 7
- a['y'] = 33
- doAssert a == {'x': 7, 'y': 33}.newOrderedTable
- t[][key] = val
- proc hasKey*[A, B](t: OrderedTableRef[A, B], key: A): bool =
- ## Returns true if `key` is in the table `t`.
- ##
- ## See also:
- ## * `contains proc<#contains,OrderedTableRef[A,B],A>`_ for use with the `in`
- ## operator
- ## * `[] proc<#[],OrderedTableRef[A,B],A>`_ for retrieving a value of a key
- ## * `getOrDefault proc<#getOrDefault,OrderedTableRef[A,B],A>`_ to return
- ## a default value (e.g. zero for int) if the key doesn't exist
- ## * `getOrDefault proc<#getOrDefault,OrderedTableRef[A,B],A,B>`_ to return
- ## a custom value if the key doesn't exist
- runnableExamples:
- let a = {'a': 5, 'b': 9}.newOrderedTable
- doAssert a.hasKey('a') == true
- doAssert a.hasKey('z') == false
- result = t[].hasKey(key)
- proc contains*[A, B](t: OrderedTableRef[A, B], key: A): bool =
- ## Alias of `hasKey proc<#hasKey,OrderedTableRef[A,B],A>`_ for use with
- ## the `in` operator.
- runnableExamples:
- let a = {'a': 5, 'b': 9}.newOrderedTable
- doAssert 'b' in a == true
- doAssert a.contains('z') == false
- return hasKey[A, B](t, key)
- proc hasKeyOrPut*[A, B](t: var OrderedTableRef[A, B], key: A, val: B): bool =
- ## Returns true if `key` is in the table, otherwise inserts `value`.
- ##
- ## See also:
- ## * `hasKey proc<#hasKey,OrderedTableRef[A,B],A>`_
- ## * `[] proc<#[],OrderedTableRef[A,B],A>`_ for retrieving a value of a key
- ## * `getOrDefault proc<#getOrDefault,OrderedTableRef[A,B],A>`_ to return
- ## a default value (e.g. zero for int) if the key doesn't exist
- ## * `getOrDefault proc<#getOrDefault,OrderedTableRef[A,B],A,B>`_ to return
- ## a custom value if the key doesn't exist
- runnableExamples:
- var a = {'a': 5, 'b': 9}.newOrderedTable
- if a.hasKeyOrPut('a', 50):
- a['a'] = 99
- if a.hasKeyOrPut('z', 50):
- a['z'] = 99
- doAssert a == {'a': 99, 'b': 9, 'z': 50}.newOrderedTable
- result = t[].hasKeyOrPut(key, val)
- proc getOrDefault*[A, B](t: OrderedTableRef[A, B], key: A): B =
- ## Retrieves the value at `t[key]` if `key` is in `t`. Otherwise, the
- ## default initialization value for type `B` is returned (e.g. 0 for any
- ## integer type).
- ##
- ## See also:
- ## * `[] proc<#[],OrderedTableRef[A,B],A>`_ for retrieving a value of a key
- ## * `hasKey proc<#hasKey,OrderedTableRef[A,B],A>`_
- ## * `hasKeyOrPut proc<#hasKeyOrPut,OrderedTableRef[A,B],A,B>`_
- ## * `mgetOrPut proc<#mgetOrPut,OrderedTableRef[A,B],A,B>`_
- ## * `getOrDefault proc<#getOrDefault,OrderedTableRef[A,B],A,B>`_ to return
- ## a custom value if the key doesn't exist
- runnableExamples:
- let a = {'a': 5, 'b': 9}.newOrderedTable
- doAssert a.getOrDefault('a') == 5
- doAssert a.getOrDefault('z') == 0
- getOrDefault(t[], key)
- proc getOrDefault*[A, B](t: OrderedTableRef[A, B], key: A, default: B): B =
- ## Retrieves the value at `t[key]` if `key` is in `t`.
- ## Otherwise, `default` is returned.
- ##
- ## See also:
- ## * `[] proc<#[],OrderedTableRef[A,B],A>`_ for retrieving a value of a key
- ## * `hasKey proc<#hasKey,OrderedTableRef[A,B],A>`_
- ## * `hasKeyOrPut proc<#hasKeyOrPut,OrderedTableRef[A,B],A,B>`_
- ## * `mgetOrPut proc<#mgetOrPut,OrderedTableRef[A,B],A,B>`_
- ## * `getOrDefault proc<#getOrDefault,OrderedTableRef[A,B],A>`_ to return
- ## a default value (e.g. zero for int) if the key doesn't exist
- runnableExamples:
- let a = {'a': 5, 'b': 9}.newOrderedTable
- doAssert a.getOrDefault('a', 99) == 5
- doAssert a.getOrDefault('z', 99) == 99
- getOrDefault(t[], key, default)
- proc mgetOrPut*[A, B](t: OrderedTableRef[A, B], key: A, val: B): var B =
- ## Retrieves value at `t[key]` or puts `val` if not present, either way
- ## returning a value which can be modified.
- ##
- ## See also:
- ## * `[] proc<#[],OrderedTableRef[A,B],A>`_ for retrieving a value of a key
- ## * `hasKey proc<#hasKey,OrderedTableRef[A,B],A>`_
- ## * `hasKeyOrPut proc<#hasKeyOrPut,OrderedTableRef[A,B],A,B>`_
- ## * `getOrDefault proc<#getOrDefault,OrderedTableRef[A,B],A>`_ to return
- ## a default value (e.g. zero for int) if the key doesn't exist
- ## * `getOrDefault proc<#getOrDefault,OrderedTableRef[A,B],A,B>`_ to return
- ## a custom value if the key doesn't exist
- runnableExamples:
- var a = {'a': 5, 'b': 9}.newOrderedTable
- doAssert a.mgetOrPut('a', 99) == 5
- doAssert a.mgetOrPut('z', 99) == 99
- doAssert a == {'a': 5, 'b': 9, 'z': 99}.newOrderedTable
- result = t[].mgetOrPut(key, val)
- proc len*[A, B](t: OrderedTableRef[A, B]): int {.inline.} =
- ## Returns the number of keys in `t`.
- runnableExamples:
- let a = {'a': 5, 'b': 9}.newOrderedTable
- doAssert len(a) == 2
- result = t.counter
- proc add*[A, B](t: OrderedTableRef[A, B], key: A, val: sink B) {.deprecated:
- "Deprecated since v1.4; it was more confusing than useful, use `[]=`".} =
- ## Puts a new `(key, value)` pair into `t` even if `t[key]` already exists.
- ##
- ## **This can introduce duplicate keys into the table!**
- ##
- ## Use `[]= proc<#[]=,OrderedTableRef[A,B],A,sinkB>`_ for inserting a new
- ## (key, value) pair in the table without introducing duplicates.
- t[].add(key, val)
- proc del*[A, B](t: OrderedTableRef[A, B], key: A) =
- ## Deletes `key` from hash table `t`. Does nothing if the key does not exist.
- ##
- ## See also:
- ## * `clear proc<#clear,OrderedTableRef[A,B]>`_ to empty the whole table
- runnableExamples:
- var a = {'a': 5, 'b': 9, 'c': 13}.newOrderedTable
- a.del('a')
- doAssert a == {'b': 9, 'c': 13}.newOrderedTable
- a.del('z')
- doAssert a == {'b': 9, 'c': 13}.newOrderedTable
- t[].del(key)
- proc pop*[A, B](t: OrderedTableRef[A, B], key: A, val: var B): bool {.since: (1, 1).} =
- ## Deletes the `key` from the table.
- ## Returns `true`, if the `key` existed, and sets `val` to the
- ## mapping of the key. Otherwise, returns `false`, and the `val` is
- ## unchanged.
- ##
- ## See also:
- ## * `del proc<#del,OrderedTableRef[A,B],A>`_
- ## * `clear proc<#clear,OrderedTableRef[A,B]>`_ to empty the whole table
- runnableExamples:
- var
- a = {'c': 5, 'b': 9, 'a': 13}.newOrderedTable
- i: int
- doAssert a.pop('b', i) == true
- doAssert a == {'c': 5, 'a': 13}.newOrderedTable
- doAssert i == 9
- i = 0
- doAssert a.pop('z', i) == false
- doAssert a == {'c': 5, 'a': 13}.newOrderedTable
- doAssert i == 0
- pop(t[], key, val)
- proc clear*[A, B](t: OrderedTableRef[A, B]) =
- ## Resets the table so that it is empty.
- ##
- ## See also:
- ## * `del proc<#del,OrderedTableRef[A,B],A>`_
- runnableExamples:
- var a = {'a': 5, 'b': 9, 'c': 13}.newOrderedTable
- doAssert len(a) == 3
- clear(a)
- doAssert len(a) == 0
- clear(t[])
- proc sort*[A, B](t: OrderedTableRef[A, B], cmp: proc (x, y: (A, B)): int,
- order = SortOrder.Ascending) =
- ## Sorts `t` according to the function `cmp`.
- ##
- ## This modifies the internal list
- ## that kept the insertion order, so insertion order is lost after this
- ## call but key lookup and insertions remain possible after `sort` (in
- ## contrast to the `sort proc<#sort,CountTableRef[A]>`_ for count tables).
- runnableExamples:
- import std/[algorithm]
- var a = newOrderedTable[char, int]()
- for i, c in "cab":
- a[c] = 10*i
- doAssert a == {'c': 0, 'a': 10, 'b': 20}.newOrderedTable
- a.sort(system.cmp)
- doAssert a == {'a': 10, 'b': 20, 'c': 0}.newOrderedTable
- a.sort(system.cmp, order = SortOrder.Descending)
- doAssert a == {'c': 0, 'b': 20, 'a': 10}.newOrderedTable
- t[].sort(cmp, order = order)
- proc `$`*[A, B](t: OrderedTableRef[A, B]): string =
- ## The `$` operator for hash tables. Used internally when calling `echo`
- ## on a table.
- dollarImpl()
- proc `==`*[A, B](s, t: OrderedTableRef[A, B]): bool =
- ## The `==` operator for ordered hash tables. Returns true if either both
- ## tables are `nil`, or neither is `nil` and the content and the order of
- ## both are equal.
- runnableExamples:
- let
- a = {'a': 5, 'b': 9, 'c': 13}.newOrderedTable
- b = {'b': 9, 'c': 13, 'a': 5}.newOrderedTable
- doAssert a != b
- if isNil(s): result = isNil(t)
- elif isNil(t): result = false
- else: result = s[] == t[]
- iterator pairs*[A, B](t: OrderedTableRef[A, B]): (A, B) =
- ## Iterates over any `(key, value)` pair in the table `t` in insertion
- ## order.
- ##
- ## See also:
- ## * `mpairs iterator<#mpairs.i,OrderedTableRef[A,B]>`_
- ## * `keys iterator<#keys.i,OrderedTableRef[A,B]>`_
- ## * `values iterator<#values.i,OrderedTableRef[A,B]>`_
- ##
- ## **Examples:**
- ##
- ## .. code-block::
- ## let a = {
- ## 'o': [1, 5, 7, 9],
- ## 'e': [2, 4, 6, 8]
- ## }.newOrderedTable
- ##
- ## for k, v in a.pairs:
- ## echo "key: ", k
- ## echo "value: ", v
- ##
- ## # key: o
- ## # value: [1, 5, 7, 9]
- ## # key: e
- ## # value: [2, 4, 6, 8]
- let L = len(t)
- forAllOrderedPairs:
- yield (t.data[h].key, t.data[h].val)
- assert(len(t) == L, "the length of the table changed while iterating over it")
- iterator mpairs*[A, B](t: OrderedTableRef[A, B]): (A, var B) =
- ## Iterates over any `(key, value)` pair in the table `t` in insertion
- ## order. The values can be modified.
- ##
- ## See also:
- ## * `pairs iterator<#pairs.i,OrderedTableRef[A,B]>`_
- ## * `mvalues iterator<#mvalues.i,OrderedTableRef[A,B]>`_
- runnableExamples:
- let a = {
- 'o': @[1, 5, 7, 9],
- 'e': @[2, 4, 6, 8]
- }.newOrderedTable
- for k, v in a.mpairs:
- v.add(v[0] + 10)
- doAssert a == {'o': @[1, 5, 7, 9, 11],
- 'e': @[2, 4, 6, 8, 12]}.newOrderedTable
- let L = len(t)
- forAllOrderedPairs:
- yield (t.data[h].key, t.data[h].val)
- assert(len(t) == L, "the length of the table changed while iterating over it")
- iterator keys*[A, B](t: OrderedTableRef[A, B]): lent A =
- ## Iterates over any key in the table `t` in insertion order.
- ##
- ## See also:
- ## * `pairs iterator<#pairs.i,OrderedTableRef[A,B]>`_
- ## * `values iterator<#values.i,OrderedTableRef[A,B]>`_
- runnableExamples:
- let a = {
- 'o': @[1, 5, 7, 9],
- 'e': @[2, 4, 6, 8]
- }.newOrderedTable
- for k in a.keys:
- a[k].add(99)
- doAssert a == {'o': @[1, 5, 7, 9, 99], 'e': @[2, 4, 6, 8,
- 99]}.newOrderedTable
- let L = len(t)
- forAllOrderedPairs:
- yield t.data[h].key
- assert(len(t) == L, "the length of the table changed while iterating over it")
- iterator values*[A, B](t: OrderedTableRef[A, B]): lent B =
- ## Iterates over any value in the table `t` in insertion order.
- ##
- ## See also:
- ## * `pairs iterator<#pairs.i,OrderedTableRef[A,B]>`_
- ## * `keys iterator<#keys.i,OrderedTableRef[A,B]>`_
- ## * `mvalues iterator<#mvalues.i,OrderedTableRef[A,B]>`_
- runnableExamples:
- let a = {
- 'o': @[1, 5, 7, 9],
- 'e': @[2, 4, 6, 8]
- }.newOrderedTable
- for v in a.values:
- doAssert v.len == 4
- let L = len(t)
- forAllOrderedPairs:
- yield t.data[h].val
- assert(len(t) == L, "the length of the table changed while iterating over it")
- iterator mvalues*[A, B](t: OrderedTableRef[A, B]): var B =
- ## Iterates over any value in the table `t` in insertion order. The values
- ## can be modified.
- ##
- ## See also:
- ## * `mpairs iterator<#mpairs.i,OrderedTableRef[A,B]>`_
- ## * `values iterator<#values.i,OrderedTableRef[A,B]>`_
- runnableExamples:
- let a = {
- 'o': @[1, 5, 7, 9],
- 'e': @[2, 4, 6, 8]
- }.newOrderedTable
- for v in a.mvalues:
- v.add(99)
- doAssert a == {'o': @[1, 5, 7, 9, 99],
- 'e': @[2, 4, 6, 8, 99]}.newOrderedTable
- let L = len(t)
- forAllOrderedPairs:
- yield t.data[h].val
- assert(len(t) == L, "the length of the table changed while iterating over it")
- # -------------------------------------------------------------------------
- # ------------------------------ CountTable -------------------------------
- # -------------------------------------------------------------------------
- type
- CountTable*[A] = object
- ## Hash table that counts the number of each key.
- ##
- ## For creating an empty CountTable, use `initCountTable proc
- ## <#initCountTable>`_.
- data: seq[tuple[key: A, val: int]]
- counter: int
- isSorted: bool
- CountTableRef*[A] = ref CountTable[A] ## Ref version of
- ## `CountTable<#CountTable>`_.
- ##
- ## For creating a new empty CountTableRef, use `newCountTable proc
- ## <#newCountTable>`_.
- # ------------------------------ helpers ---------------------------------
- proc ctRawInsert[A](t: CountTable[A], data: var seq[tuple[key: A, val: int]],
- key: A, val: int) =
- var h: Hash = hash(key) and high(data)
- while data[h].val != 0: h = nextTry(h, high(data))
- data[h].key = key
- data[h].val = val
- proc enlarge[A](t: var CountTable[A]) =
- var n: seq[tuple[key: A, val: int]]
- newSeq(n, len(t.data) * growthFactor)
- for i in countup(0, high(t.data)):
- if t.data[i].val != 0: ctRawInsert(t, n, move t.data[i].key, move t.data[i].val)
- swap(t.data, n)
- proc rawGet[A](t: CountTable[A], key: A): int =
- if t.data.len == 0:
- return -1
- var h: Hash = hash(key) and high(t.data) # start with real hash value
- while t.data[h].val != 0:
- if t.data[h].key == key: return h
- h = nextTry(h, high(t.data))
- result = -1 - h # < 0 => MISSING; insert idx = -1 - result
- template ctget(t, key, default: untyped): untyped =
- var index = rawGet(t, key)
- result = if index >= 0: t.data[index].val else: default
- proc inc*[A](t: var CountTable[A], key: A, val = 1)
- # ----------------------------------------------------------------------
- proc initCountTable*[A](initialSize = defaultInitialSize): CountTable[A] =
- ## Creates a new count table that is empty.
- ##
- ## Starting from Nim v0.20, tables are initialized by default and it is
- ## not necessary to call this function explicitly.
- ##
- ## See also:
- ## * `toCountTable proc<#toCountTable,openArray[A]>`_
- ## * `newCountTable proc<#newCountTable>`_ for creating a
- ## `CountTableRef`
- initImpl(result, initialSize)
- proc toCountTable*[A](keys: openArray[A]): CountTable[A] =
- ## Creates a new count table with every member of a container `keys`
- ## having a count of how many times it occurs in that container.
- result = initCountTable[A](keys.len)
- for key in items(keys): result.inc(key)
- proc `[]`*[A](t: CountTable[A], key: A): int =
- ## Retrieves the value at `t[key]` if `key` is in `t`.
- ## Otherwise `0` is returned.
- ##
- ## See also:
- ## * `getOrDefault<#getOrDefault,CountTable[A],A,int>`_ to return
- ## a custom value if the key doesn't exist
- ## * `[]= proc<#[]%3D,CountTable[A],A,int>`_ for inserting a new
- ## (key, value) pair in the table
- ## * `hasKey proc<#hasKey,CountTable[A],A>`_ for checking if a key
- ## is in the table
- assert(not t.isSorted, "CountTable must not be used after sorting")
- ctget(t, key, 0)
- template cntMakeEmpty(i) = t.data[i].val = 0
- template cntCellEmpty(i) = t.data[i].val == 0
- template cntCellHash(i) = hash(t.data[i].key)
- proc `[]=`*[A](t: var CountTable[A], key: A, val: int) =
- ## Inserts a `(key, value)` pair into `t`.
- ##
- ## See also:
- ## * `[] proc<#[],CountTable[A],A>`_ for retrieving a value of a key
- ## * `inc proc<#inc,CountTable[A],A,int>`_ for incrementing a
- ## value of a key
- assert(not t.isSorted, "CountTable must not be used after sorting")
- assert val >= 0
- if val == 0:
- delImplNoHCode(cntMakeEmpty, cntCellEmpty, cntCellHash)
- else:
- let h = rawGet(t, key)
- if h >= 0:
- t.data[h].val = val
- else:
- insertImpl()
- proc inc*[A](t: var CountTable[A], key: A, val = 1) =
- ## Increments `t[key]` by `val` (default: 1).
- runnableExamples:
- var a = toCountTable("aab")
- a.inc('a')
- a.inc('b', 10)
- doAssert a == toCountTable("aaabbbbbbbbbbb")
- assert(not t.isSorted, "CountTable must not be used after sorting")
- var index = rawGet(t, key)
- if index >= 0:
- inc(t.data[index].val, val)
- if t.data[index].val == 0:
- delImplIdx(t, index, cntMakeEmpty, cntCellEmpty, cntCellHash)
- else:
- if val != 0:
- insertImpl()
- proc len*[A](t: CountTable[A]): int =
- ## Returns the number of keys in `t`.
- result = t.counter
- proc smallest*[A](t: CountTable[A]): tuple[key: A, val: int] =
- ## Returns the `(key, value)` pair with the smallest `val`. Efficiency: O(n)
- ##
- ## See also:
- ## * `largest proc<#largest,CountTable[A]>`_
- assert t.len > 0, "counttable is empty"
- var minIdx = -1
- for h in 0 .. high(t.data):
- if t.data[h].val > 0 and (minIdx == -1 or t.data[minIdx].val > t.data[h].val):
- minIdx = h
- result.key = t.data[minIdx].key
- result.val = t.data[minIdx].val
- proc largest*[A](t: CountTable[A]): tuple[key: A, val: int] =
- ## Returns the `(key, value)` pair with the largest `val`. Efficiency: O(n)
- ##
- ## See also:
- ## * `smallest proc<#smallest,CountTable[A]>`_
- assert t.len > 0, "counttable is empty"
- var maxIdx = 0
- for h in 1 .. high(t.data):
- if t.data[maxIdx].val < t.data[h].val: maxIdx = h
- result.key = t.data[maxIdx].key
- result.val = t.data[maxIdx].val
- proc hasKey*[A](t: CountTable[A], key: A): bool =
- ## Returns true if `key` is in the table `t`.
- ##
- ## See also:
- ## * `contains proc<#contains,CountTable[A],A>`_ for use with the `in`
- ## operator
- ## * `[] proc<#[],CountTable[A],A>`_ for retrieving a value of a key
- ## * `getOrDefault proc<#getOrDefault,CountTable[A],A,int>`_ to return
- ## a custom value if the key doesn't exist
- assert(not t.isSorted, "CountTable must not be used after sorting")
- result = rawGet(t, key) >= 0
- proc contains*[A](t: CountTable[A], key: A): bool =
- ## Alias of `hasKey proc<#hasKey,CountTable[A],A>`_ for use with
- ## the `in` operator.
- return hasKey[A](t, key)
- proc getOrDefault*[A](t: CountTable[A], key: A; default: int = 0): int =
- ## Retrieves the value at `t[key]` if`key` is in `t`. Otherwise, the
- ## integer value of `default` is returned.
- ##
- ## See also:
- ## * `[] proc<#[],CountTable[A],A>`_ for retrieving a value of a key
- ## * `hasKey proc<#hasKey,CountTable[A],A>`_ for checking if a key
- ## is in the table
- ctget(t, key, default)
- proc del*[A](t: var CountTable[A], key: A) {.since: (1, 1).} =
- ## Deletes `key` from table `t`. Does nothing if the key does not exist.
- ##
- ## See also:
- ## * `pop proc<#pop,CountTable[A],A,int>`_
- ## * `clear proc<#clear,CountTable[A]>`_ to empty the whole table
- runnableExamples:
- var a = toCountTable("aabbbccccc")
- a.del('b')
- assert a == toCountTable("aaccccc")
- a.del('b')
- assert a == toCountTable("aaccccc")
- a.del('c')
- assert a == toCountTable("aa")
- delImplNoHCode(cntMakeEmpty, cntCellEmpty, cntCellHash)
- proc pop*[A](t: var CountTable[A], key: A, val: var int): bool {.since: (1, 1).} =
- ## Deletes the `key` from the table.
- ## Returns `true`, if the `key` existed, and sets `val` to the
- ## mapping of the key. Otherwise, returns `false`, and the `val` is
- ## unchanged.
- ##
- ## See also:
- ## * `del proc<#del,CountTable[A],A>`_
- ## * `clear proc<#clear,CountTable[A]>`_ to empty the whole table
- runnableExamples:
- var a = toCountTable("aabbbccccc")
- var i = 0
- assert a.pop('b', i)
- assert i == 3
- i = 99
- assert not a.pop('b', i)
- assert i == 99
- var index = rawGet(t, key)
- result = index >= 0
- if result:
- val = move(t.data[index].val)
- delImplIdx(t, index, cntMakeEmpty, cntCellEmpty, cntCellHash)
- proc clear*[A](t: var CountTable[A]) =
- ## Resets the table so that it is empty.
- ##
- ## See also:
- ## * `del proc<#del,CountTable[A],A>`_
- ## * `pop proc<#pop,CountTable[A],A,int>`_
- clearImpl()
- t.isSorted = false
- func ctCmp[T](a, b: tuple[key: T, val: int]): int =
- result = system.cmp(a.val, b.val)
- proc sort*[A](t: var CountTable[A], order = SortOrder.Descending) =
- ## Sorts the count table so that, by default, the entry with the
- ## highest counter comes first.
- ##
- ## .. warning:: This is destructive! Once sorted, you must not modify `t` afterwards!
- ##
- ## You can use the iterators `pairs<#pairs.i,CountTable[A]>`_,
- ## `keys<#keys.i,CountTable[A]>`_, and `values<#values.i,CountTable[A]>`_
- ## to iterate over `t` in the sorted order.
- runnableExamples:
- import std/[algorithm, sequtils]
- var a = toCountTable("abracadabra")
- doAssert a == "aaaaabbrrcd".toCountTable
- a.sort()
- doAssert toSeq(a.values) == @[5, 2, 2, 1, 1]
- a.sort(SortOrder.Ascending)
- doAssert toSeq(a.values) == @[1, 1, 2, 2, 5]
- t.data.sort(cmp = ctCmp, order = order)
- t.isSorted = true
- proc merge*[A](s: var CountTable[A], t: CountTable[A]) =
- ## Merges the second table into the first one (must be declared as `var`).
- runnableExamples:
- var a = toCountTable("aaabbc")
- let b = toCountTable("bcc")
- a.merge(b)
- doAssert a == toCountTable("aaabbbccc")
- assert(not s.isSorted, "CountTable must not be used after sorting")
- for key, value in t:
- s.inc(key, value)
- when (NimMajor, NimMinor) <= (1, 0):
- proc merge*[A](s, t: CountTable[A]): CountTable[A] =
- ## Merges the two tables into a new one.
- runnableExamples:
- let
- a = toCountTable("aaabbc")
- b = toCountTable("bcc")
- doAssert merge(a, b) == toCountTable("aaabbbccc")
- result = initCountTable[A](nextPowerOfTwo(max(s.len, t.len)))
- for table in @[s, t]:
- for key, value in table:
- result.inc(key, value)
- proc `$`*[A](t: CountTable[A]): string =
- ## The `$` operator for count tables. Used internally when calling `echo`
- ## on a table.
- dollarImpl()
- proc `==`*[A](s, t: CountTable[A]): bool =
- ## The `==` operator for count tables. Returns `true` if both tables
- ## contain the same keys with the same count. Insert order does not matter.
- equalsImpl(s, t)
- iterator pairs*[A](t: CountTable[A]): (A, int) =
- ## Iterates over any `(key, value)` pair in the table `t`.
- ##
- ## See also:
- ## * `mpairs iterator<#mpairs.i,CountTable[A]>`_
- ## * `keys iterator<#keys.i,CountTable[A]>`_
- ## * `values iterator<#values.i,CountTable[A]>`_
- ##
- ## **Examples:**
- ##
- ## .. code-block::
- ## let a = toCountTable("abracadabra")
- ##
- ## for k, v in pairs(a):
- ## echo "key: ", k
- ## echo "value: ", v
- ##
- ## # key: a
- ## # value: 5
- ## # key: b
- ## # value: 2
- ## # key: c
- ## # value: 1
- ## # key: d
- ## # value: 1
- ## # key: r
- ## # value: 2
- let L = len(t)
- for h in 0 .. high(t.data):
- if t.data[h].val != 0:
- yield (t.data[h].key, t.data[h].val)
- assert(len(t) == L, "the length of the table changed while iterating over it")
- iterator mpairs*[A](t: var CountTable[A]): (A, var int) =
- ## Iterates over any `(key, value)` pair in the table `t` (must be
- ## declared as `var`). The values can be modified.
- ##
- ## See also:
- ## * `pairs iterator<#pairs.i,CountTable[A]>`_
- ## * `mvalues iterator<#mvalues.i,CountTable[A]>`_
- runnableExamples:
- var a = toCountTable("abracadabra")
- for k, v in mpairs(a):
- v = 2
- doAssert a == toCountTable("aabbccddrr")
- let L = len(t)
- for h in 0 .. high(t.data):
- if t.data[h].val != 0:
- yield (t.data[h].key, t.data[h].val)
- assert(len(t) == L, "the length of the table changed while iterating over it")
- iterator keys*[A](t: CountTable[A]): lent A =
- ## Iterates over any key in the table `t`.
- ##
- ## See also:
- ## * `pairs iterator<#pairs.i,CountTable[A]>`_
- ## * `values iterator<#values.i,CountTable[A]>`_
- runnableExamples:
- var a = toCountTable("abracadabra")
- for k in keys(a):
- a[k] = 2
- doAssert a == toCountTable("aabbccddrr")
- let L = len(t)
- for h in 0 .. high(t.data):
- if t.data[h].val != 0:
- yield t.data[h].key
- assert(len(t) == L, "the length of the table changed while iterating over it")
- iterator values*[A](t: CountTable[A]): int =
- ## Iterates over any value in the table `t`.
- ##
- ## See also:
- ## * `pairs iterator<#pairs.i,CountTable[A]>`_
- ## * `keys iterator<#keys.i,CountTable[A]>`_
- ## * `mvalues iterator<#mvalues.i,CountTable[A]>`_
- runnableExamples:
- let a = toCountTable("abracadabra")
- for v in values(a):
- assert v < 10
- let L = len(t)
- for h in 0 .. high(t.data):
- if t.data[h].val != 0:
- yield t.data[h].val
- assert(len(t) == L, "the length of the table changed while iterating over it")
- iterator mvalues*[A](t: var CountTable[A]): var int =
- ## Iterates over any value in the table `t` (must be
- ## declared as `var`). The values can be modified.
- ##
- ## See also:
- ## * `mpairs iterator<#mpairs.i,CountTable[A]>`_
- ## * `values iterator<#values.i,CountTable[A]>`_
- runnableExamples:
- var a = toCountTable("abracadabra")
- for v in mvalues(a):
- v = 2
- doAssert a == toCountTable("aabbccddrr")
- let L = len(t)
- for h in 0 .. high(t.data):
- if t.data[h].val != 0:
- yield t.data[h].val
- assert(len(t) == L, "the length of the table changed while iterating over it")
- # ---------------------------------------------------------------------------
- # ---------------------------- CountTableRef --------------------------------
- # ---------------------------------------------------------------------------
- proc inc*[A](t: CountTableRef[A], key: A, val = 1)
- proc newCountTable*[A](initialSize = defaultInitialSize): CountTableRef[A] =
- ## Creates a new ref count table that is empty.
- ##
- ## See also:
- ## * `newCountTable proc<#newCountTable,openArray[A]>`_ for creating
- ## a `CountTableRef` from a collection
- ## * `initCountTable proc<#initCountTable>`_ for creating a
- ## `CountTable`
- new(result)
- result[] = initCountTable[A](initialSize)
- proc newCountTable*[A](keys: openArray[A]): CountTableRef[A] =
- ## Creates a new ref count table with every member of a container `keys`
- ## having a count of how many times it occurs in that container.
- result = newCountTable[A](keys.len)
- for key in items(keys): result.inc(key)
- proc `[]`*[A](t: CountTableRef[A], key: A): int =
- ## Retrieves the value at `t[key]` if `key` is in `t`.
- ## Otherwise `0` is returned.
- ##
- ## See also:
- ## * `getOrDefault<#getOrDefault,CountTableRef[A],A,int>`_ to return
- ## a custom value if the key doesn't exist
- ## * `inc proc<#inc,CountTableRef[A],A,int>`_ to inc even if missing
- ## * `[]= proc<#[]%3D,CountTableRef[A],A,int>`_ for inserting a new
- ## (key, value) pair in the table
- ## * `hasKey proc<#hasKey,CountTableRef[A],A>`_ for checking if a key
- ## is in the table
- result = t[][key]
- proc `[]=`*[A](t: CountTableRef[A], key: A, val: int) =
- ## Inserts a `(key, value)` pair into `t`.
- ##
- ## See also:
- ## * `[] proc<#[],CountTableRef[A],A>`_ for retrieving a value of a key
- ## * `inc proc<#inc,CountTableRef[A],A,int>`_ for incrementing a
- ## value of a key
- assert val > 0
- t[][key] = val
- proc inc*[A](t: CountTableRef[A], key: A, val = 1) =
- ## Increments `t[key]` by `val` (default: 1).
- runnableExamples:
- var a = newCountTable("aab")
- a.inc('a')
- a.inc('b', 10)
- doAssert a == newCountTable("aaabbbbbbbbbbb")
- t[].inc(key, val)
- proc smallest*[A](t: CountTableRef[A]): tuple[key: A, val: int] =
- ## Returns the `(key, value)` pair with the smallest `val`. Efficiency: O(n)
- ##
- ## See also:
- ## * `largest proc<#largest,CountTableRef[A]>`_
- t[].smallest
- proc largest*[A](t: CountTableRef[A]): tuple[key: A, val: int] =
- ## Returns the `(key, value)` pair with the largest `val`. Efficiency: O(n)
- ##
- ## See also:
- ## * `smallest proc<#smallest,CountTable[A]>`_
- t[].largest
- proc hasKey*[A](t: CountTableRef[A], key: A): bool =
- ## Returns true if `key` is in the table `t`.
- ##
- ## See also:
- ## * `contains proc<#contains,CountTableRef[A],A>`_ for use with the `in`
- ## operator
- ## * `[] proc<#[],CountTableRef[A],A>`_ for retrieving a value of a key
- ## * `getOrDefault proc<#getOrDefault,CountTableRef[A],A,int>`_ to return
- ## a custom value if the key doesn't exist
- result = t[].hasKey(key)
- proc contains*[A](t: CountTableRef[A], key: A): bool =
- ## Alias of `hasKey proc<#hasKey,CountTableRef[A],A>`_ for use with
- ## the `in` operator.
- return hasKey[A](t, key)
- proc getOrDefault*[A](t: CountTableRef[A], key: A, default: int): int =
- ## Retrieves the value at `t[key]` if`key` is in `t`. Otherwise, the
- ## integer value of `default` is returned.
- ##
- ## See also:
- ## * `[] proc<#[],CountTableRef[A],A>`_ for retrieving a value of a key
- ## * `hasKey proc<#hasKey,CountTableRef[A],A>`_ for checking if a key
- ## is in the table
- result = t[].getOrDefault(key, default)
- proc len*[A](t: CountTableRef[A]): int =
- ## Returns the number of keys in `t`.
- result = t.counter
- proc del*[A](t: CountTableRef[A], key: A) {.since: (1, 1).} =
- ## Deletes `key` from table `t`. Does nothing if the key does not exist.
- ##
- ## See also:
- ## * `pop proc<#pop,CountTableRef[A],A,int>`_
- ## * `clear proc<#clear,CountTableRef[A]>`_ to empty the whole table
- del(t[], key)
- proc pop*[A](t: CountTableRef[A], key: A, val: var int): bool {.since: (1, 1).} =
- ## Deletes the `key` from the table.
- ## Returns `true`, if the `key` existed, and sets `val` to the
- ## mapping of the key. Otherwise, returns `false`, and the `val` is
- ## unchanged.
- ##
- ## See also:
- ## * `del proc<#del,CountTableRef[A],A>`_
- ## * `clear proc<#clear,CountTableRef[A]>`_ to empty the whole table
- pop(t[], key, val)
- proc clear*[A](t: CountTableRef[A]) =
- ## Resets the table so that it is empty.
- ##
- ## See also:
- ## * `del proc<#del,CountTableRef[A],A>`_
- ## * `pop proc<#pop,CountTableRef[A],A,int>`_
- clear(t[])
- proc sort*[A](t: CountTableRef[A], order = SortOrder.Descending) =
- ## Sorts the count table so that, by default, the entry with the
- ## highest counter comes first.
- ##
- ## **This is destructive! You must not modify `t` afterwards!**
- ##
- ## You can use the iterators `pairs<#pairs.i,CountTableRef[A]>`_,
- ## `keys<#keys.i,CountTableRef[A]>`_, and `values<#values.i,CountTableRef[A]>`_
- ## to iterate over `t` in the sorted order.
- t[].sort(order = order)
- proc merge*[A](s, t: CountTableRef[A]) =
- ## Merges the second table into the first one.
- runnableExamples:
- let
- a = newCountTable("aaabbc")
- b = newCountTable("bcc")
- a.merge(b)
- doAssert a == newCountTable("aaabbbccc")
- s[].merge(t[])
- proc `$`*[A](t: CountTableRef[A]): string =
- ## The `$` operator for count tables. Used internally when calling `echo`
- ## on a table.
- dollarImpl()
- proc `==`*[A](s, t: CountTableRef[A]): bool =
- ## The `==` operator for count tables. Returns `true` if either both tables
- ## are `nil`, or neither is `nil` and both contain the same keys with the same
- ## count. Insert order does not matter.
- if isNil(s): result = isNil(t)
- elif isNil(t): result = false
- else: result = s[] == t[]
- iterator pairs*[A](t: CountTableRef[A]): (A, int) =
- ## Iterates over any `(key, value)` pair in the table `t`.
- ##
- ## See also:
- ## * `mpairs iterator<#mpairs.i,CountTableRef[A]>`_
- ## * `keys iterator<#keys.i,CountTableRef[A]>`_
- ## * `values iterator<#values.i,CountTableRef[A]>`_
- ##
- ## **Examples:**
- ##
- ## .. code-block::
- ## let a = newCountTable("abracadabra")
- ##
- ## for k, v in pairs(a):
- ## echo "key: ", k
- ## echo "value: ", v
- ##
- ## # key: a
- ## # value: 5
- ## # key: b
- ## # value: 2
- ## # key: c
- ## # value: 1
- ## # key: d
- ## # value: 1
- ## # key: r
- ## # value: 2
- let L = len(t)
- for h in 0 .. high(t.data):
- if t.data[h].val != 0:
- yield (t.data[h].key, t.data[h].val)
- assert(len(t) == L, "the length of the table changed while iterating over it")
- iterator mpairs*[A](t: CountTableRef[A]): (A, var int) =
- ## Iterates over any `(key, value)` pair in the table `t`. The values can
- ## be modified.
- ##
- ## See also:
- ## * `pairs iterator<#pairs.i,CountTableRef[A]>`_
- ## * `mvalues iterator<#mvalues.i,CountTableRef[A]>`_
- runnableExamples:
- let a = newCountTable("abracadabra")
- for k, v in mpairs(a):
- v = 2
- doAssert a == newCountTable("aabbccddrr")
- let L = len(t)
- for h in 0 .. high(t.data):
- if t.data[h].val != 0:
- yield (t.data[h].key, t.data[h].val)
- assert(len(t) == L, "table modified while iterating over it")
- iterator keys*[A](t: CountTableRef[A]): A =
- ## Iterates over any key in the table `t`.
- ##
- ## See also:
- ## * `pairs iterator<#pairs.i,CountTable[A]>`_
- ## * `values iterator<#values.i,CountTable[A]>`_
- runnableExamples:
- let a = newCountTable("abracadabra")
- for k in keys(a):
- a[k] = 2
- doAssert a == newCountTable("aabbccddrr")
- let L = len(t)
- for h in 0 .. high(t.data):
- if t.data[h].val != 0:
- yield t.data[h].key
- assert(len(t) == L, "the length of the table changed while iterating over it")
- iterator values*[A](t: CountTableRef[A]): int =
- ## Iterates over any value in the table `t`.
- ##
- ## See also:
- ## * `pairs iterator<#pairs.i,CountTableRef[A]>`_
- ## * `keys iterator<#keys.i,CountTableRef[A]>`_
- ## * `mvalues iterator<#mvalues.i,CountTableRef[A]>`_
- runnableExamples:
- let a = newCountTable("abracadabra")
- for v in values(a):
- assert v < 10
- let L = len(t)
- for h in 0 .. high(t.data):
- if t.data[h].val != 0:
- yield t.data[h].val
- assert(len(t) == L, "the length of the table changed while iterating over it")
- iterator mvalues*[A](t: CountTableRef[A]): var int =
- ## Iterates over any value in the table `t`. The values can be modified.
- ##
- ## See also:
- ## * `mpairs iterator<#mpairs.i,CountTableRef[A]>`_
- ## * `values iterator<#values.i,CountTableRef[A]>`_
- runnableExamples:
- var a = newCountTable("abracadabra")
- for v in mvalues(a):
- v = 2
- doAssert a == newCountTable("aabbccddrr")
- let L = len(t)
- for h in 0 .. high(t.data):
- if t.data[h].val != 0:
- yield t.data[h].val
- assert(len(t) == L, "the length of the table changed while iterating over it")
|