refcountedstring/StringValue.cpp

49 lines
1.2 KiB
C++

#include "StringValue.h"
#include <stdexcept>
#include <cstring>
StringValue::StringValue(char* data)
:_data(data), _size(std::strlen(data) + 1), _refs(1)
{}
void StringValue::operator++()
{ _refs++; }
void StringValue::operator--()
{
_refs--;
if (_refs == 0)
{
delete[] _data;
delete this;
/* This might seem scary, but StringValues are dynamically allocated and own themselves,
* thus when no longer referenced the object can -- and should -- commit suicide. */
}
}
const char& StringValue::operator[](size_t index) const
{
if (index > _size - 2)
throw std::out_of_range("Index out of range!");
return _data[index];
}
char& StringValue::operator[](size_t index)
{ return const_cast<char&>(const_cast<const StringValue*>(this)->operator[](index)); }
StringValue::operator const char*() const
{ return _data; }
size_t StringValue::size() const
{ return _size - 1; }
size_t StringValue::index_of(char* c) const
{
size_t index = c - _data; // this is totally safe pointer-arithmetic
if (index <= this->size()) // if it is within our data
return index;
else
throw std::invalid_argument("char* not within held data!");
}