Changeset 7327
- Timestamp:
- Sep 3, 2010, 12:19:53 AM (14 years ago)
- Location:
- code/branches/doc
- Files:
-
- 1 deleted
- 12 edited
Legend:
- Unmodified
- Added
- Removed
-
code/branches/doc/src/libraries/util/Serialise.h
r7182 r7327 29 29 /** 30 30 @file 31 @ingroup Util 31 32 @brief Functions to serialise most of the types/classed used in Orxonox 32 33 */ … … 53 54 template <class T> inline bool checkEquality( const T& variable, uint8_t* mem ); 54 55 55 56 56 57 // =========== char* 57 58 58 59 inline uint32_t returnSize( char*& variable ) 59 60 { 60 61 return strlen(variable)+1; 61 62 } 62 63 63 64 inline void saveAndIncrease( char*& variable, uint8_t*& mem ) 64 65 { … … 66 67 mem += returnSize(variable); 67 68 } 68 69 69 70 inline void loadAndIncrease( char*& variable, uint8_t*& mem ) 70 71 { … … 76 77 mem += len; 77 78 } 78 79 79 80 inline bool checkEquality( char*& variable, uint8_t* mem ) 80 81 { 81 82 return strcmp(variable, (char*)mem)==0; 82 83 } 83 84 84 85 // =================== Template specialisation stuff ============= 85 86 … … 423 424 return memcmp(&temp, mem, sizeof(uint64_t))==0; 424 425 } 425 426 426 427 // =========== string 427 428 -
code/branches/doc/src/libraries/util/SharedPtr.cc
r7284 r7327 27 27 */ 28 28 29 /** 30 @file 31 @brief Static linkage of the SmallObjectAllocator used by SharedPtr. 32 */ 33 29 34 #include "SharedPtr.h" 30 35 31 36 namespace orxonox 32 37 { 33 SmallObjectAllocator& createSharedCounterPool()38 namespace detail 34 39 { 35 static SmallObjectAllocator instance(sizeof(SharedCounterImpl<void>)); 36 return instance; 40 SmallObjectAllocator& createSharedCounterPool() 41 { 42 static SmallObjectAllocator instance(sizeof(SharedCounterImpl<void>)); 43 return instance; 44 } 37 45 } 38 46 } -
code/branches/doc/src/libraries/util/SharedPtr.h
r7284 r7327 27 27 */ 28 28 29 /** 30 @defgroup SharedPtr SharedPtr<T> 31 @ingroup Util Object 32 */ 33 34 /** 35 @file 36 @ingroup Util SharedPtr 37 @brief Definition of the SharedPtr template that is used to manage pointers. 38 39 @anchor SharedPtrExample 40 41 The orxonox::SharedPtr template can be used to manage a pointer to an object 42 that was created with new. The SharedPtr acts like the pointer itself, but it 43 keeps track of the number of references to it. If all references are removed, 44 SharedPtr deletes the managed object automatically. 45 46 Example: 47 48 Classic implementation using new and delete: 49 @code 50 void someFunction() 51 { 52 MyClass* object = new MyClass(); // Create a new instance of MyClass 53 54 object->myFunction(); // Calls MyClass::myFunction() 55 56 delete object; // Delete the object at the end of the scope 57 } 58 @endcode 59 60 The same function using SharedPtr: 61 @code 62 void someFunction() 63 { 64 SharedPtr<MyClass> object = new MyClass(); // Create a new instance of MyClass and store its pointer in a SharedPtr 65 66 object->myFunction(); // Calls MyClass::myFunction() 67 68 } // At the end of the scope, the SharedPtr is destroyed. Because no other SharedPtrs 69 // point at the object, the object itself is also destroyed automatically 70 @endcode 71 72 This is especially handy if you do not know what will happen with an object that was 73 created with new, for example if you pass it to another object. If multiple instances 74 share a pointer to the same object, none of these instances can delete the object 75 without interfering with the other instances. But if none of the instances destroy the 76 object, it will never be destroyed and results in a memory leak. With a SharedPtr 77 however you don't have to think about destroying the object, because the SharedPtr 78 itself keeps track of the references. 79 80 Example: 81 82 Classic implementation using new and delete: 83 @code 84 class OtherClass // Declaration of some class 85 { 86 public: 87 OtherClass(MyClass* object) // Constructor 88 { 89 this->object_ = object; // Assigns the pointer to the member variable object_ 90 } 91 92 ~OtherClass() // Destructor 93 { 94 ??? // What to do with object_? 95 } 96 97 private: 98 MyClass* object_; // A pointer to the object 99 }; 100 101 void someFunction() 102 { 103 MyClass* object = new MyClass(); // Create a new instance of MyClass 104 105 OtherClass* other1 = new OtherClass(object); // Create an instance of OtherClass and pass the object pointer 106 OtherClass* other2 = new OtherClass(object); // " 107 OtherClass* other3 = new OtherClass(object); // " 108 109 ??? // What happens with object now? 110 } 111 @endcode 112 113 If you use SharedPtr<MyClass> instead of a classic MyClass* pointer, the instance of 114 MyClass would be automatically destroyed if all instances of OtherClass are destroyed. 115 You don't need any code in the destructor and you can completely forget about the 116 object, because its managed by the SharedPtr. 117 118 The same code using SharedPtr: 119 @code 120 class OtherClass // Declaration of some class 121 { 122 public: 123 OtherClass(const SharedPtr<MyClass>& object) // Constructor 124 { 125 this->object_ = object; // Assigns the pointer to the member variable object_ 126 } 127 128 private: 129 SharedPtr<MyClass> object_; // A SharedPtr to the object 130 }; 131 132 void someFunction() 133 { 134 SharedPtr<MyClass> object = new MyClass(); // Create a new instance of MyClass 135 136 OtherClass* other1 = new OtherClass(object); // Create an instance of OtherClass and pass the object pointer 137 OtherClass* other2 = new OtherClass(object); // " 138 OtherClass* other3 = new OtherClass(object); // " 139 140 } // The SmartPtr "object" is destroyed at the end of the scope, 141 // but the three instances of OtherClass keep the object alive 142 // until they are all destroyed. 143 @endcode 144 */ 145 29 146 #ifndef _SharedPtr_H__ 30 147 #define _SharedPtr_H__ … … 39 156 namespace orxonox 40 157 { 41 class SharedCounter 42 { 43 public: 44 SharedCounter() : count_(1) {} 45 virtual void destroy() = 0; 46 47 int count_; 48 }; 49 50 template <class T> 51 class SharedCounterImpl : public SharedCounter 52 { 53 public: 54 SharedCounterImpl(T* pointer) : pointer_(pointer) {} 55 56 void destroy() 57 { 58 delete this->pointer_; 59 } 60 61 private: 62 T* pointer_; 63 }; 64 65 _UtilExport SmallObjectAllocator& createSharedCounterPool(); 66 67 FORCEINLINE SmallObjectAllocator& getSharedCounterPool() 68 { 69 static SmallObjectAllocator& instance = createSharedCounterPool(); 70 return instance; 158 namespace detail 159 { 160 /// BaseClass of SharedCounterImpl, has a counter that is initialized with 1 161 class SharedCounter 162 { 163 public: 164 SharedCounter() : count_(1) {} 165 virtual void destroy() = 0; 166 167 int count_; 168 }; 169 170 /// Child class of SharedCounter, keeps a pointer to an object of type T that can be destroyed with destroy() 171 template <class T> 172 class SharedCounterImpl : public SharedCounter 173 { 174 public: 175 SharedCounterImpl(T* pointer) : pointer_(pointer) {} 176 177 void destroy() 178 { 179 delete this->pointer_; 180 } 181 182 private: 183 T* pointer_; 184 }; 185 186 _UtilExport SmallObjectAllocator& createSharedCounterPool(); 187 188 FORCEINLINE SmallObjectAllocator& getSharedCounterPool() 189 { 190 static SmallObjectAllocator& instance = createSharedCounterPool(); 191 return instance; 192 } 71 193 } 72 194 195 /** 196 @brief The SharedPtr template is a utility to manage pointers to an object. 197 @param T The type of the managed object 198 199 SharedPtr acts like a real pointer, except that it keeps track of the number of 200 references to the object. If the the number of references drops to zero, the 201 object is destroyed automatically. 202 203 @see See @ref SharedPtrExample "this description" for some examples and more information. 204 205 @note The number of references is stored in a separate object that is shared 206 among all instances of SharedPtr that point to the same pointer. This object is 207 also responsible for destroying the pointer if the reference counter becomes zero. 208 */ 73 209 template <class T> 74 210 class SharedPtr … … 78 214 79 215 public: 216 /// Default constructor, the pointer is set to NULL. 80 217 inline SharedPtr() : pointer_(0), counter_(0) 81 218 { 82 219 } 83 220 221 /// Constructor, creates a SharedPtr that points to @a pointer, increments the counter. 84 222 inline SharedPtr(T* pointer) : pointer_(pointer), counter_(0) 85 223 { 86 224 if (this->pointer_) 87 225 { 88 void* chunk = getSharedCounterPool().alloc();89 this->counter_ = new (chunk) SharedCounterImpl<T>(this->pointer_);226 void* chunk = detail::getSharedCounterPool().alloc(); 227 this->counter_ = new (chunk) detail::SharedCounterImpl<T>(this->pointer_); 90 228 } 91 229 } 92 230 231 /// Copy-constructor, this SharedPtr now points to the same object like the other SharedPtr, increments the counter. 93 232 inline SharedPtr(const SharedPtr& other) : pointer_(other.pointer_), counter_(other.counter_) 94 233 { … … 97 236 } 98 237 238 /// Copy-constructor for SharedPtr with another template agument, increments the counter. 99 239 template <class O> 100 240 inline SharedPtr(const SharedPtr<O>& other) : pointer_(other.pointer_), counter_(other.counter_) … … 104 244 } 105 245 246 /// Destructor, decrements the counter and deletes the object if the counter becomes zero. 106 247 inline ~SharedPtr() 107 248 { … … 113 254 { 114 255 this->counter_->destroy(); 115 getSharedCounterPool().free(this->counter_);256 detail::getSharedCounterPool().free(this->counter_); 116 257 } 117 258 } 118 259 } 119 260 261 /// Assigns a new object, decrements the counter of the old object, increments the counter of the new object. 120 262 inline SharedPtr& operator=(const SharedPtr& other) 121 263 { … … 124 266 } 125 267 268 /// Assigns a new object with another template argument, decrements the counter of the old object, increments the counter of the new object. 126 269 template <class O> 127 270 inline SharedPtr& operator=(const SharedPtr<O>& other) … … 131 274 } 132 275 276 /// Casts the pointer to another type 133 277 template <class O> 134 278 inline SharedPtr<O> cast() const … … 138 282 } 139 283 284 /// Overloaded -> operator, returns the pointer to the managed object. 140 285 inline T* operator->() const 141 286 { … … 144 289 } 145 290 291 /// Overloaded * operator, returns a reference ot the managed object. 146 292 inline T& operator*() const 147 293 { … … 150 296 } 151 297 298 /// Returns the pointer to the managed object. 152 299 inline T* get() const 153 300 { … … 155 302 } 156 303 304 /// Returns true if the pointer is not NULL. 157 305 inline operator bool() const 158 306 { … … 160 308 } 161 309 310 /// Swaps the pointer and the counter of two instances of SharedPtr with the same template argument. 162 311 inline void swap(SharedPtr& other) 163 312 { … … 167 316 168 317 private: 169 inline SharedPtr(T* pointer, SharedCounter* counter) : pointer_(pointer), counter_(counter) 318 /// Private constructor, used by the cast() function. 319 inline SharedPtr(T* pointer, detail::SharedCounter* counter) : pointer_(pointer), counter_(counter) 170 320 { 171 321 if (this->pointer_) … … 173 323 } 174 324 175 T* pointer_; 176 SharedCounter* counter_;325 T* pointer_; ///< A pointer to the managed object of type @a T 326 detail::SharedCounter* counter_; ///< A pointer to the shared reference counter 177 327 }; 178 328 329 /** 330 @brief A child class of SharedPtr, used to reflect the hierarchy of the underlying class @a T. 331 @param T The type of the managed object 332 @param Parent The type of the SharedPtr that manages the parent class of @a T 333 334 This class is used to reflect the hierarchy of the underlying class @a T. 335 For example the @c Functor classes: While a @c Functor* pointer would be managed by 336 @c SharedPtr<Functor>, the child class @c FunctorStatic is managed by the class 337 <tt>SharedChildPtr<FunctorStatic, SharedPtr<Functor> ></tt>. 338 339 The second template argument @a Parent is used as the parent class of 340 SharedChildPtr. This means that each instance of <tt>SharedChildPtr<T, Parent></tt> 341 can be upcasted to @c Parent. 342 343 So for example this works: 344 @code 345 SharedChildPtr<FunctorStatic, SharedPtr<Functor> > functorStatic = createFunctor(&MyClass::myStaticFunction); 346 SharedPtr<Functor> functor = functorStatic; 347 @endcode 348 349 @note There are some typedefs and more to make the usage of SharedChildPtr easier 350 for the classes Functor and Executor. See FunctorPtr.h and ExecutorPtr.h. The above 351 example could thus be simplified the following way: 352 @code 353 FunctorStaticPtr functorStatic = createFunctor(&MyClass::myStaticFunction); 354 FunctorPtr functor = functorStatic; 355 @endcode 356 357 @see See SharedPtr for more information about the base class SharedPtr. 358 @see See @ref SharedPtrExample "this description" for some examples about how to use SharedPtr. 359 */ 179 360 template <class T, class Parent> 180 361 class SharedChildPtr : public Parent -
code/branches/doc/src/libraries/util/SignalHandler.h
r5738 r7327 29 29 /** 30 30 @file 31 @ingroup Util 31 32 @brief Declaration of the SignalHandler class. 32 33 */ … … 68 69 typedef std::list<SignalCallbackRec> SignalCallbackList; 69 70 71 /// The SignalHandler is used to catch signals like SIGSEGV and write a backtrace to the logfile. 70 72 class SignalHandler : public Singleton<SignalHandler> 71 73 { … … 99 101 namespace orxonox 100 102 { 103 /// The SignalHandler is used to catch signals like SIGSEGV and write a backtrace to the logfile. Not implemented on Windows. 101 104 class _UtilExport SignalHandler : public Singleton<SignalHandler> 102 105 { -
code/branches/doc/src/libraries/util/SmallObjectAllocator.cc
r7284 r7327 27 27 */ 28 28 29 /** 30 @file 31 @brief Implementation of SmallObjectAllocator 32 */ 33 29 34 #include "SmallObjectAllocator.h" 30 35 31 36 namespace orxonox 32 37 { 38 /** 39 @brief Constructor: initializes the allocator and its values. 40 @param objectSize The size in bytes (returned by sizeof()) of the allocated objects 41 @param numObjects The number of objects that are allocated in one block of memory 42 */ 33 43 SmallObjectAllocator::SmallObjectAllocator(size_t objectSize, size_t numObjects) 34 44 { 35 this-> objectSize_ = std::max(objectSize, sizeof(Chunk));36 this->num Objects_ = numObjects;45 this->chunkSize_ = std::max(objectSize, sizeof(Chunk)); // the chunk's size will be the maximum of the object's size and the size of a Chunk object itself 46 this->numChunksPerBlock_ = numObjects; 37 47 this->first_ = 0; 38 48 } 39 49 50 /** 51 @brief Destructor: deletes the allocated memory blocks. 52 */ 40 53 SmallObjectAllocator::~SmallObjectAllocator() 41 54 { … … 44 57 } 45 58 59 /** 60 @brief Helper function, used to set the next_ pointer of a Chunk. 61 */ 46 62 /* static */ void SmallObjectAllocator::setNext(void* chunk, void* next) 47 63 { … … 49 65 } 50 66 67 /** 68 @brief Helper function, returns the next_ pointer of a Chunk 69 */ 51 70 /* static */ void* SmallObjectAllocator::getNext(void* chunk) 52 71 { … … 54 73 } 55 74 75 /** 76 @brief Returns the first free memory chunk or allocates a new block of memory. 77 */ 56 78 void* SmallObjectAllocator::alloc() 57 79 { 80 // get the first free chunk 58 81 void* chunk = this->first_; 59 82 83 // check if the chunk exists 60 84 if (chunk) 61 85 { 86 // yes it does - the first_ pointer now points to the second element in the list 62 87 this->first_ = getNext(chunk); 63 88 } 64 89 else 65 90 { 66 char* block = new char[this->objectSize_ * this->numObjects_]; 91 // no it doesnt - allocate a new block of memory 92 char* block = new char[this->chunkSize_ * this->numChunksPerBlock_]; 67 93 this->blocks_.push_back(block); 68 94 69 for (size_t i = 1; i < this->numObjects_ - 1; ++i) 70 setNext(block + i * this->objectSize_, block + (i + 1) * this->objectSize_); 95 // iterate through the chunks in the new memory block and link them together to a single linked list 96 for (size_t i = 1; i < this->numChunksPerBlock_ - 1; ++i) 97 setNext(block + i * this->chunkSize_, block + (i + 1) * this->chunkSize_); 71 98 72 setNext(block + (this->numObjects_ - 1) * this->objectSize_, 0); 99 // the next_ pointer of the last chunk must point to NULL 100 setNext(block + (this->numChunksPerBlock_ - 1) * this->chunkSize_, 0); 73 101 74 this->first_ = block + this->objectSize_; 102 // The second chunk in the block is assigned to the first_ pointer 103 this->first_ = block + this->chunkSize_; 75 104 105 // The first chunk in the block is returned 76 106 chunk = block; 77 107 } 78 108 109 // return the pointer to the chunk 79 110 return chunk; 80 111 } 81 112 113 /** 114 @brief Puts the memory chunk back on the list of free memory. 115 */ 82 116 void SmallObjectAllocator::free(void* chunk) 83 117 { 118 // The first_ pointer points to the freed chunk, its next_ pointer points to the rest of the list 84 119 setNext(chunk, this->first_); 85 120 this->first_ = chunk; -
code/branches/doc/src/libraries/util/SmallObjectAllocator.h
r7284 r7327 27 27 */ 28 28 29 /** 30 @defgroup SmallObjectAllocator SmallObjectAllocator 31 @ingroup Util Object 32 */ 33 34 /** 35 @file 36 @ingroup Util SmallObjectAllocator 37 @brief Declaration of SmallObjectAllocator 38 39 @anchor SmallObjectAllocatorExample 40 41 The default implementations of new and delete are designed to work with objects of 42 arbitrary size. They are thus not optimal for small objects. 43 @ref orxonox::SmallObjectAllocator "SmallObjectAllocator" allocates a large memory 44 block and divides it into small chunks. These chunks are returned by the function 45 @ref orxonox::SmallObjectAllocator::alloc() "alloc()" and can be used to create a 46 new object using the placement new operator. Instead of delete, the function 47 @ref orxonox::SmallObjectAllocator::free() "free()" is used to give the memory 48 back to SmallObjectAllocator. 49 50 Example: 51 @code 52 SmallObjectAllocator allocator(sizeof(MySmallObject)); // Create an allocator. The size of the memory chunks must equal the size of the desired class 53 54 void* chunk = allocator.alloc(); // Allocate a memory chunk 55 MySmallObject* object = new (chunk) MySmallObject(); // Call the placement new operator 56 57 object->someFunction(); // Do something with the object 58 59 object->~MySmallObject(); // Call the destructor 60 allocator.free(object); // Free the allocated memory 61 @endcode 62 63 @b Important: You have to call the destructor of the object manually, because this 64 is not automatically done by the allocator nor free(). 65 66 @note The destructor can be ignored if it is empty or not implemented. This saves 67 another amount of time. 68 69 @remarks For a distributed usage of SmallObjectAllocator it may be a good idea to 70 create a static function that returns an instance to it. The allocator then works 71 like a singleton and can be accesses from everywhere. 72 */ 73 29 74 #ifndef _SmallObjectAllocator_H__ 30 75 #define _SmallObjectAllocator_H__ … … 35 80 namespace orxonox 36 81 { 82 /** 83 @brief This class is used to allocate and free small objects (usually not polymorphic). 84 85 SmallObjectAllocator provides a fast alternative to new and delete for small objects. 86 87 @see See @ref SmallObjectAllocatorExample "this description" for more information and an example. 88 */ 37 89 class _UtilExport SmallObjectAllocator 38 90 { 91 /// The memory chunk is at the same time an element of a single linked list. 39 92 struct Chunk 40 93 { 41 Chunk* next_; 94 Chunk* next_; ///< A pointer to the next chunk in the list 42 95 }; 43 96 … … 53 106 static void* getNext(void* chunk); 54 107 55 void* first_; 56 size_t objectSize_;57 size_t num Objects_;108 void* first_; ///< A pointer to the first free memory chunk 109 size_t chunkSize_; ///< The size of each chunk (and usually also the size of the created objects) 110 size_t numChunksPerBlock_; ///< The number of chunks per memory block 58 111 59 std::vector<char*> blocks_; 112 std::vector<char*> blocks_; ///< A list of all allocated memory blocks (used to destroy them again) 60 113 }; 61 114 } -
code/branches/doc/src/libraries/util/StringUtils.cc
r7297 r7327 41 41 namespace orxonox 42 42 { 43 /// A blank string (""). Used to return a blank string by reference. 43 44 std::string BLANKSTRING; 44 45 46 /// Returns a string of a unique number. This function is guaranteed to never return the same string twice. 45 47 std::string getUniqueNumberString() 46 48 { … … 48 50 } 49 51 50 /** 51 @brief Removes all whitespaces from a string. 52 @param str The string to strip 53 */ 52 /// Removes all whitespaces from a string. 54 53 void strip(std::string* str) 55 54 { … … 63 62 } 64 63 65 /** 66 @brief Returns a copy of a string without whitespaces. 67 @param str The string to strip 68 @return The stripped line 69 */ 64 /// Returns a copy of a string without whitespaces. 70 65 std::string getStripped(const std::string& str) 71 66 { … … 75 70 } 76 71 77 /** 78 @brief Returns a copy of a string without trailing whitespaces. 79 @param str The string 80 @return The modified copy 81 */ 72 /// Returns a copy of a string without trailing whitespaces. 82 73 std::string removeTrailingWhitespaces(const std::string& str) 83 74 { … … 90 81 91 82 /** 92 @brief Returns the position of the next quot ein the string, starting with start.83 @brief Returns the position of the next quotation mark in the string, starting with start. 93 84 @param str The string 94 @param start The startposition95 @return The position of the next quot e (std::string::npos if there is no next quote)85 @param start The first position to look at 86 @return The position of the next quotation mark (@c std::string::npos if there is none) 96 87 */ 97 88 size_t getNextQuote(const std::string& str, size_t start) … … 115 106 116 107 /** 117 @brief Returns true if pos is between two quot es.108 @brief Returns true if pos is between two quotation marks. 118 109 @param str The string 119 110 @param pos The position to check 120 @return True if pos is between two quot es111 @return True if pos is between two quotation marks 121 112 */ 122 113 bool isBetweenQuotes(const std::string& str, size_t pos) … … 140 131 } 141 132 142 /** 143 @brief Returns true if the string contains something like '..."between quotes"...'. 144 @param str The string 145 @return True if there is something between quotes 146 */ 133 /// Returns true if the string contains something like '..."between quotaton marks"...'. 147 134 bool hasStringBetweenQuotes(const std::string& str) 148 135 { … … 152 139 } 153 140 154 /** 155 @brief If the string contains something like '..."between quotes"...' then 'between quotes' gets returned (without quotes). 156 @param str The string between the quotes 157 */ 141 /// If the string contains something like '..."between quotaton marks"...' then 'between quotaton marks' gets returned, otherwise "". 158 142 std::string getStringBetweenQuotes(const std::string& str) 159 143 { … … 167 151 168 152 /** 169 @brief Removes enclosing quotes if available (including whitespaces at the outside of the quotes). 170 @param str The string to strip 171 @return The string with removed quotes 153 @brief Removes enclosing quotation marks if available (including whitespaces at the outside of the quotation marks). 154 @return The striped string without quotation marks 172 155 */ 173 156 std::string stripEnclosingQuotes(const std::string& str) … … 207 190 208 191 /** 209 @brief Removes enclosing {braces} (braces must be exactly on the beginning and the end of the string). 210 @param str The string to strip 211 @return The striped string 192 @brief Removes enclosing braces '{' and '}' (the braces must be exactly on the beginning and the end of the string). 193 @return The striped string without braces 212 194 */ 213 195 std::string stripEnclosingBraces(const std::string& str) … … 223 205 /** 224 206 @brief Determines if a string is a comment (starts with a comment-symbol). 225 @param str The string to check226 @return True = it's a comment227 207 228 208 A comment is defined by a leading '#', '%', ';' or '//'. … … 252 232 } 253 233 254 /** 255 @brief Determines if a string is empty (contains only whitespaces). 256 @param str The string to check 257 @return True = it's empty 258 */ 234 /// Determines if a string is empty (contains only whitespaces). 259 235 bool isEmpty(const std::string& str) 260 236 { … … 262 238 } 263 239 264 /** 265 @brief Determines if a string contains only numbers and maximal one '.'. 266 @param str The string to check 267 @return True = it's a number 268 */ 240 /// Determines if a string contains only numbers and maximal one '.'. 269 241 bool isNumeric(const std::string& str) 270 242 { … … 287 259 /** 288 260 @brief Adds backslashes to the given string which makes special chars visible. Existing slashes will be doubled. 289 @param str The string to manipulate 290 @return The string with added slashes 261 262 This function converts all special chars like line breaks, tabs, quotation marks etc. into 263 a human readable format by adding a backslash. So for example "\n" will be converted to 264 "\\" + "n". 265 266 This is usually used when a string is written to a file. 267 268 @see removeSlashes 291 269 */ 292 270 std::string addSlashes(const std::string& str) … … 319 297 /** 320 298 @brief Removes backslashes from the given string. Double backslashes are interpreted as one backslash. 321 @param str The string to manipulate 322 @return The string with removed slashes 299 300 This function removes all backslashes and converts the human readable equivalents of 301 special chars like "\\" + "n" into their real meaning (in this case a line break or "\n"). 302 303 This is usually used when reading a string from a file. 304 305 @see addSlashes 323 306 */ 324 307 std::string removeSlashes(const std::string& str) … … 360 343 } 361 344 362 /** 363 @brief Replaces each char between A and Z with its lowercase equivalent. 364 @param str The string to convert 365 */ 345 /// Replaces each char between A and Z with its lowercase equivalent. 366 346 void lowercase(std::string* str) 367 347 { … … 372 352 } 373 353 374 /** 375 @brief Returns a copy of the given string without uppercase chars. 376 @param str The string 377 @return The copy 378 */ 354 /// Returns a copy of the given string where all chars are converted to lowercase. 379 355 std::string getLowercase(const std::string& str) 380 356 { … … 384 360 } 385 361 386 /** 387 @brief Replaces each char between a and z with its uppercase equivalent. 388 @param str The string to convert 389 */ 362 /// Replaces each char between a and z with its uppercase equivalent. 390 363 void uppercase(std::string* str) 391 364 { … … 396 369 } 397 370 398 /** 399 @brief Returns a copy of the given string without lowercase chars. 400 @param str The string 401 @return The copy 402 */ 371 /// Returns a copy of the given string where all chars are converted to uppercase. 403 372 std::string getUppercase(const std::string& str) 404 373 { … … 410 379 /** 411 380 @brief Compares two strings ignoring different casing. 412 @param s1 First string 413 @param s2 Second string 381 @return s1 == s1 -> returns 0 / s1 < s2 -> returns -1 / s1 >= s2 -> returns 1 414 382 */ 415 383 int nocaseCmp(const std::string& s1, const std::string& s2) … … 437 405 438 406 /** 439 @brief Compares the first 'len'chars of two strings ignoring different casing.407 @brief Compares the first @a len chars of two strings ignoring different casing. 440 408 @param s1 First string 441 409 @param s2 Second string … … 462 430 } 463 431 464 /** 465 @brief Returns true if the string contains a comment, introduced by #, %, ; or //. 432 /// Returns true if the string contains a comment, introduced by #, %, ; or //. 433 bool hasComment(const std::string& str) 434 { 435 return (getCommentPosition(str) != std::string::npos); 436 } 437 438 /// If the string contains a comment, the comment gets returned (including the comment symbol), an empty string otherwise. 439 std::string getComment(const std::string& str) 440 { 441 return str.substr(getCommentPosition(str)); 442 } 443 444 /// If the string contains a comment, the position of the comment-symbol gets returned, @c std::string::npos otherwise. 445 size_t getCommentPosition(const std::string& str) 446 { 447 return getNextCommentPosition(str, 0); 448 } 449 450 /** 451 @brief Returns the position of the next comment-symbol, starting with @a start. 466 452 @param str The string 467 @return True if the string contains a comment 468 */ 469 bool hasComment(const std::string& str) 470 { 471 return (getCommentPosition(str) != std::string::npos); 472 } 473 474 /** 475 @brief If the string contains a comment, the comment gets returned (including the comment symbol), an empty string otherwise. 476 @param str The string 477 @return The comment 478 */ 479 std::string getComment(const std::string& str) 480 { 481 return str.substr(getCommentPosition(str)); 482 } 483 484 /** 485 @brief If the string contains a comment, the position of the comment-symbol gets returned, std::string::npos otherwise. 486 @param str The string 487 @return The position 488 */ 489 size_t getCommentPosition(const std::string& str) 490 { 491 return getNextCommentPosition(str, 0); 492 } 493 494 /** 495 @brief Returns the position of the next comment-symbol, starting with start. 496 @param str The string 497 @param start The startposition 498 @return The position 453 @param start The first position to look at 499 454 */ 500 455 size_t getNextCommentPosition(const std::string& str, size_t start) -
code/branches/doc/src/libraries/util/StringUtils.h
r7284 r7327 28 28 29 29 /** 30 @defgroup String String functions 31 @ingroup Util 32 */ 33 34 /** 30 35 @file 36 @ingroup Util String 31 37 @brief Declaration of several string manipulation functions, used in many parts of the game. 32 38 */ -
code/branches/doc/src/libraries/util/SubString.cc
r7297 r7327 40 40 #include "SubString.h" 41 41 #include <cstdio> 42 #include "Debug.h" 42 43 43 44 namespace orxonox 44 45 { 45 /** 46 * @brief default constructor 47 */ 46 const std::string SubString::WhiteSpaces = " \n\t"; 47 const std::string SubString::WhiteSpacesWithComma = " \n\t,"; 48 const SubString SubString::NullSubString = SubString(); 49 50 /** 51 @brief Default constructor. 52 */ 48 53 SubString::SubString() 49 {} 50 51 52 /** 53 * @brief create a SubString from 54 * @param string the String to Split 55 * @param delimiter the Character at which to split string (delimiter) 56 */ 57 SubString::SubString(const std::string& string, char delimiter) 58 { 59 this->split(string, delimiter); 60 } 61 62 63 /** 64 * @brief Splits a string into multiple tokens. 65 * @param string The string to split 66 * @param delimiters Multiple set of characters at what to split. (delimiters) 67 * @param delimiterNeighbours Neighbours of the delimiters that will be erased as well. 68 * @param emptyEntries If empty entries are added to the list of SubStrings 69 * @param escapeChar The escape character that overrides splitters commends and so on... 70 * @param removeEscapeChar If true, the escape char is removed from the tokens 71 * @param safemode_char Within these characters splitting won't happen 72 * @param removeSafemodeChar Removes the safemode_char from the beginning and the ending of a token 73 * @param openparenthesis_char The beginning of a safemode is marked with this 74 * @param closeparenthesis_char The ending of a safemode is marked with this 75 * @param removeParenthesisChars Removes the parenthesis from the beginning and the ending of a token 76 * @param comment_char The comment character. 77 */ 78 SubString::SubString(const std::string& string, 79 const std::string& delimiters, const std::string& delimiterNeighbours, bool emptyEntries, 80 char escapeChar, bool removeEscapeChar, char safemode_char, bool removeSafemodeChar, 81 char openparenthesis_char, char closeparenthesis_char, bool removeParenthesisChars, char comment_char) 82 { 83 SubString::splitLine(this->strings, this->bInSafemode, string, delimiters, delimiterNeighbours, emptyEntries, escapeChar, removeEscapeChar, safemode_char, removeSafemodeChar, openparenthesis_char, closeparenthesis_char, removeParenthesisChars, comment_char); 84 } 85 86 /** 87 * @brief creates a SubSet of a SubString. 88 * @param subString the SubString to take a set from. 89 * @param subSetBegin the beginning to the end 90 */ 91 SubString::SubString(const SubString& subString, unsigned int subSetBegin) 92 { 93 for (unsigned int i = subSetBegin; i < subString.size(); i++) 94 { 95 this->strings.push_back(subString[i]); 96 this->bInSafemode.push_back(subString.isInSafemode(i)); 97 } 98 } 99 100 101 /** 102 * @brief creates a SubSet of a SubString. 103 * @param subString the SubString to take a Set from 104 * @param subSetBegin the beginning to the end 105 * @param subSetEnd the end of the SubSet (max subString.size() will be checked internaly) 106 */ 107 SubString::SubString(const SubString& subString, unsigned int subSetBegin, unsigned int subSetEnd) 108 { 109 for (unsigned int i = subSetBegin; i < subString.size() && i < subSetEnd; i++) 110 { 111 this->strings.push_back(subString[i]); 112 this->bInSafemode.push_back(subString.isInSafemode(i)); 113 } 114 } 115 116 /** 117 * @brief creates a Substring from a count and values set. 118 * @param argc: the Arguments Count. 119 * @param argv: Argument Values. 120 */ 54 { 55 } 56 57 /** 58 @brief Splits a string into multiple tokens. 59 @param line The line to split 60 @param delimiters Multiple characters at which to split the line 61 @param delimiterNeighbours Neighbours of the delimiters that will be erased as well (for example white-spaces) 62 @param bAllowEmptyEntries If true, empty tokens are also added to the SubString (if there are two delimiters without a char in between) 63 @param escapeChar The escape character that is used to escape safemode chars (for example if you want to use a quotation mark between two other quotation marks). 64 @param bRemoveEscapeChar If true, the escape char is removed from the tokens 65 @param safemodeChar Within these characters splitting won't happen (usually the quotation marks) 66 @param bRemoveSafemodeChar Removes the safemodeChar from the beginning and the ending of a token 67 @param openparenthesisChar The beginning of a safemode is marked with this (usually an opening brace) 68 @param closeparenthesisChar The ending of a safemode is marked with this (usually a closing brace) 69 @param bRemoveParenthesisChars Removes the parenthesis chars from the beginning and the ending of a token 70 @param commentChar The comment character (used to ignore the part of the line after the comment char). 71 */ 72 SubString::SubString(const std::string& line, 73 const std::string& delimiters, const std::string& delimiterNeighbours, bool bAllowEmptyEntries, 74 char escapeChar, bool bRemoveEscapeChar, char safemodeChar, bool bRemoveSafemodeChar, 75 char openparenthesisChar, char closeparenthesisChar, bool bRemoveParenthesisChars, char commentChar) 76 { 77 SubString::splitLine(this->tokens_, this->bTokenInSafemode_, line, delimiters, delimiterNeighbours, bAllowEmptyEntries, escapeChar, bRemoveEscapeChar, safemodeChar, bRemoveSafemodeChar, openparenthesisChar, closeparenthesisChar, bRemoveParenthesisChars, commentChar); 78 } 79 80 /** 81 @brief creates a new SubString based on a subset of an other SubString. 82 @param other The other SubString 83 @param begin The beginning of the subset 84 85 The subset ranges from the token with index @a begin to the end of the tokens. 86 If @a begin is greater than the greatest index, the new SubString will be empty. 87 */ 88 SubString::SubString(const SubString& other, unsigned int begin) 89 { 90 for (unsigned int i = begin; i < other.size(); ++i) 91 { 92 this->tokens_.push_back(other[i]); 93 this->bTokenInSafemode_.push_back(other.isInSafemode(i)); 94 } 95 } 96 97 /** 98 @brief creates a new SubString based on a subset of an other SubString. 99 @param other The other SubString 100 @param begin The beginning of the subset 101 @param end The end of the subset 102 103 The subset ranges from the token with index @a begin until (but not including) the token with index @a end. 104 If @a begin or @a end are beyond the allowed index, the resulting SubString will be empty. 105 */ 106 SubString::SubString(const SubString& other, unsigned int begin, unsigned int end) 107 { 108 for (unsigned int i = begin; i < std::min(other.size(), end); ++i) 109 { 110 this->tokens_.push_back(other[i]); 111 this->bTokenInSafemode_.push_back(other.isInSafemode(i)); 112 } 113 } 114 115 /** 116 @brief Creates a SubString from a count and values set. 117 @param argc The number of arguments 118 @param argv An array of pointers to the arguments 119 */ 121 120 SubString::SubString(unsigned int argc, const char** argv) 122 121 { 123 122 for(unsigned int i = 0; i < argc; ++i) 124 123 { 125 this-> strings.push_back(std::string(argv[i]));126 this->b InSafemode.push_back(false);127 } 128 } 129 130 /** 131 * @brief removes the object from memory132 124 this->tokens_.push_back(std::string(argv[i])); 125 this->bTokenInSafemode_.push_back(false); 126 } 127 } 128 129 /** 130 @brief Destructor 131 */ 133 132 SubString::~SubString() 134 133 { } 135 134 136 /** @brief An empty String */ 137 // const std::string SubString::emptyString = ""; 138 /** @brief Helper that gets you a String consisting of all White Spaces */ 139 const std::string SubString::WhiteSpaces = " \n\t"; 140 /** @brief Helper that gets you a String consisting of all WhiteSpaces and the Comma */ 141 const std::string SubString::WhiteSpacesWithComma = " \n\t,"; 142 /** An Empty SubString */ 143 const SubString SubString::NullSubString = SubString(); 144 145 /** 146 * @brief stores the Value of subString in this SubString 147 * @param subString will be copied into this String. 148 * @returns this SubString. 149 */ 150 SubString& SubString::operator=(const SubString& subString) 151 { 152 this->strings = subString.strings; 153 this->bInSafemode = subString.bInSafemode; 135 /** 136 @brief Stores the tokens of @a other in this SubString 137 @return This SubString. 138 */ 139 SubString& SubString::operator=(const SubString& other) 140 { 141 this->tokens_ = other.tokens_; 142 this->bTokenInSafemode_ = other.bTokenInSafemode_; 154 143 return *this; 155 144 } 156 145 157 158 /** 159 * @brief comparator. 160 * @param subString the SubString to compare against this one. 161 * @returns true if the Stored Strings match 162 */ 163 bool SubString::operator==(const SubString& subString) const 164 { 165 return ((this->strings == subString.strings) && (this->bInSafemode == subString.bInSafemode)); 166 } 167 168 /** 169 * @brief comparator. 170 * @param subString the SubString to compare against this one. 171 * @returns true if the Stored Strings match 172 */ 173 bool SubString::compare(const SubString& subString) const 174 { 175 return (*this == subString); 176 } 177 178 /** 179 * @brief comparator. 180 * @param subString the SubString to compare against this one. 181 * @param length how many entries to compare. (from 0 to length) 182 * @returns true if the Stored Strings match 183 */ 184 bool SubString::compare(const SubString& subString, unsigned int length) const 185 { 186 if (length > this->size() || length > subString.size()) 146 /** 147 @brief Compares this SubString to another SubString and returns true if they contain the same values. 148 */ 149 bool SubString::operator==(const SubString& other) const 150 { 151 return ((this->tokens_ == other.tokens_) && (this->bTokenInSafemode_ == other.bTokenInSafemode_)); 152 } 153 154 /** 155 @copydoc operator== 156 */ 157 bool SubString::compare(const SubString& other) const 158 { 159 return (*this == other); 160 } 161 162 /** 163 @brief Compares this SubString to another SubString and returns true if the first @a length values match. 164 @param other The other SubString 165 @param length How many tokens to compare 166 */ 167 bool SubString::compare(const SubString& other, unsigned int length) const 168 { 169 if (length > this->size() || length > other.size()) 187 170 return false; 188 171 189 for (unsigned int i = 0; i < length; i++)190 if ((this-> strings[i] != subString.strings[i]) || (this->bInSafemode[i] != subString.bInSafemode[i]))172 for (unsigned int i = 0; i < length; ++i) 173 if ((this->tokens_[i] != other.tokens_[i]) || (this->bTokenInSafemode_[i] != other.bTokenInSafemode_[i])) 191 174 return false; 192 175 return true; 193 176 } 194 177 195 196 /** 197 * @brief append operator 198 * @param subString the String to append. 199 * @returns a SubString where this and subString are appended. 200 */ 201 SubString SubString::operator+(const SubString& subString) const 202 { 203 return SubString(*this) += subString; 204 } 205 206 207 /** 208 * @brief append operator. 209 * @param subString append subString to this SubString. 210 * @returns this substring appended with subString 211 */ 212 SubString& SubString::operator+=(const SubString& subString) 213 { 214 for (unsigned int i = 0; i < subString.size(); i++) 215 { 216 this->strings.push_back(subString[i]); 217 this->bInSafemode.push_back(subString.isInSafemode(i)); 178 /** 179 @brief Concatenates the tokens of two SubStrings and returns the resulting new SubString 180 @return A new SubString that contains the tokens of this and the other SubString 181 */ 182 SubString SubString::operator+(const SubString& other) const 183 { 184 return SubString(*this) += other; 185 } 186 187 /** 188 @brief Appends the tokens of @a other to this SubString 189 @return This SubString 190 */ 191 SubString& SubString::operator+=(const SubString& other) 192 { 193 for (unsigned int i = 0; i < other.size(); ++i) 194 { 195 this->tokens_.push_back(other[i]); 196 this->bTokenInSafemode_.push_back(other.isInSafemode(i)); 218 197 } 219 198 return *this; 220 199 } 221 200 222 223 /** 224 * @brief Split the String at 225 * @param string where to split 226 * @param splitter delimiter. 227 */ 228 unsigned int SubString::split(const std::string& string, char splitter) 229 { 230 this->strings.clear(); 231 this->bInSafemode.clear(); 232 char split[2]; 233 split[0] = splitter; 234 split[1] = '\0'; 235 SubString::splitLine(this->strings, this->bInSafemode, string, split); 236 return strings.size(); 237 } 238 239 240 /** 241 * @brief Splits a string into multiple tokens. 242 * @param string The string to split 243 * @param delimiters Multiple set of characters at what to split. (delimiters) 244 * @param delimiterNeighbours: Neighbours of the delimiters that will be erased too. 245 * @param emptyEntries: If empty entries are added to the list of SubStrings 246 * @param escapeChar The escape character that overrides splitters commends and so on... 247 * @param removeEscapeChar If true, the escape char is removed from the tokens 248 * @param safemode_char Within these characters splitting won't happen 249 * @param removeSafemodeChar Removes the safemode_char from the beginning and the ending of a token 250 * @param openparenthesis_char The beginning of a safemode is marked with this 251 * @param closeparenthesis_char The ending of a safemode is marked with this 252 * @param removeParenthesisChars Removes the parenthesis from the beginning and the ending of a token 253 * @param comment_char The comment character. 254 */ 255 unsigned int SubString::split(const std::string& string, 256 const std::string& delimiters, const std::string& delimiterNeighbours, bool emptyEntries, 257 char escapeChar, bool removeEscapeChar, char safemode_char, bool removeSafemodeChar, 258 char openparenthesis_char, char closeparenthesis_char, bool removeParenthesisChars, char comment_char) 259 { 260 this->strings.clear(); 261 this->bInSafemode.clear(); 262 SubString::splitLine(this->strings, this->bInSafemode, string, delimiters, delimiterNeighbours, emptyEntries, escapeChar, removeEscapeChar, safemode_char, removeSafemodeChar, openparenthesis_char, closeparenthesis_char, removeParenthesisChars, comment_char); 263 return this->strings.size(); 264 } 265 266 267 /** 268 * @brief joins together all Strings of this Substring. 269 * @param delimiter the String between the subStrings. 270 * @returns the joined String. 271 */ 201 /** 202 @copydoc SubString(const std::string&,const std::string&,const std::string&,bool,char,bool,char,bool,char,char,bool,char) 203 */ 204 unsigned int SubString::split(const std::string& line, 205 const std::string& delimiters, const std::string& delimiterNeighbours, bool bAllowEmptyEntries, 206 char escapeChar, bool bRemoveEscapeChar, char safemodeChar, bool bRemoveSafemodeChar, 207 char openparenthesisChar, char closeparenthesisChar, bool bRemoveParenthesisChars, char commentChar) 208 { 209 this->tokens_.clear(); 210 this->bTokenInSafemode_.clear(); 211 SubString::splitLine(this->tokens_, this->bTokenInSafemode_, line, delimiters, delimiterNeighbours, bAllowEmptyEntries, escapeChar, bRemoveEscapeChar, safemodeChar, bRemoveSafemodeChar, openparenthesisChar, closeparenthesisChar, bRemoveParenthesisChars, commentChar); 212 return this->tokens_.size(); 213 } 214 215 /** 216 @brief Joins the tokens of this SubString using the given delimiter and returns a string. 217 @param delimiter This delimiter will be placed between each two tokens 218 @return The joined string. 219 */ 272 220 std::string SubString::join(const std::string& delimiter) const 273 221 { 274 if (!this-> strings.empty())275 { 276 std::string retVal = this-> strings[0];277 for (unsigned int i = 1; i < this-> strings.size(); i++)278 retVal += delimiter + this-> strings[i];222 if (!this->tokens_.empty()) 223 { 224 std::string retVal = this->tokens_[0]; 225 for (unsigned int i = 1; i < this->tokens_.size(); ++i) 226 retVal += delimiter + this->tokens_[i]; 279 227 return retVal; 280 228 } … … 283 231 } 284 232 285 286 /** 287 * @brief creates a SubSet of a SubString. 288 * @param subSetBegin the beginning to the end 289 * @returns the SubSet 290 * 291 * This function is added for your convenience, and does the same as 292 * SubString::SubString(const SubString& subString, unsigned int subSetBegin) 293 */ 294 SubString SubString::subSet(unsigned int subSetBegin) const 295 { 296 return SubString(*this, subSetBegin); 297 } 298 299 300 /** 301 * @brief creates a SubSet of a SubString. 302 * @param subSetBegin the beginning to 303 * @param subSetEnd the end of the SubSet to select (if bigger than subString.size() it will be downset.) 304 * @returns the SubSet 305 * 306 * This function is added for your convenience, and does the same as 307 * SubString::SubString(const SubString& subString, unsigned int subSetBegin) 308 */ 309 SubString SubString::subSet(unsigned int subSetBegin, unsigned int subSetEnd) const 310 { 311 return SubString(*this, subSetBegin, subSetEnd); 312 } 313 314 315 /** 316 * @brief Splits a line into tokens and stores them in ret. 317 * @param ret The array, where the splitted strings will be stored in 318 * @param bInSafemode A vector wich stores for each character of the string if it is in safemode or not 319 * @param line The inputLine to split 320 * @param delimiters A string of delimiters (here the input will be splitted) 321 * @param delimiterNeighbours Neighbours of the delimiter, that will be removed if they are to the left or the right of a delimiter. 322 * @param emptyEntries If empty strings are added to the list of strings. 323 * @param escape_char Escape carater (escapes splitters) 324 * @param removeEscapeChar If true, the escape char is removed from the tokens 325 * @param safemode_char The beginning of the safemode is marked with this 326 * @param removeSafemodeChar Removes the safemode_char from the beginning and the ending of a token 327 * @param openparenthesis_char The beginning of a safemode is marked with this 328 * @param closeparenthesis_char The ending of a safemode is marked with this 329 * @param removeParenthesisChars Removes the parenthesis from the beginning and the ending of a token 330 * @param comment_char The beginning of a comment is marked with this: (until the end of a line) 331 * @param start_state The initial state on how to parse the string. 332 * @return SPLIT_LINE_STATE the parser was in when returning 333 * 334 * This is the Actual Splitting Algorithm from Clemens Wacha 335 * Supports delimiters, escape characters, 336 * ignores special characters between safemode_char and between comment_char and linend '\n'. 337 */ 233 /** 234 @brief Creates a subset of this SubString. 235 @param begin The beginning of the subset 236 @return A new SubString containing the defined subset. 237 238 The subset ranges from the token with index @a begin to the end of the tokens. 239 If @a begin is greater than the greatest index, the new SubString will be empty. 240 241 This function is added for your convenience, and does the same as 242 SubString::SubString(const SubString& other, unsigned int begin) 243 */ 244 SubString SubString::subSet(unsigned int begin) const 245 { 246 return SubString(*this, begin); 247 } 248 249 /** 250 @brief Creates a subset of this SubString. 251 @param begin The beginning of the subset 252 @param end The ending of the subset 253 @return A new SubString containing the defined subset. 254 255 The subset ranges from the token with index @a begin until (but not including) the token with index @a end. 256 If @a begin or @a end are beyond the allowed index, the resulting SubString will be empty. 257 258 This function is added for your convenience, and does the same as 259 SubString::SubString(const SubString& other, unsigned int begin, unsigned int end) 260 */ 261 SubString SubString::subSet(unsigned int begin, unsigned int end) const 262 { 263 return SubString(*this, begin, end); 264 } 265 266 /** 267 @copydoc SubString(const std::string&,const std::string&,const std::string&,bool,char,bool,char,bool,char,char,bool,char) 268 @param tokens The array, where the splitted strings will be stored in 269 @param bTokenInSafemode A vector wich stores for each character of the string if it is in safemode or not 270 @param start_state The internal state of the parser 271 272 This is the actual splitting algorithm from Clemens Wacha. 273 Supports delimiters, escape characters, ignores special characters between safemodeChar and between commentChar and line end "\n". 274 275 Extended by Orxonox to support parenthesis as additional safe-mode. 276 */ 338 277 SubString::SPLIT_LINE_STATE 339 SubString::splitLine(std::vector<std::string>& ret,340 std::vector<bool>& b InSafemode,278 SubString::splitLine(std::vector<std::string>& tokens, 279 std::vector<bool>& bTokenInSafemode, 341 280 const std::string& line, 342 281 const std::string& delimiters, 343 282 const std::string& delimiterNeighbours, 344 bool emptyEntries,345 char escape _char,346 bool removeEscapeChar,347 char safemode _char,348 bool removeSafemodeChar,349 char openparenthesis _char,350 char closeparenthesis _char,351 bool removeParenthesisChars,352 char comment _char,283 bool bAllowEmptyEntries, 284 char escapeChar, 285 bool bRemoveEscapeChar, 286 char safemodeChar, 287 bool bRemoveSafemodeChar, 288 char openparenthesisChar, 289 char closeparenthesisChar, 290 bool bRemoveParenthesisChars, 291 char commentChar, 353 292 SPLIT_LINE_STATE start_state) 354 293 { … … 360 299 bool inSafemode = false; 361 300 362 if(start_state != SL_NORMAL && ret.size() > 0)363 { 364 token = ret[ret.size()-1];365 ret.pop_back();366 } 367 if(start_state != SL_NORMAL && b InSafemode.size() > 0)368 { 369 inSafemode = b InSafemode[bInSafemode.size()-1];370 b InSafemode.pop_back();301 if(start_state != SL_NORMAL && tokens.size() > 0) 302 { 303 token = tokens[tokens.size()-1]; 304 tokens.pop_back(); 305 } 306 if(start_state != SL_NORMAL && bTokenInSafemode.size() > 0) 307 { 308 inSafemode = bTokenInSafemode[bTokenInSafemode.size()-1]; 309 bTokenInSafemode.pop_back(); 371 310 } 372 311 … … 376 315 { 377 316 case SL_NORMAL: 378 if(line[i] == escape _char)317 if(line[i] == escapeChar) 379 318 { 380 319 state = SL_ESCAPE; 381 if (! removeEscapeChar)320 if (!bRemoveEscapeChar) 382 321 token += line[i]; 383 322 } 384 else if(line[i] == safemode _char)323 else if(line[i] == safemodeChar) 385 324 { 386 325 state = SL_SAFEMODE; 387 326 inSafemode = true; 388 if (! removeSafemodeChar)327 if (!bRemoveSafemodeChar) 389 328 token += line[i]; 390 329 } 391 else if(line[i] == openparenthesis _char)330 else if(line[i] == openparenthesisChar) 392 331 { 393 332 state = SL_PARENTHESES; 394 333 inSafemode = true; 395 if (! removeParenthesisChars)334 if (!bRemoveParenthesisChars) 396 335 token += line[i]; 397 336 } 398 else if(line[i] == comment _char)337 else if(line[i] == commentChar) 399 338 { 400 339 if (fallBackNeighbours > 0) 401 340 token = token.substr(0, token.size() - fallBackNeighbours); 402 // /FINISH403 if( emptyEntries || token.size() > 0)341 // FINISH 342 if(bAllowEmptyEntries || token.size() > 0) 404 343 { 405 ret.push_back(token);344 tokens.push_back(token); 406 345 token.clear(); 407 b InSafemode.push_back(inSafemode);346 bTokenInSafemode.push_back(inSafemode); 408 347 inSafemode = false; 409 348 } … … 416 355 if (fallBackNeighbours > 0) 417 356 token = token.substr(0, token.size() - fallBackNeighbours); 418 // /FINISH419 if( emptyEntries || token.size() > 0)357 // FINISH 358 if(bAllowEmptyEntries || token.size() > 0) 420 359 { 421 ret.push_back(token);360 tokens.push_back(token); 422 361 token.clear(); 423 b InSafemode.push_back(inSafemode);362 bTokenInSafemode.push_back(inSafemode); 424 363 inSafemode = false; 425 364 } … … 434 373 else 435 374 { 436 i++;375 ++i; 437 376 continue; 438 377 } … … 444 383 break; 445 384 case SL_ESCAPE: 446 if (! removeSafemodeChar)385 if (!bRemoveSafemodeChar) 447 386 token += line[i]; 448 387 else … … 461 400 break; 462 401 case SL_SAFEMODE: 463 if(line[i] == safemode _char)402 if(line[i] == safemodeChar) 464 403 { 465 404 state = SL_NORMAL; 466 if (! removeSafemodeChar)405 if (!bRemoveSafemodeChar) 467 406 token += line[i]; 468 407 } 469 else if(line[i] == escape _char)408 else if(line[i] == escapeChar) 470 409 { 471 410 state = SL_SAFEESCAPE; … … 491 430 492 431 case SL_PARENTHESES: 493 if(line[i] == closeparenthesis _char)432 if(line[i] == closeparenthesisChar) 494 433 { 495 434 state = SL_NORMAL; 496 if (! removeParenthesisChars)435 if (!bRemoveParenthesisChars) 497 436 token += line[i]; 498 437 } 499 else if(line[i] == escape _char)438 else if(line[i] == escapeChar) 500 439 { 501 440 state = SL_PARENTHESESESCAPE; … … 523 462 if(line[i] == '\n') 524 463 { 525 // /FINISH464 // FINISH 526 465 if(token.size() > 0) 527 466 { 528 ret.push_back(token);467 tokens.push_back(token); 529 468 token.clear(); 530 b InSafemode.push_back(inSafemode);469 bTokenInSafemode.push_back(inSafemode); 531 470 inSafemode = false; 532 471 } … … 543 482 break; 544 483 } 545 i++;546 } 547 548 // /FINISH484 ++i; 485 } 486 487 // FINISH 549 488 if (fallBackNeighbours > 0) 550 489 token = token.substr(0, token.size() - fallBackNeighbours); 551 if( emptyEntries || token.size() > 0)552 { 553 ret.push_back(token);490 if(bAllowEmptyEntries || token.size() > 0) 491 { 492 tokens.push_back(token); 554 493 token.clear(); 555 b InSafemode.push_back(inSafemode);494 bTokenInSafemode.push_back(inSafemode); 556 495 inSafemode = false; 557 496 } … … 559 498 } 560 499 561 562 /** 563 * @brief Some nice debug information about this SubString 564 */ 500 /** 501 @brief Some nice debug information about this SubString. 502 */ 565 503 void SubString::debug() const 566 504 { 567 printf("Substring-information::count=%d ::", this->strings.size());568 for (unsigned int i = 0; i < this-> strings.size(); i++)569 printf("s%d='%s'::", i, this->strings[i].c_str());570 printf("\n");505 COUT(0) << "Substring-information::count=" << this->tokens_.size() << " ::"; 506 for (unsigned int i = 0; i < this->tokens_.size(); ++i) 507 COUT(0) << "s" << i << "='" << this->tokens_[i].c_str() << "'::"; 508 COUT(0) << std::endl; 571 509 } 572 510 } -
code/branches/doc/src/libraries/util/SubString.h
r7297 r7327 37 37 */ 38 38 39 /*! 40 * @file 41 * @brief a small class to get the parts of a string separated by commas 42 * 43 * This class is also identified as a Tokenizer. It splits up one long 44 * String into multiple small ones by a designated Delimiter. 45 * 46 * Substring is Advanced, and it is possible, to split a string by ',' 47 * but also removing leading and trailing spaces around the comma. 48 * 49 * Example: 50 * Split the String std::string st = "1345, The new empire , is , orxonox" 51 * is splitted with: 52 * @code SubString(st, ',', " \n\t") @endcode 53 * into 54 * "1345", "The new empire", "is", "orxonox" 55 * As you can see, the useless spaces around ',' were removed. 56 */ 39 /** 40 @file 41 @ingroup Util String 42 @brief a small class to get the parts of a string separated by commas 43 44 @anchor SubStringExample 45 46 The class SubString can be used to split an std::string into multiple tokens, using 47 a delimiter. SubString allows different options, for example to remove whitespaces 48 around the delimiters or different safe-mode chars, like quotation marks and braces. 49 50 You can access the tokens of the SubString using the [] operator like an array. 51 SubString also supports to join the tokens (or a subset of the tokens) again using 52 @ref orxonox::SubString::join() "join()". It's even possible to get a subset of the 53 SubString as another SubString using @ref orxonox::SubString::subSet() "subSet()". 54 55 Example: 56 @code 57 std::string text = "This is a test, \"Hello \\\" World\" and vector {1, 2, 3}"; 58 SubString tokens(text, SubString::WhiteSpaces, "", false, '\\', true, '"', true, '{', '}', true, '\0'); 59 60 for (unsigned int i = 0; i < tokens.size(); ++i) 61 COUT(0) << i << ": " << tokens[i] << std::endl; 62 @endcode 63 64 The output of this code is: 65 - 0: This 66 - 1: is 67 - 2: a 68 - 3: test, 69 - 4: Hello " World 70 - 5: and 71 - 6: vector 72 - 7: 1, 2, 3 73 74 The string was split using the delimiter " ". A string between quotation mark is not 75 split, the same holds for strings between '{' and '}'. Note how the quotation marks and 76 the braces were removed from the tokens, because the corresponding argument is 'true'. 77 78 Also note that the comma after "test" in token 3 is still there - it is neither part of the 79 delimiters SubString::WhiteSpaces nor part of the delimiterNeighbours parameter, so it 80 remains a part of the token. 81 */ 57 82 58 83 #ifndef __SubString_H__ … … 66 91 namespace orxonox 67 92 { 68 //! A class that can load one string and split it in multipe ones69 93 /** 70 * SubString is a very Powerfull way to create a SubSet from a String 71 * It can be used, to Split strings append them and join them again. 72 */ 94 @brief A class that splits a string into multiple tokens using different options. 95 96 The string is split into multiple tokens using a delimiter. Different options like 97 escape character, quotation marks, and more can be used to satisfy your needs. 98 99 See @ref SubStringExample "this description" for an example. 100 */ 73 101 class _UtilExport SubString 74 102 { 75 public:76 //! An enumerator for the State the Parser is in77 typedef enum{103 /// An enumerator for the internal state of the parser 104 enum SPLIT_LINE_STATE 105 { 78 106 SL_NORMAL, //!< Normal state 79 107 SL_ESCAPE, //!< After an escape character 80 SL_SAFEMODE, //!< In safe mode ( between "" mostly).108 SL_SAFEMODE, //!< In safe mode (usually between quotation marks). 81 109 SL_SAFEESCAPE, //!< In safe mode with the internal escape character, that escapes even the savemode character. 82 110 SL_COMMENT, //!< In Comment mode. 83 111 SL_PARENTHESES, //!< Between parentheses (usually '{' and '}') 84 112 SL_PARENTHESESESCAPE, //!< Between parentheses with the internal escape character, that escapes even the closing paranthesis character. 85 } SPLIT_LINE_STATE; 86 113 }; 87 114 88 115 public: 89 116 SubString(); 90 SubString(const std::string& string, char delimiter = ','); 91 SubString(const std::string& string, 92 const std::string& delimiters, const std::string& delimiterNeighbours = "", bool emptyEntries=false, 93 char escapeChar ='\\', bool removeEscapeChar = true, char safemode_char = '"', bool removeSafemodeChar = true, 94 char openparenthesis_char = '{', char closeparenthesis_char = '}', bool removeParenthesisChars = true, char comment_char = '\0'); 117 SubString(const std::string& line, 118 const std::string& delimiters = SubString::WhiteSpaces, 119 const std::string& delimiterNeighbours = "", 120 bool bAllowEmptyEntries=false, 121 char escapeChar ='\\', 122 bool bRemoveEscapeChar = true, 123 char safemodeChar = '"', 124 bool bRemoveSafemodeChar = true, 125 char openparenthesisChar = '{', 126 char closeparenthesisChar = '}', 127 bool bRemoveParenthesisChars = true, 128 char commentChar = '\0'); 95 129 SubString(unsigned int argc, const char** argv); 96 /** @brief create a Substring as a copy of another one. @param subString the SubString to copy. */ 97 SubString(const SubString& subString) { *this = subString; }; 98 SubString(const SubString& subString, unsigned int subSetBegin); 99 SubString(const SubString& subString, unsigned int subSetBegin, unsigned int subSetEnd); 130 SubString(const SubString& other, unsigned int begin); 131 SubString(const SubString& other, unsigned int begin, unsigned int end); 100 132 ~SubString(); 101 133 102 134 // operate on the SubString 103 SubString& operator=(const SubString& subString);104 bool operator==(const SubString& subString) const;105 bool compare(const SubString& subString) const;106 bool compare(const SubString& subString, unsigned int length) const;107 SubString operator+(const SubString& subString) const;108 SubString& operator+=(const SubString& subString);109 / ** @param subString the String to append @returns appended String. @brief added for convenience */110 SubString& append(const SubString subString) { return (*this += subString); };135 SubString& operator=(const SubString& other); 136 bool operator==(const SubString& other) const; 137 bool compare(const SubString& other) const; 138 bool compare(const SubString& other, unsigned int length) const; 139 SubString operator+(const SubString& other) const; 140 SubString& operator+=(const SubString& other); 141 /// Appends the tokens of another SubString to this. @return This SubString. 142 inline SubString& append(const SubString& other) { return (*this += other); } 111 143 112 144 ///////////////////////////////////////// 113 145 // Split and Join the any String. /////// 114 unsigned int split(const std::string& string = "", char delimiter = ','); 115 unsigned int split(const std::string& string, 116 const std::string& delimiters, const std::string& delimiterNeighbours = "", bool emptyEntries = false, 117 char escapeChar ='\\', bool removeEscapeChar = true, char safemode_char = '"', bool removeSafemodeChar = true, 118 char openparenthesis_char = '{', char closeparenthesis_char = '}', bool removeParenthesisChars = true, char comment_char = '\0'); 146 unsigned int split(const std::string& line, 147 const std::string& delimiters = SubString::WhiteSpaces, 148 const std::string& delimiterNeighbours = "", 149 bool bAllowEmptyEntries = false, 150 char escapeChar ='\\', 151 bool bRemoveEscapeChar = true, 152 char safemodeChar = '"', 153 bool bRemoveSafemodeChar = true, 154 char openparenthesisChar = '{', 155 char closeparenthesisChar = '}', 156 bool bRemoveParenthesisChars = true, 157 char commentChar = '\0'); 158 119 159 std::string join(const std::string& delimiter = " ") const; 120 160 //////////////////////////////////////// 121 161 122 162 // retrieve a SubSet from the String 123 SubString subSet(unsigned int subSetBegin) const;124 SubString subSet(unsigned int subSetBegin, unsigned int subSetEnd) const;163 SubString subSet(unsigned int begin) const; 164 SubString subSet(unsigned int begin, unsigned int end) const; 125 165 126 166 // retrieve Information from within 127 /** @brief Returns true if the SubString is empty */ 128 inline bool empty() const { return this->strings.empty(); }; 129 /** @brief Returns the count of Strings stored in this substring */ 130 inline unsigned int size() const { return this->strings.size(); }; 131 /** @brief Returns the i'th string from the subset of Strings @param i the i'th String */ 132 inline const std::string& operator[](unsigned int i) const { return this->strings[i]; }; 133 /** @brief Returns the i'th string from the subset of Strings @param i the i'th String */ 134 inline const std::string& getString(unsigned int i) const { return (*this)[i]; }; 135 /** @brief Returns all Strings as std::vector */ 136 inline const std::vector<std::string>& getAllStrings() const { return this->strings; } 137 /** @brief Returns true if the token is in safemode. @param i the i'th token */ 138 inline bool isInSafemode(unsigned int i) const { return this->bInSafemode[i]; } 139 /** @brief Returns the front of the StringList. */ 140 inline const std::string& front() const { return this->strings.front(); }; 141 /** @brief Returns the back of the StringList. */ 142 inline const std::string& back() const { return this->strings.back(); }; 143 /** @brief removes the back of the strings list. */ 144 inline void pop_back() { this->strings.pop_back(); this->bInSafemode.pop_back(); }; 145 167 /// Returns true if the SubString is empty 168 inline bool empty() const { return this->tokens_.empty(); } 169 /// Returns the number of tokens stored in this SubString 170 inline unsigned int size() const { return this->tokens_.size(); } 171 /// Returns the i'th token from the subset of strings @param index The index of the requested doken 172 inline const std::string& operator[](unsigned int index) const { return this->tokens_[index]; } 173 /// Returns the i'th token from the subset of strings @param index The index of the requested token 174 inline const std::string& getString(unsigned int index) const { return (*this)[index]; } 175 /// Returns all tokens as std::vector 176 inline const std::vector<std::string>& getAllStrings() const { return this->tokens_; } 177 /// Returns true if the token is in safemode. @param index The index of the token 178 inline bool isInSafemode(unsigned int index) const { return this->bTokenInSafemode_[index]; } 179 /// Returns the front of the list of tokens. 180 inline const std::string& front() const { return this->tokens_.front(); } 181 /// Returns the back of the list of tokens. 182 inline const std::string& back() const { return this->tokens_.back(); } 183 /// Removes the back of the list of tokens. 184 inline void pop_back() { this->tokens_.pop_back(); this->bTokenInSafemode_.pop_back(); } 185 186 void debug() const; 187 188 public: 189 static const std::string WhiteSpaces; ///< All whitespaces (usually used as delimiters or delimiterNeighbours 190 static const std::string WhiteSpacesWithComma; ///< All whitespaces and the comma (usually used as delimiters) 191 static const SubString NullSubString; ///< An empty SubString 192 193 private: 146 194 // the almighty algorithm. 147 static SPLIT_LINE_STATE splitLine(std::vector<std::string>& ret,148 std::vector<bool>& b InSafemode,195 static SPLIT_LINE_STATE splitLine(std::vector<std::string>& tokens, 196 std::vector<bool>& bTokenInSafemode, 149 197 const std::string& line, 150 198 const std::string& delimiters = SubString::WhiteSpaces, 151 199 const std::string& delimiterNeighbours = "", 152 bool emptyEntries = false,153 char escape _char = '\\',154 bool removeEscapeChar = true,155 char safemode _char = '"',156 bool removeSafemodeChar = true,157 char openparenthesis _char = '{',158 char closeparenthesis _char = '}',159 bool removeParenthesisChars = true,160 char comment _char = '\0',200 bool bAllowEmptyEntries = false, 201 char escapeChar = '\\', 202 bool bRemoveEscapeChar = true, 203 char safemodeChar = '"', 204 bool bRemoveSafemodeChar = true, 205 char openparenthesisChar = '{', 206 char closeparenthesisChar = '}', 207 bool bRemoveParenthesisChars = true, 208 char commentChar = '\0', 161 209 SPLIT_LINE_STATE start_state = SL_NORMAL); 162 // debugging. 163 void debug() const; 164 165 public: 166 static const std::string WhiteSpaces; 167 static const std::string WhiteSpacesWithComma; 168 static const SubString NullSubString; 169 170 private: 171 std::vector<std::string> strings; //!< strings produced from a single string splitted in multiple strings 172 std::vector<bool> bInSafemode; 210 211 std::vector<std::string> tokens_; ///< The tokens after spliting the input line 212 std::vector<bool> bTokenInSafemode_; ///< Saves for each token if it was in safe mode (between quotation marks or parenthesis) 173 213 }; 174 214 } -
code/branches/doc/src/libraries/util/TemplateUtils.h
r5738 r7327 29 29 /** 30 30 @file 31 @ingroup Util 31 32 @brief Declaration of various helper templates. 32 33 */ -
code/branches/doc/src/libraries/util/VA_NARGS.h
r7284 r7327 29 29 /** 30 30 @file 31 @ingroup Util 31 32 @brief Declaration of the ORXONOX_VA_NARGS macro which returns the number of arguments passed to a variadic macro. 32 33 */
Note: See TracChangeset
for help on using the changeset viewer.