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