Skip to content

Commit

Permalink
Add class plainstring.
Browse files Browse the repository at this point in the history
It is a simple string class, which automatically manages its buffer, provides assignment, comparison and conversion to char const*.

git-svn-id: svn://tron.homeunix.org/simutrans/simutrans/trunk@4981 8aca7d54-2c30-db11-9de9-000461428c89
  • Loading branch information
chmallon committed Dec 4, 2011
1 parent c6ec811 commit a85b419
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 0 deletions.
14 changes: 14 additions & 0 deletions dataobj/loadsave.cc
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
#include "../simversion.h"
#include "../simmem.h"
#include "../simdebug.h"
#include "../utils/plainstring.h"
#include "loadsave.h"

#include "../utils/simstring.h"
Expand Down Expand Up @@ -775,6 +776,19 @@ void loadsave_t::rdwr_str(char* s, size_t const size)
}


void loadsave_t::rdwr_str(plainstring& s)
{
if (is_loading()) {
char buf[1024];
rdwr_str(buf, lengthof(buf));
s = buf;
} else {
char const* tmp = s.c_str();
rdwr_str(tmp);
}
}


void loadsave_t::start_tag(const char *tag)
{
if( is_xml() ) {
Expand Down
4 changes: 4 additions & 0 deletions dataobj/loadsave.h
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

#define INVALID_RDWR_ID (-1)

class plainstring;

/**
* loadsave_t:
*
Expand Down Expand Up @@ -106,6 +108,8 @@ class loadsave_t {
// s is a buf of size given
void rdwr_str(char* s, size_t size);

void rdwr_str(plainstring&);

// only meaningful for XML
void start_tag( const char *tag );
void end_tag( const char *tag );
Expand Down
50 changes: 50 additions & 0 deletions utils/plainstring.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
#ifndef PLAINSTRING_H
#define PLAINSTRING_H

#include <cstring>

#include "../simtypes.h"


class plainstring
{
public:
plainstring() : str_() {}

plainstring(char const* const s) : str_(copy_string(s)) {}

~plainstring() { delete [] str_; }

plainstring& operator =(char const* const o)
{
char* const s = copy_string(o);
delete [] str_;
str_ = s;
return *this;
}

char const* c_str() const { return str_; }

operator char const*() const { return str_; }
operator char*() { return str_; }

bool operator ==(char const* const o) const { return str_ && o ? std::strcmp(str_, o) == 0 : str_ == o; }
bool operator !=(char const* const o) const { return !(*this == o); }

private:
static char* copy_string(char const* const s)
{
if (s) {
size_t const n = std::strlen(s) + 1;
return static_cast<char*>(std::memcpy(new char[n], s, n));
} else {
return 0;
}
}

char* str_;
};

void free(plainstring const&) DELETED;

#endif

0 comments on commit a85b419

Please sign in to comment.