summary refs log tree commit diff stats
path: root/tests/gc/weakrefs.nim
blob: 0a6d4b873a6b36911f07ac616c07c14617b4d47b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
discard """
  output: "true"
"""

import intsets

type
  TMyObject = object
    id: int
  StrongObject = ref TMyObject
  WeakObject = object
    id: int
    data: ptr TMyObject

var
  gid: int # for id generation
  valid = initIntSet()

proc finalizer(x: StrongObject) =
  valid.excl(x.id)

proc create: StrongObject =
  new(result, finalizer)
  result.id = gid
  valid.incl(gid)
  inc gid

proc register(s: StrongObject): WeakObject =
  result.data = cast[ptr TMyObject](s)
  result.id = s.id

proc access(w: WeakObject): StrongObject =
  ## returns nil if the object doesn't exist anymore
  if valid.contains(w.id):
    result = cast[StrongObject](w.data)

proc main =
  var s: seq[WeakObject]
  newSeq(s, 10_000)
  for i in 0 .. s.high:
    s[i] = register(create())
  # test that we have at least 80% unreachable weak objects by now:
  when defined(gcMarkAndSweep):
    GC_fullcollect()
  var unreachable = 0
  for i in 0 .. s.high:
    if access(s[i]) == nil: inc unreachable
  echo unreachable > 8_000

main()