/* weak objects and dictsnappers */
/* see weak/_dict.py for high-level documentation */

/***********************************************************
Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
The Netherlands.

                        All Rights Reserved

Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the names of Stichting Mathematisch
Centrum or CWI or Corporation for National Research Initiatives or
CNRI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.

While CWI is the initial source for this software, a modified version
is made available by the Corporation for National Research Initiatives
(CNRI) at the Internet address ftp://ftp.python.org.

STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.

******************************************************************/

#include "Python.h"

typedef struct {
	PyObject_HEAD
        PyObject *o;
} WeakObject;

staticforward PyTypeObject Weak_Type;

#define WeakObject_Check(v)	((v)->ob_type == &Weak_Type)

static WeakObject *
newWeakObject(arg)
	PyObject *arg;
{
	WeakObject *self;
	self = PyObject_NEW(WeakObject, &Weak_Type);
	if (self == NULL)
		return NULL;
	return self;
}

/* Weak methods */

static void
Weak_dealloc(self)
	WeakObject *self;
{
	PyMem_DEL(self);
}

static PyObject *
Weak_get(self, args, kwds)
	WeakObject *self;
	PyObject *args;
	PyObject *kwds;
{
	if (!PyArg_ParseTuple(args, ""))
		return NULL;

	if (self->o)
	  {
	    Py_INCREF(self->o);
	    return self->o;
	  }
	else
	  {
	    Py_INCREF(Py_None);
	    return Py_None;
	  }
}

statichere PyTypeObject Weak_Type = {
	/* The ob_type field must be initialized in the module init function
	 * to be portable to Windows without using C++. */
	PyObject_HEAD_INIT(NULL)
	0,			/*ob_size*/
	"weak._weak.weak",			/*tp_name*/
	sizeof(WeakObject),	/*tp_basicsize*/
	0,			/*tp_itemsize*/
	/* methods */
	(destructor)Weak_dealloc, /*tp_dealloc*/
	0,			/*tp_print*/
	0,                      /*tp_getattr*/
	0,                      /*tp_setattr*/
	0,			/*tp_compare*/
	0,			/*tp_repr*/
	0,		        /*tp_as_number*/
	0,			/*tp_as_sequence*/
	0,			/*tp_as_mapping*/
	0,			/*tp_hash*/
	Weak_get,		/*tp_call*/
};
/* --------------------------------------------------------------------- */

/* Function of one Python object argument returning new Weak object */

static PyObject *
weak_new(self, args)
	PyObject *self; /* Not used */
	PyObject *args;
{
	WeakObject *rv;
	PyObject *o;

	if (!PyArg_ParseTuple(args, "O;weak._weak.new", &o))
		return NULL;
	rv = newWeakObject(args);
	if ( rv == NULL )
	    return NULL;
	rv->o = o;
	return (PyObject *)rv;
}

typedef struct {
	PyObject_HEAD
        PyObject *weaks;
        PyObject *key;
        PyObject *value;
} DictsnapperObject;

staticforward PyTypeObject Dictsnapper_Type;

#define DictsnapperObject_Check(v)	((v)->ob_type == &Dictsnapper_Type)

static DictsnapperObject *
newDictsnapperObject(arg)
	PyObject *arg;
{
	DictsnapperObject *self;
	self = PyObject_NEW(DictsnapperObject, &Dictsnapper_Type);
	if (self == NULL)
		return NULL;
	return self;
}

/* Dictsnapper methods */

static void
Dictsnapper_dealloc(self)
	DictsnapperObject *self;
{
  PyObject *w;

  /* OK, we're being deleted; that means the object we clean for has
     been deleted.  If it's entry is still the current one for KEY in
     WEAKS (which could be false due to deletion or replacement),
     delete it. */
  
  w = PyDict_GetItem(self->weaks, self->key);
  
  if (w && ((WeakObject *) w)->o == self->value)
  {
      /*fprintf(stderr, "snapping\n");*/
      PyDict_DelItem(self->weaks, self->key);
  }
  
  Py_DECREF(self->weaks);
  Py_DECREF(self->key);
  /* do NOT Py_DECREF() self->value */
  
  PyMem_DEL(self);
}

statichere PyTypeObject Dictsnapper_Type = {
	/* The ob_type field must be initialized in the module init function
	 * to be portable to Windows without using C++. */
	PyObject_HEAD_INIT(NULL)
	0,			/*ob_size*/
	"weak._weak.dictsnapper",			/*tp_name*/
	sizeof(DictsnapperObject),	/*tp_basicsize*/
	0,			/*tp_itemsize*/
	/* methods */
	(destructor)Dictsnapper_dealloc, /*tp_dealloc*/
	0,			/*tp_print*/
	0,                      /*tp_getattr*/
	0,                      /*tp_setattr*/
	0,			/*tp_compare*/
	0,			/*tp_repr*/
	0,		        /*tp_as_number*/
	0,			/*tp_as_sequence*/
	0,			/*tp_as_mapping*/
	0,			/*tp_hash*/
};
/* --------------------------------------------------------------------- */

static PyObject *
dictsnapper_new(self, args)
	PyObject *self; /* Not used */
	PyObject *args;
{
	DictsnapperObject *rv;
	PyObject *weaks, *key, *value;
	
	if (!PyArg_ParseTuple(args, "O!OO;weak._weak.dictsnapper", 
			      &PyDict_Type, &weaks, &key, &value))
		return NULL;

	rv = newDictsnapperObject(args);

	if ( rv == NULL )
	    return NULL;

	Py_INCREF(weaks);
	Py_INCREF(key);
	/* do NOT Py_INCREF(value) */

	rv->weaks = weaks;
	rv->key = key;
	rv->value = value;

	return (PyObject *)rv;
}

static PyMethodDef _weak_methods[] = {
	{"weak",		weak_new,		1},
	{"dictsnapper",		dictsnapper_new,		1},
	{NULL,		NULL}		/* sentinel */
};

DL_EXPORT(void)
init_weak()
{
  PyObject *m, *d;

  Weak_Type.ob_type = &PyType_Type;

  m = Py_InitModule("_weak", _weak_methods);
}
