#ifndef CHILON_CSTRING_HPP
#define CHILON_CSTRING_HPP
#include <memory>
#include <boost/utility.hpp>
/// \file Utilities for using cstring's allocated with malloc
namespace chilon {
/**
* Represents a cstring
*/
struct cstring_base : boost::noncopyable {
char const *str() const { return str_; }
char *str() { return str_; }
bool empty() const { return str_; }
cstring_base() : str_(0) {}
cstring_base(char *str) : str_(str) {}
protected:
char *str_;
};
// a cstring which must be dynamically allocated with cmalloc
struct cstring_allocated : cstring_base {
cstring_allocated() : cstring_base() {}
cstring_allocated(char *str) : cstring_base(str) {}
cstring_allocated(cstring_allocated&& rhs) : cstring_base(rhs.str_) { rhs.str_ = 0; }
~cstring_allocated() { if (str_) free(str_); }
};
// a cstring which may be dynamic or stack based
struct cstring : cstring_base {
bool allocated() const { return allocated_; }
cstring() : cstring_base(), allocated_(false) {}
cstring(char * const str, bool const allocated = false)
: cstring_base(str), allocated_(allocated) {}
cstring(char const * const str, bool const allocated = false)
: cstring_base(const_cast<char *>(str)), allocated_(allocated) {}
~cstring() { if (allocated()) free(str_); }
cstring(cstring&& rhs)
: cstring_base(rhs.str_), allocated_(rhs.allocated_)
{ rhs.allocated_ = false; }
private:
bool allocated_;
};
}
#endif