14.  Appendix B: Convenience Functions for GC-Safe Data Structures  

      Figure @(gcroot) shows the source code for a set of functions to insert Scheme objects into a vector that has been registered with the garbage collector, to delete objects from the vector, and to retrieve the object stored under a given vector index. These functions help building dynamic data structures (such as linked lists or hash tables) containing Scheme objects. There is nothing application-specific in the code; if you find it useful, you can directly include it in your Elk extension or Elk-based application without any changes. See section @(ch-gcglobal) for a detailed description.


static int max_objects = 32;     /* initial size */
static int num_objects;
static Object objects;
static int inx;

int register_object(Object x) {
	Object v;
	int n;
	GC_Node;

	if (num_objects == max_objects) {
		max_objects *= 2;
		GC_Link(x);
		v = Make_Vector(max_objects, Null);
		GC_Unlink;
		memcpy(VECTOR(v)->data, VECTOR(objects)->data,
			num_objects * sizeof(Object));
		objects = v;
		inx = num_objects;
	}
	for (n = 0; !Nullp(VECTOR(objects)->data[inx]);
			inx++, inx %= max_objects) {
		n++;
		assert(n < max_objects);
	}
	VECTOR(objects)->data[inx] = x;
	num_objects++;
	return inx;
}

void deregister_object(int i) {
	VECTOR(objects)->data[i] = Null;
	--num_objects;
	assert(num_objects >= 0);
}

Object get_object(int i) {
	return VECTOR(objects)->data[i];
}

void elk_init_gcroot(void) {
	objects = Make_Vector(max_objects, Null);
	Global_GC_Link(objects);
}
Figure 11: Functions to map Scheme objects to indexes into a GC-safe vector



Markup created by unroff 1.0,    September 24, 1996,    net@informatik.uni-bremen.de