From 4455e5d4b6f30d4ce042c68c8285b2062d146197 Mon Sep 17 00:00:00 2001 From: Felix Krause Date: Thu, 7 Jul 2016 18:13:12 +0200 Subject: `==` in tables should not raise KeyError * With previous code, the compiler deduced that equalsImpl may raise a KeyError. While this could only actually happen in a nasty multi-threaded environment, I fixed the code so that it will never happen. --- lib/pure/collections/tables.nim | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'lib') diff --git a/lib/pure/collections/tables.nim b/lib/pure/collections/tables.nim index e454a43cb..8d5fbdfc3 100644 --- a/lib/pure/collections/tables.nim +++ b/lib/pure/collections/tables.nim @@ -304,8 +304,9 @@ template equalsImpl() = # to use the slow route here: for key, val in s: # prefix notation leads to automatic dereference in case of PTable - if not t.hasKey(key): return false - if t[key] != val: return false + try: + if t[key] != val: return false + except KeyError: return false return true proc `==`*[A, B](s, t: Table[A, B]): bool = -- cgit 1.4.1-2-gfad0 From 9f8cdf25605c3cbf2d05ab12ae9e555608b4ad47 Mon Sep 17 00:00:00 2001 From: Felix Krause Date: Fri, 8 Jul 2016 10:41:37 +0200 Subject: Use getOrDefault for tables.`==` --- lib/pure/collections/tables.nim | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) (limited to 'lib') diff --git a/lib/pure/collections/tables.nim b/lib/pure/collections/tables.nim index 8d5fbdfc3..9dc29fe69 100644 --- a/lib/pure/collections/tables.nim +++ b/lib/pure/collections/tables.nim @@ -298,19 +298,17 @@ proc hasKey*[A, B](t: TableRef[A, B], key: A): bool = ## returns true iff `key` is in the table `t`. result = t[].hasKey(key) -template equalsImpl() = +template equalsImpl(t) = if s.counter == t.counter: # different insertion orders mean different 'data' seqs, so we have # to use the slow route here: for key, val in s: - # prefix notation leads to automatic dereference in case of PTable - try: - if t[key] != val: return false - except KeyError: return false + if not t.hasKey(key): return false + if t.getOrDefault(key) != val: return false return true proc `==`*[A, B](s, t: Table[A, B]): bool = - equalsImpl() + equalsImpl(t) proc indexBy*[A, B, C](collection: A, index: proc(x: B): C): Table[C, B] = ## Index the collection with the proc provided. @@ -400,7 +398,7 @@ proc `$`*[A, B](t: TableRef[A, B]): string = proc `==`*[A, B](s, t: TableRef[A, B]): bool = if isNil(s): result = isNil(t) elif isNil(t): result = false - else: equalsImpl() + else: equalsImpl(t[]) proc newTableFrom*[A, B, C](collection: A, index: proc(x: B): C): TableRef[C, B] = ## Index the collection with the proc provided. -- cgit 1.4.1-2-gfad0