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