// This file is a part of Framsticks GDK library.
// Copyright (C) 2002-2006  Szymon Ulatowski.  See LICENSE.txt for details.
// Refer to http://www.frams.alife.pl/ for further information.

#ifndef _SSTRING_H_
#define _SSTRING_H_

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

class SBuf
{
char *txt;
int used;	///< data size
int size;	///< buffer size, not including \0, special case: 0==buffer not allocated
int refcount;	///< buffer is used by 'refcount' objects.
void initEmpty();
void ensureSize(int wantsize, int memhint);
void copyFrom(const char* ch, int chlen=-1, int memhint=-1);
void freeBuf();
void append(const char* ch, int chlen=-1);
static SBuf empty;
SBuf(int initsize, int memhint=-1);
friend class SString;
SBuf(const SBuf& b) {}
public:
SBuf();
~SBuf();
};

/// (not so) simple text string class

class SString
{
private:
SBuf *buf;	///< buffer
int appending;  ///< append mode, changes can occur after character # 'appending'
int memhint;	///< sstring will allocate bigger chunks of memory

void initEmpty();
int guessMemSize(int request);
void copyFrom(SString &from); ///< copy from SString, reference if possible
void detach(); ///< detach from shared buffer, if any
void detachEmpty(int ensuresize=0); ///< detach and make empty
void detachCopy(int ensuresize=0); ///< detach and make private copy

public:
SString(); ///< make an empty string
SString(const char*t,int t_len=-1); ///< make a string from char*
SString(int x); ///< string with initial buffer size
SString(const SString& from); ///< duplicate string
~SString();

void copyFrom(const char* ch, int chlen=-1); ///< copy string, length of -1 == unknown

void* operator new(size_t s, void* mem) {return mem;}
#ifdef _MSC_VER
void operator delete(void* mem, void* t) {}
#endif
void* operator new(size_t s) {return malloc(sizeof(SString));}
void operator delete(void* mem) {free(mem);}

int len() const {return buf->used;} ///< get string length
void shrink(); ///< free unnecessary buffer

/// after this call, you can modify sstring directly.
/// returned value is the pointer to the internal buffer.
/// <B>ensuresize</B> is minimal value of bytes you need,
/// the buffer will be resized as needed.
/// all "direct" operations have to leave the buffer with trailing '\0'
/// at the end. endWrite() will search for this value in order to determine
/// new string length.
/// <P>Sample:<CODE>
/// SString t;
/// sprintf(t.directWrite(50),"a=%d,b=%f",a,b);
/// t.endWrite();</CODE>
char *directWrite(int ensuresize=-1);
//char *directWrite();
/// like directWrite, but it returns the pointer to the first char after current string
/// for easy appending. <B>maxappend</B> is minimum of character in buffer
/// that can be appended after this call.
/// <P>Sample:<CODE>
/// SString t;
/// sprintf(t.directAppend(10),"c=%d",c);
/// t.endAppend();</CODE>
char *directAppend(int maxappend=0);
/// update string length, after directWrite.
/// you don't have to to call endWrite after directWrite if the string's length doesn't change.
/// optional <B>newlength</B> parameter gives a chance to further optimize
/// this operation if you know exact length of resulting string.
/// <P>Sample:<CODE>
/// SString t("samplestring");
/// strncpy(t.directWrite(50),src,bytecount);
/// t.endWrite(bytecount);</CODE>
void endWrite(int newlength=-1);
/// update string length, after directAppend.
/// you will usually need to call endAppend (or endWrite) after directAppend,
/// because the purpose of directAppend is to change string's length.
/// optional <B>appendlength</B> parameter gives a chance to further optimize
/// this operation if you know exact length of the appended string.
/// <P>Sample:<CODE>
/// SString t("samplestring");
/// strncpy(t.directAppend(50),src,bytecount);
/// t.endAppend(bytecount);</CODE>
void endAppend(int appendlength=-1);
/// argument is the amount of memory, that will be probably used
/// by this string instance. string can use this value
/// to optimize memory allocation (bigger chunks will be allocated).
void memoryHint(int howbig);

/// find a character in SString.
/// return index if the character was found or -1 otherwise.
int indexOf(int character,int start=0) const;

/// find a substring.
/// return index if the substring was found or -1 otherwise.
int indexOf(const char *substring,int start=0) const;

/// find a substring.
/// return index if the substring was found or -1 otherwise.
int indexOf(const SString & substring,int start=0) const;

operator const char*() const {return buf->txt;} ///< get SString's readonly buffer
//operator char*() {detachCopy(len()); return buf->txt;} ///< get SString's writable buffer
void operator=(const char*t); ///< assign from const char*
//void operator=(int x) {free(txt);nowy(x);} ///< clear string and make new empty one
void operator=(const SString &s);

void append(const char *txt,int count);
SString operator+(const SString &s) const;
void operator+=(int x); ///< append x spaces after current string
void operator+=(const char*); ///< append char* contents
void operator+=(const SString&); ///< append other SString

int equals(const SString &s) const; ///< TRUE if equal
int operator==(const SString &s) const {return equals(s);} ///< TRUE if equal
const char* operator()(int p) const {return buf->txt+p;} ///< pointer to p'th character in SString
char operator[](int i) {return buf->txt[i];} ///< get char like in array

/// return a substring of the current string
SString substr(int begin, int length=1<<30) const;

/// simple tokenization:
/// starting at <B>pos</B>, get next substring delimited by <B>separator</B> character
/// and put it in output parameter <B>token</B>.
/// <B>pos</B> is moved accordingly.
/// returns <B>false</B> if no more tokens are available or <B>true</B> otherwise.
int getNextToken(int& pos,SString &token,char separator) const;

void operator+=(char ch) {directAppend(1)[0]=ch;endAppend(1);} ///< append single character

int startsWith(const char *pattern) const;
char charAt(int pos) const {return buf->txt[pos];}

static const SString& valueOf(int);
static const SString& valueOf(double);

static SString empty;
};

#endif
