From 39a4d37f82f1cee44949ecbc314540966a792e35 Mon Sep 17 00:00:00 2001 From: demotomohiro Date: Mon, 5 Feb 2024 17:26:49 +0900 Subject: [PATCH] fixes #23275; Add `==` for Deque --- lib/pure/collections/deques.nim | 20 +++++++++++++++++ tests/stdlib/tdeques.nim | 40 +++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/lib/pure/collections/deques.nim b/lib/pure/collections/deques.nim index b07138e842e2f..b3378280c5aa0 100644 --- a/lib/pure/collections/deques.nim +++ b/lib/pure/collections/deques.nim @@ -455,3 +455,23 @@ proc `$`*[T](deq: Deque[T]): string = if result.len > 1: result.add(", ") result.addQuoted(x) result.add("]") + +func `==`*[T](deq1, deq2: Deque[T]): bool = + ## The `==` operator for Deque. + ## Returns `true` if both deques contains the same values in the same order. + runnableExamples: + var a, b = initDeque[int]() + a.addFirst(2) + a.addFirst(1) + b.addLast(1) + b.addLast(2) + doAssert a == b + + if deq1.count != deq2.count: + return false + + for i in 0 ..< deq1.count: + if deq1.data[(deq1.head + i) and deq1.mask] != deq2.data[(deq2.head + i) and deq2.mask]: + return false + + true diff --git a/tests/stdlib/tdeques.nim b/tests/stdlib/tdeques.nim index 49072b1504416..84ccd879d0788 100644 --- a/tests/stdlib/tdeques.nim +++ b/tests/stdlib/tdeques.nim @@ -189,6 +189,46 @@ proc main() = a.shrink(fromFirst = 0, fromLast = 1) doAssert $a == "[10, 20, 30]" + block: + var a, b: Deque[int] + for i in 1 .. 256: + a.addLast(i) + for i in 1 .. 255: + a.popLast + b.addLast(1) + doAssert a == b + + block: + # Issue 23275 + # Test `==`. + block: + var a, b = initDeque[int]() + doAssert a == b + a.addFirst(1) + doAssert a != b + b.addLast(1) + doAssert a == b + a.popFirst + b.popLast + doAssert a == b + a.addLast 2 + doAssert a != b + b.addFirst 2 + doAssert a == b + + block: + var a, b = initDeque[int]() + for i in countDown(100, 1): + a.addFirst(i) + for i in 1..100: + b.addLast(i) + doAssert a == b + for i in 1..99: + a.popLast + doAssert a == [1].toDeque + var c = initDeque[int]() + c.addLast(1) + doAssert a == c static: main() main()