const_smart_ptr.nim 2.0 KB

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