/* 
   NSZone.m

   Copyright (C) 1995, 1996 Ovidiu Predescu and Mircea Oancea.
   All rights reserved.

   Author: Ovidiu Predescu <ovidiu@bx.logicnet.ro>

   This file is part of libFoundation.

   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.

   We disclaim all warranties with regard to this software, including all
   implied warranties of merchantability and fitness, in no event shall
   we 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 <config.h>

#if HAVE_STDLIB_H
# include <stdlib.h>
#endif

#if HAVE_LIBC_H
# include <libc.h>
#else
# include <unistd.h>
#endif

#include <Foundation/NSAutoreleasePool.h>
#include <Foundation/NSString.h>
#include <Foundation/NSZone.h>

#include <extensions/NSException.h>

#include "NSDefaultZone.h"

#include <Foundation/NSAllocDebugZone.h>

static id defaultZone;

/* The NSZone class keeps a linked list of zones. The default zone should be
   the last zone in this list because the implementation of NSDefaultZone
   implements the -pointerInZone: method to return YES no matter what is the
   value of its argument. This because we cannot assume nothing about how the
   system malloc library, especially if it has a function that tells us if
   a pointer was allocated using malloc(). */

typedef struct ZoneListNode {
    struct ZoneListNode* next;
    NSZone* zone;
} ZoneListNode;

static ZoneListNode* zones = NULL;

@implementation NSZone

+ (void)initialize
{
    static BOOL initialized = NO;
    char* str;

    if(!initialized) {
	initialized = YES;
	// alloc is redefined in NSDefaultZone to return memory for this
	// class from malloc; this is because alloc in NSObject calls
	// NSAllocateObject(class, 0, defaultZone) and defaultZone is 
	// uninitialized yet
	// So for zones we have special allocation method allocZoneInstance
	// and we redefine all refcounting methods and keep an ivar refCount
	
	str = getenv("ALLOCDEBUG");
	if (str && *str)
	    defaultZone = [[NSAllocDebugZone alloc] init];
	else
	    defaultZone = [[NSDefaultZone alloc] init];
    }
}

+ (id)alloc
{
    return defaultZone;
}

+ (id)allocWithZone:(NSZone*)zone
{
    return defaultZone;
}

+ (NSZone*)defaultZone
{
    return defaultZone;
}

+ (NSZone*)zoneFromPointer:(void*)pointer
{
    ZoneListNode* node = zones;

    while(node && ![node->zone pointerInZone:pointer])
	node = node->next;

    if (node)
	return node->zone;

    return defaultZone;
}

+ (BOOL)checkZone
{
    return [defaultZone checkZone];
}

- initForSize:(unsigned)startSize granularity:(unsigned)granularity
    canFree:(BOOL)canFree
{
    [self subclassResponsibility:_cmd];
    return self;
}

- (void*)malloc:(unsigned)size
{
    [self subclassResponsibility:_cmd];
    return NULL;
}

- (void*)calloc:(unsigned)numElems byteSize:(unsigned)byteSize
{
    [self subclassResponsibility:_cmd];
    return NULL;
}

- (void*)realloc:(void*)pointer size:(unsigned)size
{
    [self subclassResponsibility:_cmd];
    return NULL;
}

- (void)recycle
{
    [self subclassResponsibility:_cmd];
}

- (BOOL)pointerInZone:(void*)pointer
{
    [self subclassResponsibility:_cmd];
    return NO;
}

- (void)freePointer:(void*)pointer
{
    [self subclassResponsibility:_cmd];
}

- (void)setName:(NSString*)newName
{
    [newName retain];
    [name release];
    name = newName;
}

- (NSString*)name
{
    return name;
}

- (BOOL)checkZone
{
    return YES;
}

/* Refcounting is special to NSZone */

+ (id)allocZoneInstance
{
    struct myzone {
	@defs(NSZone);
    }*	theZone;
    Class class = (Class)self;
    ZoneListNode* node;

    theZone = calloc(1, class->instance_size);
    
    theZone->isa = self;
    theZone->refCount = 1;

    /* Enter this zone into the zones list */
    node = malloc(sizeof(ZoneListNode));
    node->next = zones;
    node->zone = (NSZone*)theZone;
    zones = node;
    

    return (id)theZone;
}

- autorelease
{
    [NSAutoreleasePool addObject:self];
    return self;
}

- (void)dealloc
{
    /* Remove the zone node from the zones list. */

    /* Try to see if the zone is the first one in list. */
    if (zones->zone == self)
	zones = zones->next;
    else {
	ZoneListNode* prev = zones;
	ZoneListNode* curr = zones->next;

	/* Iterate on the zones list until we find ourself */
	while (curr && curr->zone != self) {
	    prev = curr;
	    curr = curr->next;
	}

	/* The curr should not be NULL, but who knows... */
	Assert (curr);

	prev->next = curr->next;
    }

    free(self);
}

- (oneway void)release
{
    if (!refCount || !--refCount)
	[self dealloc];
}

- (id)retain
{
    refCount++;
    return self;
}

- (unsigned int)retainCount
{
    return refCount;
}

@end /* NSZone */
