#import <RCString.h>
/*
    Copyright (C) 1992. Bruce Ediger.

      This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU Library General Public License.
*/

//
// category of "miscellaneous" methods.
//

@implementation RCString (Misc)

- empty
{
	if (p->n > 1)
		[self copyReference];

	if (p->s) {
		free(p->s);
		p->s = NULL;
	}
	p->l = 0;
	return self;
}

- toUpper
{
	int icIndex;

	if (p->n > 1)
		[self copyReference];

	if (p->l > 1)
		for (icIndex = 0; icIndex < p->l; ++icIndex) {
			if (p->s[icIndex] <= 'z' && p->s[icIndex] >= 'a')
				p->s[icIndex] = p->s[icIndex] - 'a' + 'A'; 
		}
	return self;
}

- toLower
{
	int icIndex;

	if (p->n > 1)
		[self copyReference];

	if (p->l > 1)
		for (icIndex = 0; icIndex < p->l; ++icIndex) {
			if (p->s[icIndex] <= 'Z' && p->s[icIndex] >= 'A')
				p->s[icIndex] = p->s[icIndex] - 'A' + 'a'; 
		}
	return self;
}

- replaceWithAsciiString: (char *)aString
{
	if(--p->n == 0)
		free(p->s);
	else
		p = (struct srep *) malloc(sizeof(struct srep));

	if (p) {
		p->n = 1;
		if (aString)
			p->l = strlen(aString) + 1;
		else
			p->l = 1;
		p->s = malloc(p->l);
		if (p->s && aString)
				bcopy(aString, p->s, p->l);
		else if (p->s && aString == NULL)
			*(p->s) = '\0';
	}
	return self;
}

// replace this objects internal string rep with another
// object's internal string rep.
- replaceWithObject: (RCString *)anObject
{
	if (p->n == 1) {
		// this object is the only reference. it's safe
		// to just free() the whole internal rep
		if (p->s)
			free(p->s);
		free(p);
	} else {
		--p->n;  // decrement ref count of previous internal rep
	}
	p = anObject->p;
	++p->n;
	return self;
}

// A hook into object to perform some arbitrary 
// processing on the object's ASCIIZ string.
// This may not be too clever.
- performArbitraryFunction:(int (*)())someFunction
{
	if (someFunction != NULL) {
		if (p->n > 1)
			[self copyReference];

		if ((*someFunction)(p->s)) {
			p->l = strlen(p->s);
		}
	}

	return self;
}

@end
