#ifndef STRINGDICT_H
#define STRINGDICT_H
#include "cdt.h"
#include <string>
#include <algorithm>
#include <iostream>
struct StringDict {
StringDict();
void init();
const char *enter(const char *val);
void release(const char *val);
void ref(const char *val); private:
Dict_t *dict;
};
extern StringDict g_stringDict;
struct DString { typedef const char *iterator;
typedef const char *const_iterator;
typedef size_t size_type;
static const size_type npos;
DString() : val(0) {}
DString(const char *v) : val(g_stringDict.enter(v)) {}
DString(const DString &ds) : val(ds.val) {
g_stringDict.ref(val);
}
DString(const std::string &s) : val(g_stringDict.enter(s.c_str())) {}
~DString() {
g_stringDict.release(val);
}
DString &operator =(const DString &ds) {
const char *old = val; g_stringDict.ref(val = ds.val);
g_stringDict.release(old);
return *this;
}
operator std::string() const {
return val?std::string(val):std::string();
}
bool operator <(const DString &ds) const {
return val<ds.val;
}
bool operator ==(const DString &ds) const {
return val==ds.val;
}
bool operator !=(const DString &ds) const {
return val!=ds.val;
}
const char *c_str() const {
return val;
}
size_type size() const {
if(!val)
return 0;
return strlen(val);
}
size_type length() const {
return size();
}
bool empty() const {
return length()==0;
}
void clear() {
*this = 0;
}
char operator[](size_t pos) const {
return val[pos];
}
const char &operator[](size_t pos) {
return val[pos];
}
iterator begin() {
return val;
}
iterator end() {
return val+size();
}
const_iterator begin() const {
return val;
}
const_iterator end() const {
return val+size();
}
size_type find(char c,size_type pos) const {
if(pos>=size())
return npos;
const_iterator i = std::find(begin()+pos,end(),c);
if(i==end())
return npos;
else
return i-begin();
}
DString substr(size_type pos,size_type len) const {
DString ret;
if(pos>=size())
return ret;
ret.assign(begin()+pos,len);
return ret;
}
DString &assign(const char *v,size_type len) {
if(!v) {
return *this = 0;
}
if(len>=strlen(v))
return *this = v;
char *copy = new char[len+1];
strncpy(copy,v,len);
copy[len] = 0;
*this = copy;
delete [] copy;
return *this;
}
private:
const char *val;
};
inline std::ostream &operator <<(std::ostream &os,const DString &s) {
if(s.length())
os << s.c_str();
return os;
}
#include "common/dgxep.h"
struct DictStringLost : DGException {
const char *s;
DictStringLost(const char *s) :
DGException("StringDict internal exception: string lost"),
s(s)
{}
};
#endif // STRINGDICT_H