//
//	MiscClassVariable.m -- a class to implement true class variables
//		Written by Mike Ferris (c) 1994 by Mike Ferris.
//		Modified from original MOKit "MOClassVariable" class by Don Yacktman.
//				Version 1.0.  All rights reserved.
//
//		This notice may not be removed from this source code.
//
//	This object is included in the MiscKit by permission from the author
//	and its use is governed by the MiscKit license, found in the file
//	"LICENSE.rtf" in the MiscKit distribution.  Please refer to that file
//	for a list of all applicable permissions and restrictions.
//	


#import "misckit/MiscClassVariable.h"
#import <objc/objc-runtime.h>

#define CLASS_VERSION		0
#define CLASS_NAME			"MiscClassVariable"

@implementation MiscClassVariable

+ initialize
// Set the version.
{
	if (self == objc_lookUpClass(CLASS_NAME))  {
		[self setVersion:CLASS_VERSION];
	}
	return self;
}

- init
// Just call the DI.
{
	return [self initDoesFreeValues:NO];
}

- initDoesFreeValues:(BOOL)flag
// Designated Initializer.
// Allocate the hashtable used to store the values.
{
	[super init];
	ht = [[HashTable allocFromZone:[self zone]] 
				initKeyDesc:"%" valueDesc:"@"];
	doesFreeValues = flag;
	return self;
}

- free
// Free the hashtable (objects too, if we're supposed to).
{
	if (doesFreeValues)  [ht freeObjects];
	[ht free];
	return [super free];
}

- setObject:obj forClass:(Class)class
// The old value for the class (if any) is freed if doesFreeValues is YES, 
// otherwise it returns the previous value.  Returns nil if doesFreeValues is
// YES.
{
	NXAtom className = NXUniqueString([class name]);
	id prevVal = nil;
	
	if (obj)  {
		// insert the new value
		prevVal = (id)[ht insertKey:className value:obj];
	}  else  {
		// no new value, just remove the old
		prevVal = (id)[ht valueForKey:className];
		if (prevVal)  [ht removeKey:className];
	}
	
	if (doesFreeValues)  {
		if (prevVal)  [prevVal free];
		return nil;
	}  else  {
		return prevVal;
	}
}

- getObjectForClass:(Class)class
// Look up the value for the given class.  Returns nil if no value has 
// been set.
{
	NXAtom className = NXUniqueString([class name]);
	return (id)[ht valueForKey:className];
}

@end
