xref: /haiku/src/kits/shared/HashString.cpp (revision b671e9bbdbd10268a042b4f4cc4317ccd03d105e)
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
16 HashString::HashString()
17 	: fLength(0),
18 	  fString(NULL)
19 {
20 }
21 
22 // copy constructor
23 HashString::HashString(const HashString &string)
24 	: fLength(0),
25 	  fString(NULL)
26 {
27 	*this = string;
28 }
29 
30 // constructor
31 HashString::HashString(const char *string, int32 length)
32 	: fLength(0),
33 	  fString(NULL)
34 {
35 	SetTo(string, length);
36 }
37 
38 // destructor
39 HashString::~HashString()
40 {
41 	Unset();
42 }
43 
44 // SetTo
45 bool
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
59 HashString::Unset()
60 {
61 	if (fString) {
62 		delete[] fString;
63 		fString = NULL;
64 	}
65 	fLength = 0;
66 }
67 
68 // Truncate
69 void
70 HashString::Truncate(int32 newLength)
71 {
72 	if (newLength < 0)
73 		newLength = 0;
74 	if (newLength < fLength) {
75 		char *string = fString;
76 		int32 len = fLength;
77 		fString = NULL;
78 		len = 0;
79 		if (!_SetTo(string, newLength)) {
80 			fString = string;
81 			fLength = newLength;
82 			fString[fLength] = '\0';
83 		} else
84 			delete[] string;
85 	}
86 }
87 
88 // GetString
89 const char *
90 HashString::GetString() const
91 {
92 	if (fString)
93 		return fString;
94 	return "";
95 }
96 
97 // =
98 HashString &
99 HashString::operator=(const HashString &string)
100 {
101 	if (&string != this)
102 		_SetTo(string.fString, string.fLength);
103 	return *this;
104 }
105 
106 // ==
107 bool
108 HashString::operator==(const HashString &string) const
109 {
110 	return (fLength == string.fLength
111 			&& (fLength == 0 || !strcmp(fString, string.fString)));
112 }
113 
114 // _SetTo
115 bool
116 HashString::_SetTo(const char *string, int32 length)
117 {
118 	bool result = true;
119 	Unset();
120 	if (string && length > 0) {
121 		fString = new(std::nothrow) char[length + 1];
122 		if (fString) {
123 			memcpy(fString, string, length);
124 			fString[length] = '\0';
125 			fLength = length;
126 		} else
127 			result = false;
128 	}
129 	return result;
130 }
131 
132