Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

Changeset 7327


Ignore:
Timestamp:
Sep 3, 2010, 12:19:53 AM (14 years ago)
Author:
landauf
Message:

added documentation

Location:
code/branches/doc
Files:
1 deleted
12 edited

Legend:

Unmodified
Added
Removed
  • code/branches/doc/src/libraries/util/Serialise.h

    r7182 r7327  
    2929/**
    3030    @file
     31    @ingroup Util
    3132    @brief Functions to serialise most of the types/classed used in Orxonox
    3233*/
     
    5354    template <class T> inline bool checkEquality( const T& variable, uint8_t* mem );
    5455
    55  
     56
    5657  // =========== char*
    57    
     58
    5859  inline uint32_t returnSize( char*& variable )
    5960  {
    6061    return strlen(variable)+1;
    6162  }
    62      
     63
    6364  inline void saveAndIncrease( char*& variable, uint8_t*& mem )
    6465  {
     
    6667    mem += returnSize(variable);
    6768  }
    68        
     69
    6970  inline void loadAndIncrease( char*& variable, uint8_t*& mem )
    7071  {
     
    7677    mem += len;
    7778  }
    78          
     79
    7980  inline bool checkEquality( char*& variable, uint8_t* mem )
    8081  {
    8182    return strcmp(variable, (char*)mem)==0;
    8283  }
    83    
     84
    8485// =================== Template specialisation stuff =============
    8586
     
    423424        return memcmp(&temp, mem, sizeof(uint64_t))==0;
    424425    }
    425        
     426
    426427// =========== string
    427428
  • code/branches/doc/src/libraries/util/SharedPtr.cc

    r7284 r7327  
    2727 */
    2828
     29/**
     30    @file
     31    @brief Static linkage of the SmallObjectAllocator used by SharedPtr.
     32*/
     33
    2934#include "SharedPtr.h"
    3035
    3136namespace orxonox
    3237{
    33     SmallObjectAllocator& createSharedCounterPool()
     38    namespace detail
    3439    {
    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        }
    3745    }
    3846}
  • code/branches/doc/src/libraries/util/SharedPtr.h

    r7284 r7327  
    2727 */
    2828
     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
    29146#ifndef _SharedPtr_H__
    30147#define _SharedPtr_H__
     
    39156namespace orxonox
    40157{
    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        }
    71193    }
    72194
     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    */
    73209    template <class T>
    74210    class SharedPtr
     
    78214
    79215        public:
     216            /// Default constructor, the pointer is set to NULL.
    80217            inline SharedPtr() : pointer_(0), counter_(0)
    81218            {
    82219            }
    83220
     221            /// Constructor, creates a SharedPtr that points to @a pointer, increments the counter.
    84222            inline SharedPtr(T* pointer) : pointer_(pointer), counter_(0)
    85223            {
    86224                if (this->pointer_)
    87225                {
    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_);
    90228                }
    91229            }
    92230
     231            /// Copy-constructor, this SharedPtr now points to the same object like the other SharedPtr, increments the counter.
    93232            inline SharedPtr(const SharedPtr& other) : pointer_(other.pointer_), counter_(other.counter_)
    94233            {
     
    97236            }
    98237
     238            /// Copy-constructor for SharedPtr with another template agument, increments the counter.
    99239            template <class O>
    100240            inline SharedPtr(const SharedPtr<O>& other) : pointer_(other.pointer_), counter_(other.counter_)
     
    104244            }
    105245
     246            /// Destructor, decrements the counter and deletes the object if the counter becomes zero.
    106247            inline ~SharedPtr()
    107248            {
     
    113254                    {
    114255                        this->counter_->destroy();
    115                         getSharedCounterPool().free(this->counter_);
     256                        detail::getSharedCounterPool().free(this->counter_);
    116257                    }
    117258                }
    118259            }
    119260
     261            /// Assigns a new object, decrements the counter of the old object, increments the counter of the new object.
    120262            inline SharedPtr& operator=(const SharedPtr& other)
    121263            {
     
    124266            }
    125267
     268            /// Assigns a new object with another template argument, decrements the counter of the old object, increments the counter of the new object.
    126269            template <class O>
    127270            inline SharedPtr& operator=(const SharedPtr<O>& other)
     
    131274            }
    132275
     276            /// Casts the pointer to another type
    133277            template <class O>
    134278            inline SharedPtr<O> cast() const
     
    138282            }
    139283
     284            /// Overloaded -> operator, returns the pointer to the managed object.
    140285            inline T* operator->() const
    141286            {
     
    144289            }
    145290
     291            /// Overloaded * operator, returns a reference ot the managed object.
    146292            inline T& operator*() const
    147293            {
     
    150296            }
    151297
     298            /// Returns the pointer to the managed object.
    152299            inline T* get() const
    153300            {
     
    155302            }
    156303
     304            /// Returns true if the pointer is not NULL.
    157305            inline operator bool() const
    158306            {
     
    160308            }
    161309
     310            /// Swaps the pointer and the counter of two instances of SharedPtr with the same template argument.
    162311            inline void swap(SharedPtr& other)
    163312            {
     
    167316
    168317        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)
    170320            {
    171321                if (this->pointer_)
     
    173323            }
    174324
    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
    177327    };
    178328
     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    */
    179360    template <class T, class Parent>
    180361    class SharedChildPtr : public Parent
  • code/branches/doc/src/libraries/util/SignalHandler.h

    r5738 r7327  
    2929/**
    3030    @file
     31    @ingroup Util
    3132    @brief Declaration of the SignalHandler class.
    3233*/
     
    6869    typedef std::list<SignalCallbackRec> SignalCallbackList;
    6970
     71    /// The SignalHandler is used to catch signals like SIGSEGV and write a backtrace to the logfile.
    7072    class SignalHandler : public Singleton<SignalHandler>
    7173    {
     
    99101namespace orxonox
    100102{
     103    /// The SignalHandler is used to catch signals like SIGSEGV and write a backtrace to the logfile. Not implemented on Windows.
    101104    class _UtilExport SignalHandler : public Singleton<SignalHandler>
    102105    {
  • code/branches/doc/src/libraries/util/SmallObjectAllocator.cc

    r7284 r7327  
    2727 */
    2828
     29/**
     30    @file
     31    @brief Implementation of SmallObjectAllocator
     32*/
     33
    2934#include "SmallObjectAllocator.h"
    3035
    3136namespace orxonox
    3237{
     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    */
    3343    SmallObjectAllocator::SmallObjectAllocator(size_t objectSize, size_t numObjects)
    3444    {
    35         this->objectSize_ = std::max(objectSize, sizeof(Chunk));
    36         this->numObjects_ = 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;
    3747        this->first_ = 0;
    3848    }
    3949
     50    /**
     51        @brief Destructor: deletes the allocated memory blocks.
     52    */
    4053    SmallObjectAllocator::~SmallObjectAllocator()
    4154    {
     
    4457    }
    4558
     59    /**
     60        @brief Helper function, used to set the next_ pointer of a Chunk.
     61    */
    4662    /* static */ void SmallObjectAllocator::setNext(void* chunk, void* next)
    4763    {
     
    4965    }
    5066
     67    /**
     68        @brief Helper function, returns the next_ pointer of a Chunk
     69    */
    5170    /* static */ void* SmallObjectAllocator::getNext(void* chunk)
    5271    {
     
    5473    }
    5574
     75    /**
     76        @brief Returns the first free memory chunk or allocates a new block of memory.
     77    */
    5678    void* SmallObjectAllocator::alloc()
    5779    {
     80        // get the first free chunk
    5881        void* chunk = this->first_;
    5982
     83        // check if the chunk exists
    6084        if (chunk)
    6185        {
     86            // yes it does - the first_ pointer now points to the second element in the list
    6287            this->first_ = getNext(chunk);
    6388        }
    6489        else
    6590        {
    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_];
    6793            this->blocks_.push_back(block);
    6894
    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_);
    7198
    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);
    73101
    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_;
    75104
     105            // The first chunk in the block is returned
    76106            chunk = block;
    77107        }
    78108
     109        // return the pointer to the chunk
    79110        return chunk;
    80111    }
    81112
     113    /**
     114        @brief Puts the memory chunk back on the list of free memory.
     115    */
    82116    void SmallObjectAllocator::free(void* chunk)
    83117    {
     118        // The first_ pointer points to the freed chunk, its next_ pointer points to the rest of the list
    84119        setNext(chunk, this->first_);
    85120        this->first_ = chunk;
  • code/branches/doc/src/libraries/util/SmallObjectAllocator.h

    r7284 r7327  
    2727 */
    2828
     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
    2974#ifndef _SmallObjectAllocator_H__
    3075#define _SmallObjectAllocator_H__
     
    3580namespace orxonox
    3681{
     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    */
    3789    class _UtilExport SmallObjectAllocator
    3890    {
     91        /// The memory chunk is at the same time an element of a single linked list.
    3992        struct Chunk
    4093        {
    41             Chunk* next_;
     94            Chunk* next_;   ///< A pointer to the next chunk in the list
    4295        };
    4396
     
    53106            static void* getNext(void* chunk);
    54107
    55             void* first_;
    56             size_t objectSize_;
    57             size_t numObjects_;
     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
    58111
    59             std::vector<char*> blocks_;
     112            std::vector<char*> blocks_;     ///< A list of all allocated memory blocks (used to destroy them again)
    60113    };
    61114}
  • code/branches/doc/src/libraries/util/StringUtils.cc

    r7297 r7327  
    4141namespace orxonox
    4242{
     43    /// A blank string (""). Used to return a blank string by reference.
    4344    std::string BLANKSTRING;
    4445
     46    /// Returns a string of a unique number. This function is guaranteed to never return the same string twice.
    4547    std::string getUniqueNumberString()
    4648    {
     
    4850    }
    4951
    50     /**
    51         @brief Removes all whitespaces from a string.
    52         @param str The string to strip
    53     */
     52    /// Removes all whitespaces from a string.
    5453    void strip(std::string* str)
    5554    {
     
    6362    }
    6463
    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.
    7065    std::string getStripped(const std::string& str)
    7166    {
     
    7570    }
    7671
    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.
    8273    std::string removeTrailingWhitespaces(const std::string& str)
    8374    {
     
    9081
    9182    /**
    92         @brief Returns the position of the next quote in the string, starting with start.
     83        @brief Returns the position of the next quotation mark in the string, starting with start.
    9384        @param str The string
    94         @param start The startposition
    95         @return The position of the next quote (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)
    9687    */
    9788    size_t getNextQuote(const std::string& str, size_t start)
     
    115106
    116107    /**
    117         @brief Returns true if pos is between two quotes.
     108        @brief Returns true if pos is between two quotation marks.
    118109        @param str The string
    119110        @param pos The position to check
    120         @return True if pos is between two quotes
     111        @return True if pos is between two quotation marks
    121112    */
    122113    bool isBetweenQuotes(const std::string& str, size_t pos)
     
    140131    }
    141132
    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"...'.
    147134    bool hasStringBetweenQuotes(const std::string& str)
    148135    {
     
    152139    }
    153140
    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 "".
    158142    std::string getStringBetweenQuotes(const std::string& str)
    159143    {
     
    167151
    168152    /**
    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
    172155    */
    173156    std::string stripEnclosingQuotes(const std::string& str)
     
    207190
    208191    /**
    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
    212194    */
    213195    std::string stripEnclosingBraces(const std::string& str)
     
    223205    /**
    224206        @brief Determines if a string is a comment (starts with a comment-symbol).
    225         @param str The string to check
    226         @return True = it's a comment
    227207
    228208        A comment is defined by a leading '#', '%', ';' or '//'.
     
    252232    }
    253233
    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).
    259235    bool isEmpty(const std::string& str)
    260236    {
     
    262238    }
    263239
    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 '.'.
    269241    bool isNumeric(const std::string& str)
    270242    {
     
    287259    /**
    288260        @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
    291269    */
    292270    std::string addSlashes(const std::string& str)
     
    319297    /**
    320298        @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
    323306    */
    324307    std::string removeSlashes(const std::string& str)
     
    360343    }
    361344
    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.
    366346    void lowercase(std::string* str)
    367347    {
     
    372352    }
    373353
    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.
    379355    std::string getLowercase(const std::string& str)
    380356    {
     
    384360    }
    385361
    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.
    390363    void uppercase(std::string* str)
    391364    {
     
    396369    }
    397370
    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.
    403372    std::string getUppercase(const std::string& str)
    404373    {
     
    410379    /**
    411380        @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
    414382    */
    415383    int nocaseCmp(const std::string& s1, const std::string& s2)
     
    437405
    438406    /**
    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.
    440408        @param s1 First string
    441409        @param s2 Second string
     
    462430    }
    463431
    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.
    466452        @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
    499454    */
    500455    size_t getNextCommentPosition(const std::string& str, size_t start)
  • code/branches/doc/src/libraries/util/StringUtils.h

    r7284 r7327  
    2828
    2929/**
     30    @defgroup String String functions
     31    @ingroup Util
     32*/
     33
     34/**
    3035    @file
     36    @ingroup Util String
    3137    @brief Declaration of several string manipulation functions, used in many parts of the game.
    3238*/
  • code/branches/doc/src/libraries/util/SubString.cc

    r7297 r7327  
    4040#include "SubString.h"
    4141#include <cstdio>
     42#include "Debug.h"
    4243
    4344namespace orxonox
    4445{
    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    */
    4853    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    */
    121120    SubString::SubString(unsigned int argc, const char** argv)
    122121    {
    123122        for(unsigned int i = 0; i < argc; ++i)
    124123        {
    125             this->strings.push_back(std::string(argv[i]));
    126             this->bInSafemode.push_back(false);
    127         }
    128     }
    129 
    130     /**
    131      * @brief removes the object from memory
    132      */
     124            this->tokens_.push_back(std::string(argv[i]));
     125            this->bTokenInSafemode_.push_back(false);
     126        }
     127    }
     128
     129    /**
     130        @brief Destructor
     131    */
    133132    SubString::~SubString()
    134133    { }
    135134
    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_;
    154143        return *this;
    155144    }
    156145
    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())
    187170            return false;
    188171
    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]))
    191174                return false;
    192175        return true;
    193176    }
    194177
    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));
    218197        }
    219198        return *this;
    220199    }
    221200
    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    */
    272220    std::string SubString::join(const std::string& delimiter) const
    273221    {
    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];
    279227            return retVal;
    280228        }
     
    283231    }
    284232
    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    */
    338277    SubString::SPLIT_LINE_STATE
    339     SubString::splitLine(std::vector<std::string>& ret,
    340                          std::vector<bool>& bInSafemode,
     278    SubString::splitLine(std::vector<std::string>& tokens,
     279                         std::vector<bool>& bTokenInSafemode,
    341280                         const std::string& line,
    342281                         const std::string& delimiters,
    343282                         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,
    353292                         SPLIT_LINE_STATE start_state)
    354293    {
     
    360299        bool inSafemode = false;
    361300
    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 && bInSafemode.size() > 0)
    368         {
    369             inSafemode = bInSafemode[bInSafemode.size()-1];
    370             bInSafemode.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();
    371310        }
    372311
     
    376315            {
    377316            case SL_NORMAL:
    378                 if(line[i] == escape_char)
     317                if(line[i] == escapeChar)
    379318                {
    380319                    state = SL_ESCAPE;
    381                     if (!removeEscapeChar)
     320                    if (!bRemoveEscapeChar)
    382321                        token += line[i];
    383322                }
    384                 else if(line[i] == safemode_char)
     323                else if(line[i] == safemodeChar)
    385324                {
    386325                    state = SL_SAFEMODE;
    387326                    inSafemode = true;
    388                     if (!removeSafemodeChar)
     327                    if (!bRemoveSafemodeChar)
    389328                        token += line[i];
    390329                }
    391                 else if(line[i] == openparenthesis_char)
     330                else if(line[i] == openparenthesisChar)
    392331                {
    393332                    state = SL_PARENTHESES;
    394333                    inSafemode = true;
    395                     if (!removeParenthesisChars)
     334                    if (!bRemoveParenthesisChars)
    396335                        token += line[i];
    397336                }
    398                 else if(line[i] == comment_char)
     337                else if(line[i] == commentChar)
    399338                {
    400339                    if (fallBackNeighbours > 0)
    401340                        token = token.substr(0, token.size() - fallBackNeighbours);
    402                     /// FINISH
    403                     if(emptyEntries || token.size() > 0)
     341                    // FINISH
     342                    if(bAllowEmptyEntries || token.size() > 0)
    404343                    {
    405                         ret.push_back(token);
     344                        tokens.push_back(token);
    406345                        token.clear();
    407                         bInSafemode.push_back(inSafemode);
     346                        bTokenInSafemode.push_back(inSafemode);
    408347                        inSafemode = false;
    409348                    }
     
    416355                    if (fallBackNeighbours > 0)
    417356                        token = token.substr(0, token.size() - fallBackNeighbours);
    418                     /// FINISH
    419                     if(emptyEntries || token.size() > 0)
     357                    // FINISH
     358                    if(bAllowEmptyEntries || token.size() > 0)
    420359                    {
    421                         ret.push_back(token);
     360                        tokens.push_back(token);
    422361                        token.clear();
    423                         bInSafemode.push_back(inSafemode);
     362                        bTokenInSafemode.push_back(inSafemode);
    424363                        inSafemode = false;
    425364                    }
     
    434373                        else
    435374                        {
    436                             i++;
     375                            ++i;
    437376                            continue;
    438377                        }
     
    444383                break;
    445384            case SL_ESCAPE:
    446                 if (!removeSafemodeChar)
     385                if (!bRemoveSafemodeChar)
    447386                    token += line[i];
    448387                else
     
    461400                break;
    462401            case SL_SAFEMODE:
    463                 if(line[i] == safemode_char)
     402                if(line[i] == safemodeChar)
    464403                {
    465404                    state = SL_NORMAL;
    466                     if (!removeSafemodeChar)
     405                    if (!bRemoveSafemodeChar)
    467406                        token += line[i];
    468407                }
    469                 else if(line[i] == escape_char)
     408                else if(line[i] == escapeChar)
    470409                {
    471410                    state = SL_SAFEESCAPE;
     
    491430
    492431            case SL_PARENTHESES:
    493                 if(line[i] == closeparenthesis_char)
     432                if(line[i] == closeparenthesisChar)
    494433                {
    495434                    state = SL_NORMAL;
    496                     if (!removeParenthesisChars)
     435                    if (!bRemoveParenthesisChars)
    497436                        token += line[i];
    498437                }
    499                 else if(line[i] == escape_char)
     438                else if(line[i] == escapeChar)
    500439                {
    501440                    state = SL_PARENTHESESESCAPE;
     
    523462                if(line[i] == '\n')
    524463                {
    525                     /// FINISH
     464                    // FINISH
    526465                    if(token.size() > 0)
    527466                    {
    528                         ret.push_back(token);
     467                        tokens.push_back(token);
    529468                        token.clear();
    530                         bInSafemode.push_back(inSafemode);
     469                        bTokenInSafemode.push_back(inSafemode);
    531470                        inSafemode = false;
    532471                    }
     
    543482                break;
    544483            }
    545             i++;
    546         }
    547 
    548         /// FINISH
     484            ++i;
     485        }
     486
     487        // FINISH
    549488        if (fallBackNeighbours > 0)
    550489            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);
    554493            token.clear();
    555             bInSafemode.push_back(inSafemode);
     494            bTokenInSafemode.push_back(inSafemode);
    556495            inSafemode = false;
    557496        }
     
    559498    }
    560499
    561 
    562     /**
    563      * @brief Some nice debug information about this SubString
    564      */
     500    /**
     501        @brief Some nice debug information about this SubString.
     502    */
    565503    void SubString::debug() const
    566504    {
    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;
    571509    }
    572510}
  • code/branches/doc/src/libraries/util/SubString.h

    r7297 r7327  
    3737 */
    3838
    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*/
    5782
    5883#ifndef __SubString_H__
     
    6691namespace orxonox
    6792{
    68     //! A class that can load one string and split it in multipe ones
    6993    /**
    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    */
    73101    class _UtilExport SubString
    74102    {
    75     public:
    76         //! An enumerator for the State the Parser is in
    77         typedef enum {
     103        /// An enumerator for the internal state of the parser
     104        enum SPLIT_LINE_STATE
     105        {
    78106            SL_NORMAL,            //!< Normal state
    79107            SL_ESCAPE,            //!< After an escape character
    80             SL_SAFEMODE,          //!< In safe mode (between "" mostly).
     108            SL_SAFEMODE,          //!< In safe mode (usually between quotation marks).
    81109            SL_SAFEESCAPE,        //!< In safe mode with the internal escape character, that escapes even the savemode character.
    82110            SL_COMMENT,           //!< In Comment mode.
    83111            SL_PARENTHESES,       //!< Between parentheses (usually '{' and '}')
    84112            SL_PARENTHESESESCAPE, //!< Between parentheses with the internal escape character, that escapes even the closing paranthesis character.
    85         } SPLIT_LINE_STATE;
    86 
     113        };
    87114
    88115    public:
    89116        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');
    95129        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);
    100132        ~SubString();
    101133
    102134        // 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); }
    111143
    112144        /////////////////////////////////////////
    113145        // 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
    119159        std::string join(const std::string& delimiter = " ") const;
    120160        ////////////////////////////////////////
    121161
    122162        // 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;
    125165
    126166        // 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:
    146194        // the almighty algorithm.
    147         static SPLIT_LINE_STATE splitLine(std::vector<std::string>& ret,
    148                                           std::vector<bool>& bInSafemode,
     195        static SPLIT_LINE_STATE splitLine(std::vector<std::string>& tokens,
     196                                          std::vector<bool>& bTokenInSafemode,
    149197                                          const std::string& line,
    150198                                          const std::string& delimiters = SubString::WhiteSpaces,
    151199                                          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',
    161209                                          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)
    173213    };
    174214}
  • code/branches/doc/src/libraries/util/TemplateUtils.h

    r5738 r7327  
    2929/**
    3030    @file
     31    @ingroup Util
    3132    @brief Declaration of various helper templates.
    3233*/
  • code/branches/doc/src/libraries/util/VA_NARGS.h

    r7284 r7327  
    2929/**
    3030    @file
     31    @ingroup Util
    3132    @brief Declaration of the ORXONOX_VA_NARGS macro which returns the number of arguments passed to a variadic macro.
    3233*/
Note: See TracChangeset for help on using the changeset viewer.