/* -*-C-*-
*******************************************************************************
*
* File:         SimpleString.m
* RCS:          $Header: /usr/local/lib/cvs/EnhanceMail/SimpleString.m,v 1.1.1.4 1996/06/23 16:10:11 cedman Exp $
* Description:  
* Author:       Carl Edman
* Created:      Tue Oct 17 23:45:45 1995
* Modified:     Sat Jun 22 19:10:45 1996 (Carl Edman) cedman@capitalist.princeton.edu
* Language:     C
* Package:      N/A
* Status:       Experimental (Do Not Distribute)
*
* (C) Copyright 1995, but otherwise this file is perfect freeware.
*
*******************************************************************************
*/

#import "SimpleString.h"

#define START 64

@implementation SimpleString
- init
   {
   cur=data=malloc(START);
   *cur='\0';
   return [super init];
   }

- free
   {
   free(data);
   return [super free];
   }

- grow
   {
   int pos=cur-data;
   data=realloc(data,malloc_size(data)*2);
   cur=data+pos;   
   return self;
   }

- (char *)string
   {
   return data;
   }

- (int)length
   {
   return cur-data;
   }

- empty
   {
   cur=data;
   *cur='\0';
   return self;
   }

- (int)appendChar:(char)c
   {
   while (cur+1>=data+malloc_size(data)) [self grow];
   *cur++=c;
   *cur='\0';
   return cur-data;
   }

- (int)appendString:(const char *)str
   {
   return [self appendString:str length:strlen(str)];
   }

- (int)appendString:(const char *)str length:(int)len
   {
   while (cur+len>=data+malloc_size(data)) [self grow];
   while(len>0) { *cur++=*str++; len--; }
   *cur='\0';
   return cur-data;
   }

- (int)appendStream:(NXStream *)s
   {
   int c;
   
   while ((c=NXRead(s,cur,data+malloc_size(data)-cur))>0)
      {
      cur+=c;
      if (cur>=data+malloc_size(data)) [self grow];
      }
   
   *cur='\0';
   return cur-data;
   }

- (int)appendFile:(int)fd
   {
   int c;
   
   while ((c=read(fd,cur,data+malloc_size(data)-cur))>0)
      {
      cur+=c;
      if (cur>=data+malloc_size(data)) [self grow];
      }
   
   *cur='\0';
   return cur-data;
   }

- (int)writeFile:(int)fd
   {
   char *pos;
   int c;

   for(pos=data;pos<cur;)
      {
      c=write(fd,pos,cur-pos);
      if (c<0) return c;
      pos+=c;
      }
   
   return cur-data;
   }

- (int)appendSimpleString:(id)sstr
   {
   char *d=[sstr string];
   int l=[sstr length];

   return [self appendString:d length:l];
   }

- (int)includeSimpleString:(id)sstr
   {
   int ret;
   ret=[self appendSimpleString:sstr];
   [sstr free];
   return ret;
   }

- (int)lastChar
   {
   return (cur>data) ? *(cur-1) : -1;
   }
@end
