1
#ifndef CHILON_CSTRING_HPP
2
#define CHILON_CSTRING_HPP
3
4
#include <memory>
5
6
#include <boost/utility.hpp>
7
8
/// \file Utilities for using cstring's allocated with malloc
9
10
namespace chilon {
11
/**
12
 * Represents a cstring
13
 */
14
struct cstring_base : boost::noncopyable {
15
    char const *str() const { return str_; }
16
    char *str()             { return str_; }
17
18
    bool empty() const  { return str_; }
19
20
    cstring_base() : str_(0) {}
21
    cstring_base(char *str) : str_(str) {}
22
  protected:
23
    char *str_;
24
};
25
26
// a cstring which must be dynamically allocated with cmalloc
27
struct cstring_allocated : cstring_base {
28
    cstring_allocated() : cstring_base() {}
29
    cstring_allocated(char *str) : cstring_base(str) {}
30
31
    cstring_allocated(cstring_allocated&& rhs) : cstring_base(rhs.str_) { rhs.str_ = 0; }
32
    ~cstring_allocated() { if (str_) free(str_); }
33
};
34
35
// a cstring which may be dynamic or stack based
36
struct cstring : cstring_base {
37
    bool allocated() const { return allocated_; }
38
39
    cstring() : cstring_base(), allocated_(false) {}
40
41
    cstring(char * const str, bool const allocated = false)
42
      : cstring_base(str), allocated_(allocated) {}
43
44
    cstring(char const * const str, bool const allocated = false)
45
      : cstring_base(const_cast<char *>(str)), allocated_(allocated) {}
46
47
    ~cstring() { if (allocated()) free(str_); }
48
49
    cstring(cstring&& rhs)
50
      : cstring_base(rhs.str_), allocated_(rhs.allocated_)
51
    { rhs.allocated_ = false; }
52
  private:
53
    bool allocated_;
54
};
55
56
}
57
58
#endif