1 // String.cpp 2 3 #include <new.h> 4 #include <string.h> 5 6 #include "String.h" 7 8 // strnlen 9 size_t 10 strnlen(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 30 String::String() 31 : fLength(0), 32 fString(NULL) 33 { 34 } 35 36 // copy constructor 37 String::String(const String &string) 38 : fLength(0), 39 fString(NULL) 40 { 41 *this = string; 42 } 43 44 // constructor 45 String::String(const char *string, int32 length) 46 : fLength(0), 47 fString(NULL) 48 { 49 SetTo(string, length); 50 } 51 52 // destructor 53 String::~String() 54 { 55 Unset(); 56 } 57 58 // SetTo 59 bool 60 String::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 72 void 73 String::Unset() 74 { 75 if (fString) { 76 delete[] fString; 77 fString = NULL; 78 } 79 fLength = 0; 80 } 81 82 // Truncate 83 void 84 String::Truncate(int32 newLength) 85 { 86 if (newLength < 0) 87 newLength = 0; 88 if (newLength < fLength) { 89 char *string = fString; 90 int32 len = fLength; 91 fString = NULL; 92 len = 0; 93 if (!_SetTo(string, newLength)) { 94 fString = string; 95 fLength = newLength; 96 fString[fLength] = '\0'; 97 } else 98 delete[] string; 99 } 100 } 101 102 // GetString 103 const char * 104 String::GetString() const 105 { 106 if (fString) 107 return fString; 108 return ""; 109 } 110 111 // = 112 String & 113 String::operator=(const String &string) 114 { 115 if (&string != this) 116 _SetTo(string.fString, string.fLength); 117 return *this; 118 } 119 120 // == 121 bool 122 String::operator==(const String &string) const 123 { 124 return (fLength == string.fLength 125 && (fLength == 0 || !strcmp(fString, string.fString))); 126 } 127 128 // _SetTo 129 bool 130 String::_SetTo(const char *string, int32 length) 131 { 132 bool result = true; 133 Unset(); 134 if (string && length > 0) { 135 fString = new(nothrow) char[length + 1]; 136 if (fString) { 137 memcpy(fString, string, length); 138 fString[length] = '\0'; 139 fLength = length; 140 } else 141 result = false; 142 } 143 return result; 144 } 145 146