Skip to content

Instantly share code, notes, and snippets.

@planetis-m
Created June 29, 2021 10:33
Show Gist options
  • Save planetis-m/42b675403212e018b5b9c9cc2378dffc to your computer and use it in GitHub Desktop.
Save planetis-m/42b675403212e018b5b9c9cc2378dffc to your computer and use it in GitHub Desktop.
type
UniquePtr*[T] = object
val: ptr T
proc `=destroy`*[T](p: var UniquePtr[T]) =
mixin `=destroy`
if p.val != nil:
`=destroy`(p.val[])
dealloc(p.val)
p.val = nil
proc `=`*[T](dest: var UniquePtr[T], src: UniquePtr[T]) {.error.}
proc newUniquePtr*[T](val: sink T): UniquePtr[T] {.nodestroy.} =
result.val = cast[ptr T](alloc(sizeof(T)))
result.val[] = val
proc `[]`*[T](p: UniquePtr[T]): var T {.inline.} =
when compileOption("boundChecks"):
assert(p.val != nil, "deferencing nil unique pointer")
p.val[]
type X = array[1024*1024*100, byte]
proc main =
let p = newUniquePtr(default(X))
echo p[][0] == 1.byte
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment