1MODULE WeakRef; 2 3(* Implementation of parametric weak references. 4 Copyright (C) 2003,2004 Stewart Greenhill 5 6 This module is free software; you can redistribute it and/or 7 modify it under the terms of the GNU Lesser General Public License 8 as published by the Free Software Foundation; either version 2 of 9 the License, or (at your option) any later version. 10 11 This module is distributed in the hope that it will be useful, but 12 WITHOUT ANY WARRANTY; without even the implied warranty of 13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14 Lesser General Public License for more details. 15 16 You should have received a copy of the GNU Lesser General Public 17 License along with OOC. If not, write to the Free Software Foundation, 18 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 19*) 20 21IMPORT RT0; 22 23TYPE 24 Type = RT0.Object; 25 26TYPE 27 WeakRef* (T : Type) = POINTER TO WeakRefDesc(T); 28 WeakRefDesc (T : Type) = RECORD [NO_TRACED_POINTERS] 29 (**WeakRef encapsulates a pointer to a collectable object, but does not 30 prevent the object from being collected by the run-time system. *) 31 ptr : T; 32 END; 33 34PROCEDURE (r : WeakRef(T)) Get* () : T; 35(**Return a pointer to the object referenced by this weak reference. This will 36 be the previous value of the reference (defined via @oproc{r.Set} or 37 @oproc{r.INIT}), or @code{NIL} if the object has been collected. *) 38BEGIN 39 RETURN r.ptr; 40END Get; 41 42PROCEDURE (r : WeakRef(T)) Set* (ptr : T); 43(**Set this reference to refer to @oparam{ptr}. The weak reference may be 44 explicitly cleared by specifying @code{NIL} for @oparam{ptr}. While this 45 has no visible effect, it may result in a slight improvement in GC 46 performance. *) 47BEGIN 48 IF ptr = NIL THEN 49 IF r.ptr # NIL THEN 50 RT0.UnregisterDisappearingLink(r.ptr); 51 END; 52 r.ptr := NIL; 53 ELSE 54 r.ptr := ptr; 55 RT0.RegisterDisappearingLink(r.ptr); 56 END; 57END Set; 58 59PROCEDURE (r : WeakRef(T)) Equal* (r2 : WeakRef(T)) : BOOLEAN; 60(**Determine of two weak references are equal. This function returns 61 @code{TRUE} if the object). This is equivalent to 62 @code{r.Get() = r2.Get()}. *) 63BEGIN 64 RETURN r.ptr = r2.ptr; 65END Equal; 66 67PROCEDURE (r : WeakRef(T)) INIT* (ptr : T); 68(**Create a weak reference to @oparam{ptr}. The reference does not prevent the 69 object from being collected by the garbage collector. *) 70BEGIN 71 r.ptr := NIL; 72 r.Set(ptr); 73END INIT; 74 75END WeakRef. 76