1// String.cpp
2
3#include <new>
4#include <string.h>
5
6#include "String.h"
7
8// strnlen
9size_t
10strnlen(const char *str, size_t maxLen)
11{
12	if (str) {
13		size_t origMaxLen = maxLen;
14		while (maxLen > 0 && *str != '\0') {
15			maxLen--;
16			str++;
17		}
18		return origMaxLen - maxLen;
19	}
20	return 0;
21}
22
23
24/*!
25	\class String
26	\brief A very simple string class.
27*/
28
29// constructor
30String::String()
31	: fLength(0),
32	  fString(NULL)
33{
34}
35
36// copy constructor
37String::String(const String &string)
38	: fLength(0),
39	  fString(NULL)
40{
41	*this = string;
42}
43
44// constructor
45String::String(const char *string, int32 length)
46	: fLength(0),
47	  fString(NULL)
48{
49	SetTo(string, length);
50}
51
52// destructor
53String::~String()
54{
55	Unset();
56}
57
58// SetTo
59bool
60String::SetTo(const char *string, int32 maxLength)
61{
62	if (string) {
63		if (maxLength > 0)
64			maxLength = strnlen(string, maxLength);
65		else if (maxLength < 0)
66			maxLength = strlen(string);
67	}
68	return _SetTo(string, maxLength);
69}
70
71// Unset
72void
73String::Unset()
74{
75	if (fString) {
76		delete[] fString;
77		fString = NULL;
78	}
79	fLength = 0;
80}
81
82// Truncate
83void
84String::Truncate(int32 newLength)
85{
86	if (newLength < 0)
87		newLength = 0;
88	if (newLength < fLength) {
89		char *string = fString;
90		fString = NULL;
91		if (!_SetTo(string, newLength)) {
92			fString = string;
93			fLength = newLength;
94			fString[fLength] = '\0';
95		} else
96			delete[] string;
97	}
98}
99
100// GetString
101const char *
102String::GetString() const
103{
104	if (fString)
105		return fString;
106	return "";
107}
108
109// =
110String &
111String::operator=(const String &string)
112{
113	if (&string != this)
114		_SetTo(string.fString, string.fLength);
115	return *this;
116}
117
118// ==
119bool
120String::operator==(const String &string) const
121{
122	return (fLength == string.fLength
123			&& (fLength == 0 || !strcmp(fString, string.fString)));
124}
125
126// _SetTo
127bool
128String::_SetTo(const char *string, int32 length)
129{
130	bool result = true;
131	Unset();
132	if (string && length > 0) {
133		fString = new(std::nothrow) char[length + 1];
134		if (fString) {
135			memcpy(fString, string, length);
136			fString[length] = '\0';
137			fLength = length;
138		} else
139			result = false;
140	}
141	return result;
142}
143
144