Skip to content

Commit

Permalink
[bugfix] fix nim-lang#11588, initialize SharedTable
Browse files Browse the repository at this point in the history
  • Loading branch information
narimiran committed Jun 26, 2019
1 parent b7f8031 commit 71e1dad
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 10 deletions.
22 changes: 12 additions & 10 deletions lib/pure/collections/tableimpl.nim
Original file line number Diff line number Diff line change
Expand Up @@ -30,18 +30,23 @@ proc rawInsert[X, A, B](t: var X, data: var KeyValuePairSeq[A, B],
key: A, val: B, hc: Hash, h: Hash) =
rawInsertImpl()

template addImpl(enlarge) {.dirty.} =
template checkIfInitialized() =
if t.dataLen == 0:
initImpl(t, defaultInitialSize)
when compiles(defaultInitialSize):
initImpl(t, defaultInitialSize)
else: # SharedTable
init(t)

template addImpl(enlarge) {.dirty.} =
checkIfInitialized()
if mustRehash(t.dataLen, t.counter): enlarge(t)
var hc: Hash
var j = rawGetDeep(t, key, hc)
rawInsert(t, t.data, key, val, hc, j)
inc(t.counter)

template maybeRehashPutImpl(enlarge) {.dirty.} =
if t.dataLen == 0:
initImpl(t, defaultInitialSize)
checkIfInitialized()
if mustRehash(t.dataLen, t.counter):
enlarge(t)
index = rawGetKnownHC(t, key, hc)
Expand All @@ -50,16 +55,14 @@ template maybeRehashPutImpl(enlarge) {.dirty.} =
inc(t.counter)

template putImpl(enlarge) {.dirty.} =
if t.dataLen == 0:
initImpl(t, defaultInitialSize)
checkIfInitialized()
var hc: Hash
var index = rawGet(t, key, hc)
if index >= 0: t.data[index].val = val
else: maybeRehashPutImpl(enlarge)

template mgetOrPutImpl(enlarge) {.dirty.} =
if t.dataLen == 0:
initImpl(t, defaultInitialSize)
checkIfInitialized()
var hc: Hash
var index = rawGet(t, key, hc)
if index < 0:
Expand All @@ -69,8 +72,7 @@ template mgetOrPutImpl(enlarge) {.dirty.} =
result = t.data[index].val

template hasKeyOrPutImpl(enlarge) {.dirty.} =
if t.dataLen == 0:
initImpl(t, defaultInitialSize)
checkIfInitialized()
var hc: Hash
var index = rawGet(t, key, hc)
if index < 0:
Expand Down
33 changes: 33 additions & 0 deletions tests/stdlib/tsharedtable.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
discard """
output: '''
'''
"""

import sharedtables

block:
var
table1: SharedTable[int, int]
table2: SharedTable[int, int]

init(table1)
table1[1] = 10
assert table1.mget(1) == 10

# without init
table2[5] = 15
assert table2.mget(5) == 15


block:
var
table1: SharedTable[int, int]
table2: SharedTable[int, int]

init(table1)
assert table1.mgetOrPut(1, 7) == 7
assert table1.mgetOrPut(1, 99) == 7

# without init
assert table2.mgetOrPut(1, 7) == 7
assert table2.mgetOrPut(1, 99) == 7

0 comments on commit 71e1dad

Please sign in to comment.