topt.nim 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. discard """
  2. output: '''5
  3. vseq destroy
  4. '''
  5. joinable: false
  6. """
  7. type
  8. opt*[T] = object
  9. case exists: bool
  10. of true: val: T
  11. of false: discard
  12. proc some*[T](val: sink T): opt[T] {.inline.} =
  13. ## Returns an ``opt`` that has the value.
  14. ## nil is considered as none for reference types
  15. result = opt[T](exists: true, val: val)
  16. proc none*(T: typedesc): opt[T] {.inline.} =
  17. ## Returns an ``opt`` for this type that has no value.
  18. # the default is the none type
  19. discard
  20. proc none*[T]: opt[T] {.inline.} =
  21. ## Alias for ``none(T)``.
  22. none(T)
  23. proc unsafeGet*[T](self: opt[T]): lent T {.inline.} =
  24. ## Returns the value of a ``some``. Behavior is undefined for ``none``.
  25. self.val
  26. type
  27. VSeq*[T] = object
  28. len: int
  29. data: ptr UncheckedArray[T]
  30. proc `=destroy`*[T](m: var VSeq[T]) {.inline.} =
  31. if m.data != nil:
  32. echo "vseq destroy"
  33. dealloc(m.data)
  34. m.data = nil
  35. proc `=`*[T](m: var VSeq[T], m2: VSeq[T]) {.error.}
  36. proc `=sink`*[T](m: var VSeq[T], m2: VSeq[T]) {.inline.} =
  37. if m.data != m2.data:
  38. `=destroy`(m)
  39. m.len = m2.len
  40. m.data = m2.data
  41. proc newVSeq*[T](len: int): VSeq[T] =
  42. ## Only support sequence creation from scalar size because creation from
  43. ## vetorized size can't reproduce the original scalar size
  44. result.len = len
  45. if len > 0:
  46. result.data = cast[ptr UncheckedArray[T]](alloc(sizeof(T) * len))
  47. let x = some newVSeq[float](5)
  48. echo x.unsafeGet.len
  49. let y = none(VSeq[float])