const_smart_ptr.nim 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. type
  2. ConstPtr*[T] = object
  3. val: ptr T
  4. proc `=destroy`*[T](p: ConstPtr[T]) =
  5. if p.val != nil:
  6. `=destroy`(p.val[])
  7. dealloc(p.val)
  8. proc `=copy`*[T](dest: var ConstPtr[T], src: ConstPtr[T]) {.error.}
  9. proc `=sink`*[T](dest: var ConstPtr[T], src: ConstPtr[T]) {.inline.} =
  10. if dest.val != nil and dest.val != src.val:
  11. `=destroy`(dest)
  12. dest.val = src.val
  13. proc newConstPtr*[T](val: sink T): ConstPtr[T] {.inline.} =
  14. result.val = cast[type(result.val)](alloc(sizeof(result.val[])))
  15. reset(result.val[])
  16. result.val[] = val
  17. converter convertConstPtrToObj*[T](p: ConstPtr[T]): lent T =
  18. result = p.val[]
  19. #-------------------------------------------------------------
  20. type
  21. MySeqNonCopyable* = object
  22. len: int
  23. data: ptr UncheckedArray[float]
  24. proc `=destroy`*(m: MySeqNonCopyable) {.inline.} =
  25. if m.data != nil:
  26. deallocShared(m.data)
  27. proc `=copy`*(m: var MySeqNonCopyable, m2: MySeqNonCopyable) {.error.}
  28. proc `=sink`*(m: var MySeqNonCopyable, m2: MySeqNonCopyable) {.inline.} =
  29. if m.data != m2.data:
  30. if m.data != nil:
  31. `=destroy`(m)
  32. m.len = m2.len
  33. m.data = m2.data
  34. proc len*(m: MySeqNonCopyable): int {.inline.} = m.len
  35. proc `[]`*(m: MySeqNonCopyable; i: int): float {.inline.} =
  36. m.data[i.int]
  37. proc `[]=`*(m: var MySeqNonCopyable; i: int, val: float) {.inline.} =
  38. m.data[i.int] = val
  39. proc setTo(s: var MySeqNonCopyable, val: float) =
  40. for i in 0..<s.len.int:
  41. s.data[i] = val
  42. proc newMySeq*(size: int, initial_value = 0.0): MySeqNonCopyable =
  43. result.len = size
  44. if size > 0:
  45. result.data = cast[ptr UncheckedArray[float]](createShared(float, size))
  46. result.setTo(initial_value)
  47. #----------------------------------------------------------------------
  48. proc test*(x1: int): ConstPtr[MySeqNonCopyable] {.inline.} = # remove inline here to make it work as expected
  49. if x1 == 0:
  50. let x = newMySeq(1, 0.0)
  51. result = newConstPtr(x)
  52. else:
  53. let y = newMySeq(x1, 0.0)
  54. result = newConstPtr(y)
  55. discard test(10)