// StringBuilder.C // // Written 19 Feb 1996 by Max Hailperin . // // Implementation of a class for incrementally building up strings // without knowing in advance their final size -- see StringBuilder.h // // The implementation techinique used is a "dynamically growing" array // where the "growth" really consists of copying the array into twice // as big a one when it is outgrown. #include "StringBuilder.h" class StringBuilderRep{ public: char *buf; int size; int nextFree; void reset(); }; static const int initialSize = 20; // non-critical, seems reasonable void StringBuilderRep::reset(){ size = initialSize; buf = new char[size]; nextFree = 0; } StringBuilder::StringBuilder(){ rep = new StringBuilderRep; rep->reset(); } StringBuilder::~StringBuilder(){ delete [] rep->buf; delete rep; } void StringBuilder::add(char c){ if(rep->nextFree == rep->size){ char *oldBuf = rep->buf; rep->size *= 2; rep->buf = new char[rep->size]; for(int i = 0; i < rep->nextFree; i++) rep->buf[i] = oldBuf[i]; delete [] oldBuf; } rep->buf[rep->nextFree++] = c; } char * StringBuilder::string(){ add('\0'); char *s = rep->buf; rep->reset(); return s; }