From 42f761814d055971894f61926f193d4ce48e0934 Mon Sep 17 00:00:00 2001 From: Timothee Cour Date: Wed, 17 Feb 2021 10:06:44 -0800 Subject: [PATCH 1/2] make std/lists usable with ptr instead of ref --- lib/pure/collections/lists.nim | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/lib/pure/collections/lists.nim b/lib/pure/collections/lists.nim index e1c3808b20492..03eb77b38a8c7 100644 --- a/lib/pure/collections/lists.nim +++ b/lib/pure/collections/lists.nim @@ -81,6 +81,10 @@ type value*: T SinglyLinkedNode*[T] = ref SinglyLinkedNodeObj[T] + SinglyLinkedNodePtr*[T] = object + next*: ptr SinglyLinkedNodePtr[T] + value*: T + SinglyLinkedList*[T] = object ## \ ## A singly linked list. ## @@ -89,6 +93,10 @@ type head*: (SinglyLinkedNode[T]) tail* {.cursor.}: SinglyLinkedNode[T] + SinglyLinkedListPtr*[T] = object + head*: ptr SinglyLinkedNodePtr[T] + tail*: ptr SinglyLinkedNodePtr[T] + DoublyLinkedList*[T] = object ## \ ## A doubly linked list. ## @@ -112,7 +120,7 @@ type ## a new empty ring. head*: DoublyLinkedNode[T] - SomeLinkedList*[T] = SinglyLinkedList[T] | DoublyLinkedList[T] + SomeLinkedList*[T] = SinglyLinkedList[T] | DoublyLinkedList[T] | SinglyLinkedListPtr[T] SomeLinkedRing*[T] = SinglyLinkedRing[T] | DoublyLinkedRing[T] @@ -126,6 +134,9 @@ proc initSinglyLinkedList*[T](): SinglyLinkedList[T] = var a = initSinglyLinkedList[int]() discard +proc initSinglyLinkedListPtr*[T](): SinglyLinkedListPtr[T] = + discard + proc initDoublyLinkedList*[T](): DoublyLinkedList[T] = ## Creates a new doubly linked list that is empty. runnableExamples: @@ -399,8 +410,9 @@ proc prependMoved*[T: SomeLinkedList](a, b: var T) {.since: (1, 5, 1).} = (b, a) = (a, b) else: swap a, b -proc add*[T](L: var SinglyLinkedList[T], - n: SinglyLinkedNode[T]) {.inline.} = +# proc add*[T](L: var (SinglyLinkedList[T] | SinglyLinkedListPtr[T]), n: type(L.tail)) {.inline.} = # xxx make this work +proc add*[T](L: var (SinglyLinkedList[T] | SinglyLinkedListPtr[T]), + n: SinglyLinkedNode[T] | ptr SinglyLinkedNodePtr[T]) {.inline.} = ## Appends (adds to the end) a node `n` to `L`. Efficiency: O(1). ## ## See also: From 5a704885fdd4b6ddd0c227d5475019eaf7dc79b0 Mon Sep 17 00:00:00 2001 From: Timothee Cour Date: Wed, 17 Feb 2021 10:09:00 -0800 Subject: [PATCH 2/2] add test --- tests/stdlib/tlists.nim | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/tests/stdlib/tlists.nim b/tests/stdlib/tlists.nim index 2d3165c9c8fbe..89dd278b99af2 100644 --- a/tests/stdlib/tlists.nim +++ b/tests/stdlib/tlists.nim @@ -231,3 +231,11 @@ block remove: # return value check doAssert l.toSeq == [1] doAssert l.remove(l.head) == true doAssert l.toSeq == [] + +block: # SinglyLinkedNodePtr, etc + var list = initSinglyLinkedListPtr[int]() + var nodes: array[4, SinglyLinkedNodePtr[int]] + for i,n in mpairs(nodes): + n.value = i + list.add n.addr + doAssert toSeq(list) == [0,1,2,3]