From b688250202ea479a51cbd20003e2ea2a147a3c3d Mon Sep 17 00:00:00 2001 From: Araq Date: Fri, 29 Nov 2019 11:55:50 +0100 Subject: fixes #12766 --- tests/destructor/const_smart_ptr.nim | 77 +++++++++++++++++++++++++++++++++++ tests/destructor/tconst_smart_ptr.nim | 7 ++++ 2 files changed, 84 insertions(+) create mode 100644 tests/destructor/const_smart_ptr.nim create mode 100644 tests/destructor/tconst_smart_ptr.nim (limited to 'tests') diff --git a/tests/destructor/const_smart_ptr.nim b/tests/destructor/const_smart_ptr.nim new file mode 100644 index 000000000..4d8c7c9a3 --- /dev/null +++ b/tests/destructor/const_smart_ptr.nim @@ -0,0 +1,77 @@ +type + ConstPtr*[T] = object + val: ptr T + +proc `=destroy`*[T](p: var ConstPtr[T]) = + if p.val != nil: + `=destroy`(p.val[]) + dealloc(p.val) + p.val = nil + +proc `=`*[T](dest: var ConstPtr[T], src: ConstPtr[T]) {.error.} + +proc `=sink`*[T](dest: var ConstPtr[T], src: ConstPtr[T]) {.inline.} = + if dest.val != nil and dest.val != src.val: + `=destroy`(dest) + dest.val = src.val + +proc newConstPtr*[T](val: sink T): ConstPtr[T] {.inline.} = + result.val = cast[type(result.val)](alloc(sizeof(result.val[]))) + reset(result.val[]) + result.val[] = val + +converter convertConstPtrToObj*[T](p: ConstPtr[T]): lent T = + result = p.val[] + + +#------------------------------------------------------------- + +type + MySeqNonCopyable* = object + len: int + data: ptr UncheckedArray[float] + +proc `=destroy`*(m: var MySeqNonCopyable) {.inline.} = + if m.data != nil: + deallocShared(m.data) + m.data = nil + +proc `=`*(m: var MySeqNonCopyable, m2: MySeqNonCopyable) {.error.} + +proc `=sink`*(m: var MySeqNonCopyable, m2: MySeqNonCopyable) {.inline.} = + if m.data != m2.data: + if m.data != nil: + `=destroy`(m) + m.len = m2.len + m.data = m2.data + +proc len*(m: MySeqNonCopyable): int {.inline.} = m.len + +proc `[]`*(m: MySeqNonCopyable; i: int): float {.inline.} = + m.data[i.int] + +proc `[]=`*(m: var MySeqNonCopyable; i: int, val: float) {.inline.} = + m.data[i.int] = val + +proc setTo(s: var MySeqNonCopyable, val: float) = + for i in 0.. 0: + result.data = cast[ptr UncheckedArray[float]](createShared(float, size)) + result.setTo(initial_value) + +#---------------------------------------------------------------------- + + +proc test*(x1: int): ConstPtr[MySeqNonCopyable] {.inline.} = # remove inline here to make it work as expected + if x1 == 0: + let x = newMySeq(1, 0.0) + result = newConstPtr(x) + else: + let y = newMySeq(x1, 0.0) + result = newConstPtr(y) + +discard test(10) diff --git a/tests/destructor/tconst_smart_ptr.nim b/tests/destructor/tconst_smart_ptr.nim new file mode 100644 index 000000000..39fe12612 --- /dev/null +++ b/tests/destructor/tconst_smart_ptr.nim @@ -0,0 +1,7 @@ +discard """ + action: "compile" +""" + +import const_smart_ptr + +discard test(0) -- cgit 1.4.1-2-gfad0