8d16df12fdaab25011c4db1d0556a801c0f6b8d4
[platform/core/uifw/dali-core.git] / dali / public-api / common / dali-vector.h
1 #ifndef __DALI_VECTOR_H__
2 #define __DALI_VECTOR_H__
3
4 /*
5  * Copyright (c) 2017 Samsung Electronics Co., Ltd.
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  */
20
21 // EXTERNAL INCLUDES
22 #include <cstddef>
23 #include <algorithm>
24
25 // INTERNAL INCLUDES
26 #include <dali/public-api/common/dali-common.h>
27 #include <dali/public-api/common/type-traits.h>
28 #include <dali/public-api/math/math-utils.h>
29
30 /**
31  * @brief For DALi internal use, asserts are enabled in debug builds.
32  *
33  * For Application use, asserts can be enabled manually.
34  * @SINCE_1_0.0
35  */
36 #if defined( DEBUG_ENABLED )
37 #define ENABLE_VECTOR_ASSERTS
38 #endif
39
40 #if defined( ENABLE_VECTOR_ASSERTS )
41 #define DALI_ASSERT_VECTOR(cond) DALI_ASSERT_ALWAYS(cond)
42 #else
43 #define DALI_ASSERT_VECTOR(cond)
44 #endif
45
46 namespace Dali
47 {
48 /**
49  * @addtogroup dali_core_common
50  * @{
51  */
52
53 /**
54  * @brief Base class to handle the memory of simple vector.
55  *
56  * Memory layout is such that it has two std::size_t to hold the count
57  * and capacity of the vector. VectorBase::mData is adjusted so that it points to the
58  * beginning of the first real item so that iterating the items is quick.
59  * @SINCE_1_0.0
60  */
61 class DALI_IMPORT_API VectorBase
62 {
63 public: // Typedefs
64
65   typedef std::size_t SizeType;
66
67 protected: // Construction
68
69   /**
70    * @brief Default constructor. Does not allocate space.
71    * @SINCE_1_0.0
72    */
73   VectorBase();
74
75   /**
76    * @brief Destructor.
77    *
78    * Does not release the space. Derived class needs to call Release.
79    * Not virtual as this should not be called directly and we do not want
80    * a vtable for this class as it would unnecessarily increase size.
81    * @SINCE_1_0.0
82    */
83   ~VectorBase();
84
85 public: // API
86
87   /**
88    * @brief This method is inlined as it's needed frequently for Vector::End() iterator.
89    *
90    * @SINCE_1_0.0
91    * @return The count of elements in this vector
92    */
93   SizeType Count() const
94   {
95     SizeType items = 0u;
96     if( mData )
97     {
98       SizeType* metadata = reinterpret_cast< SizeType* >( mData );
99       items = *(metadata - 1u);
100     }
101     return items;
102   }
103
104   /**
105    * @brief Gets the count of elements in this vector.
106    * @SINCE_1_0.0
107    * @return The count of elements in this vector
108    */
109   SizeType Size() const
110   {
111     return Count();
112   }
113
114   /**
115    * @brief @ return if the vector is empty.
116    * @SINCE_1_0.0
117    * @return True if the count of elements is empty
118    */
119   bool Empty() const
120   {
121     return Count() == 0u;
122   }
123
124   /**
125    * @brief Gets the capacity of this vector.
126    * @SINCE_1_0.0
127    * @return The capacity of this vector
128    */
129   SizeType Capacity() const;
130
131   /**
132    * @brief Releases the data.
133    *
134    * Does not call destructors on objects held.
135    * @SINCE_1_0.0
136    */
137   void Release();
138
139 protected: // for Derived classes
140
141   /**
142    * @brief Helper to set the count.
143    *
144    * @SINCE_1_0.0
145    * @param[in] count Number of elements in the vector
146    */
147   void SetCount( SizeType count );
148
149   /**
150    * @brief Reserves space in the vector.
151    *
152    * @SINCE_1_0.0
153    * @param[in] count Count of elements to reserve
154    * @param[in] elementSize Size of a single element
155    */
156   void Reserve( SizeType count, SizeType elementSize );
157
158   /**
159    * @brief Copy a vector.
160    *
161    * @SINCE_1_0.0
162    * @param[in] vector Vector to copy from
163    * @param[in] elementSize Size of a single element
164    */
165   void Copy( const VectorBase& vector, SizeType elementSize );
166
167   /**
168    * @brief Swaps the contents of two vectors.
169    *
170    * @SINCE_1_0.0
171    * @param[in] vector Vector to swap with
172    */
173   void Swap( VectorBase& vector );
174
175   /**
176    * @brief Erases an element.
177    *
178    * Does not change capacity.
179    * @SINCE_1_0.0
180    * @param[in] address Address to erase from
181    * @param[in] elementSize Size to erase
182    * @pre Last element cannot be erased as there is nothing to move.
183    */
184   void Erase( char* address, SizeType elementSize );
185
186   /**
187    * @brief Erases a range of elements.
188    *
189    * Does not change capacity.
190    * @SINCE_1_0.0
191    * @param[in] first Address to the first element to be erased
192    * @param[in] last Address to the last element to be erased
193    * @param[in] elementSize Size of one of the elements to be erased
194    * @return Address pointing to the next element of the last one
195    */
196   char* Erase( char* first, char* last, SizeType elementSize );
197
198   /**
199    * @brief Copies a number of bytes from \e source to \e destination.
200    *
201    * \e source and \e destination must not overlap.
202    *
203    * @SINCE_1_0.0
204    * @param[in] destination Pointer to the destination address
205    * @param[in] source Pointer to the source address
206    * @param[in] numberOfBytes The number of bytes to be copied
207    */
208   void CopyMemory( char* destination, const char* source, size_t numberOfBytes );
209
210 private:
211
212   // not copiable as it does not know the size of elements
213   VectorBase( const VectorBase& ); ///< Undefined @SINCE_1_0.0
214   VectorBase& operator=( const VectorBase& ); ///< Undefined @SINCE_1_0.0
215
216 protected: // Data
217
218   void* mData; ///< Pointer to the data.
219
220 };
221
222 /**
223  * @brief Vector algorithm variant for trivial types.
224  *
225  * Trivial types do not need destructor or copy constructor called.
226  * @SINCE_1_0.0
227  */
228 template< bool IsTrivial >
229 class VectorAlgorithms : public VectorBase
230 {
231 protected: // API for deriving classes
232
233   typedef VectorBase::SizeType SizeType;
234
235   /**
236    * @brief Empty constructor.
237    * @SINCE_1_0.0
238    */
239   VectorAlgorithms()
240   { }
241
242   /**
243    * @brief Empty destructor.
244    * @SINCE_1_0.0
245    */
246   ~VectorAlgorithms()
247   { }
248
249   /**
250    * @brief Copy vector contents.
251    *
252    * @SINCE_1_0.0
253    * @param[in] rhs VectorBase object to copy from
254    * @param[in] elementSize Size of the content
255    */
256   void Copy( const VectorBase& rhs, SizeType elementSize )
257   {
258     if( rhs.Capacity() > 0u )
259     {
260       VectorBase::Copy( rhs, elementSize );
261     }
262     else
263     {
264       VectorBase::Release();
265     }
266   }
267
268   /**
269    * @brief Reserves space in the vector.
270    *
271    * @SINCE_1_0.0
272    * @param[in] count Count of elements to reserve
273    * @param[in] elementSize Size of a single element
274    */
275   void Reserve( SizeType count, SizeType elementSize )
276   {
277     VectorBase::Reserve( count, elementSize );
278   }
279
280   /**
281    * @brief Resizes the vector. Does not change capacity.
282    *
283    * @SINCE_1_0.0
284    * @param[in] count Count to resize to
285    * @param[in] elementSize Size of a single element
286    */
287   void Resize( SizeType count, SizeType elementSize )
288   {
289     // reserve will copy old elements as well
290     Reserve( count, elementSize );
291   }
292
293   /**
294    * @brief Clears the contents.
295    *
296    * For simple types, nothing to do.
297    * @SINCE_1_0.0
298    */
299   void Clear()
300   {
301     if( mData )
302     {
303       VectorBase::SetCount( 0u );
304     }
305   }
306
307   /**
308    * @brief Releases the vector.
309    * @SINCE_1_0.0
310    */
311   void Release()
312   {
313     VectorBase::Release();
314   }
315
316   /**
317    * @brief Erases an element. Does not change capacity.
318    *
319    * @SINCE_1_0.0
320    * @param[in] address Address to erase from
321    * @param[in] elementSize Size to erase
322    */
323   void Erase( char* address, SizeType elementSize )
324   {
325     VectorBase::Erase( address, elementSize );
326   }
327
328   /**
329    * @brief Erases a range of elements. Does not change capacity.
330    *
331    * @SINCE_1_0.0
332    * @param[in] first Address to the first element to be erased
333    * @param[in] last Address to the last element to be erased
334    * @param[in] elementSize Size of one of the elements to be erased
335    * @return Address pointing to the next element of the last one
336    */
337   char* Erase( char* first, char* last, SizeType elementSize )
338   {
339     return VectorBase::Erase( first, last, elementSize );
340   }
341
342   /**
343    * @brief Inserts the given elements into the vector.
344    *
345    * @SINCE_1_0.0
346    * @param[in] at Address where to insert the elements into the vector
347    * @param[in] from Address to the first element to be inserted
348    * @param[in] to Address to the last element to be inserted
349    * @param[in] elementSize Size of one of the elements to be inserted
350    */
351   void Insert( char* at, char* from, char* to, SizeType elementSize )
352   {
353     const SizeType size = to - from;
354     const SizeType count = Count();
355     const SizeType newCount = count + size / elementSize;
356
357     if( newCount > Capacity() )
358     {
359       // Calculate the at offset as the pointer is invalid after the Reserve() call.
360       std::size_t offset = at - reinterpret_cast<char*>( mData );
361
362       // need more space
363       Reserve( NextPowerOfTwo( newCount ), elementSize ); // reserve enough space to store at least the next power of two elements of the new required size.
364
365       // Set the new at pointer.
366       at = reinterpret_cast<char*>( mData ) + offset;
367     }
368     // set new count first as otherwise the debug assert will hit us
369     SetCount( newCount );
370
371     // Move current items to a new position inside the vector.
372     CopyMemory( at + size,
373                 at,
374                 ( reinterpret_cast<char*>( mData ) + count * elementSize ) - at );
375
376     // Copy the given items.
377     CopyMemory( at, from, size );
378   }
379 };
380
381 /**
382  * @brief Vector algorithm variant for complex types.
383  *
384  * Not yet supported so will lead to compile error
385  * as constructor and destructor are private.
386  * TODO add support for this variant.
387  * @SINCE_1_0.0
388  */
389 template<>
390 class VectorAlgorithms< false > : public VectorBase
391 {
392 private:
393   VectorAlgorithms()
394   { }
395   ~VectorAlgorithms()
396   { }
397 };
398
399 /**
400  * @brief Vector class with minimum space allocation when it's empty.
401  *
402  * @SINCE_1_0.0
403  * @param type The type of the data that the vector holds
404  */
405 template< class T, bool IsTrivialType = TypeTraits<T>::IS_TRIVIAL_TYPE == true >
406 class Vector : public VectorAlgorithms< IsTrivialType >
407 {
408 public: // API
409
410   /**
411    * @brief Type definitions.
412    * @SINCE_1_0.0
413    */
414   typedef VectorBase::SizeType SizeType; ///< Size type @SINCE_1_0.0
415   typedef T* Iterator;  ///< Most simple Iterator is a pointer @SINCE_1_0.0
416   typedef const T* ConstIterator; ///< Const iterator @SINCE_1_0.0
417   typedef T  ItemType; ///< Item type @SINCE_1_0.0
418
419   enum
420   {
421     BaseType = IsTrivialType
422   };
423
424   /**
425    * @brief Default constructor. Does not allocate any space.
426    * @SINCE_1_0.0
427    */
428   Vector()
429   { }
430
431   /**
432    * @brief Destructor. Releases the allocated space.
433    * @SINCE_1_0.0
434    */
435   ~Vector()
436   {
437     Release();
438   }
439
440   /**
441    * @brief Copy constructor.
442    *
443    * @SINCE_1_0.0
444    * @param[in] vector Vector to copy from
445    */
446   Vector( const Vector& vector )
447   {
448     // reuse assignment
449     operator=( vector );
450   }
451
452   /**
453    * @brief Assignment operator.
454    *
455    * @SINCE_1_0.0
456    * @param[in] vector Vector to assign from
457    * @return Reference to self for chaining
458    */
459   Vector& operator=( const Vector& vector )
460   {
461     if( this != &vector )
462     {
463       VectorAlgorithms<BaseType>::Copy( vector, sizeof( ItemType ) );
464     }
465     return *this;
466   }
467
468   /**
469    * @brief Iterator to the beginning of the data.
470    * @SINCE_1_0.0
471    * @return Iterator to the beginning of the data
472    */
473   Iterator Begin() const
474   {
475     ItemType* address = reinterpret_cast<ItemType*>( VectorBase::mData );
476     return address;
477   }
478
479   /**
480    * @brief Iterator to the end of the data (one past last element).
481    * @SINCE_1_0.0
482    * @return Iterator to the end of the data (one past last element)
483    */
484   Iterator End() const
485   {
486     ItemType* address = reinterpret_cast<ItemType*>( VectorBase::mData );
487     address += VectorBase::Count();
488     return address;
489   }
490
491   /**
492    * Support for C++11 Range-based for loop: for( item : container ).
493    * @SINCE_1_2.60
494    * @return The start iterator
495    */
496   Iterator begin() const
497   {
498     return Begin();
499   }
500
501   /**
502    * Support for C++11 Range-based for loop: for( item : container ).
503    * @SINCE_1_2.60
504    * @return The end iterator
505    */
506   Iterator end() const
507   {
508     return End();
509   }
510
511   /**
512    * @brief Subscript operator.
513    * @SINCE_1_0.0
514    * @param[in] index Index of the element
515    * @return Reference to the element for given index
516    * @pre Index must be in the vector's range.
517    */
518   ItemType& operator[]( SizeType index )
519   {
520     // reuse the const version
521     return const_cast< ItemType& >( const_cast< const Vector< ItemType >& >( *this )[ index ] );
522   }
523
524   /**
525    * @brief Subscript operator.
526    * @SINCE_1_0.0
527    * @param[in] index Index of the element
528    * @return Reference to the element for given index
529    * @pre Index must be in the vector's range.
530    */
531   const ItemType& operator[]( SizeType index ) const
532   {
533     DALI_ASSERT_VECTOR( VectorBase::mData && "Vector is empty" );
534     DALI_ASSERT_VECTOR( index < VectorBase::Count() && "Index out of bounds" );
535     ItemType* address = reinterpret_cast<ItemType*>( VectorBase::mData );
536     address += index;
537     return *address;
538   }
539
540   /**
541    * @brief Pushes back an element to the vector.
542    *
543    * The underlying storage may be reallocated to provide space.
544    * If this occurs, all pre-existing pointers into the vector will
545    * become invalid.
546    *
547    * @SINCE_1_0.0
548    * @param[in] element Element to be added
549    */
550   void PushBack( const ItemType& element )
551   {
552     const SizeType count = VectorBase::Count();
553     const SizeType newCount = count + 1u;
554     const SizeType capacity = VectorBase::Capacity();
555     if( newCount > capacity )
556     {
557       // need more space
558       Reserve( newCount << 1u ); // reserve double the current count
559     }
560     // set new count first as otherwise the debug assert will hit us
561     VectorBase::SetCount( newCount );
562     operator[]( count ) = element;
563   }
564
565   /**
566    * @brief Inserts an element to the vector.
567    *
568    * Elements after \e at are moved one position to the right.
569    *
570    * The underlying storage may be reallocated to provide space.
571    * If this occurs, all pre-existing pointers into the vector will
572    * become invalid.
573    *
574    * @SINCE_1_0.0
575    * @param[in] at Iterator where to insert the elements into the vector
576    * @param[in] element An element to be added
577    * @pre Iterator at must be in the vector's range ( Vector::Begin(), Vector::End() ).
578    */
579   void Insert( Iterator at, const ItemType& element )
580   {
581     DALI_ASSERT_VECTOR( ( at <= End() ) && ( at >= Begin() ) && "Iterator not inside vector" );
582     const SizeType size = sizeof( ItemType );
583     char* address = const_cast<char*>( reinterpret_cast<const char*>( &element ) );
584     VectorAlgorithms<BaseType>::Insert( reinterpret_cast< char* >( at ),
585                                         address,
586                                         address + size,
587                                         size );
588   }
589
590   /**
591    * @brief Inserts the given elements into the vector.
592    *
593    * Elements after \e at are moved the number of given elements positions to the right.
594    *
595    * The underlying storage may be reallocated to provide space.
596    * If this occurs, all pre-existing pointers into the vector will
597    * become invalid.
598    *
599    * @SINCE_1_0.0
600    * @param[in] at Iterator where to insert the elements into the vector
601    * @param[in] from Iterator to the first element to be inserted
602    * @param[in] to Iterator to the last element to be inserted
603    * @pre Iterator \e at must be in the vector's range ( Vector::Begin(), Vector::End() ).
604    * @pre Iterators \e from and \e to must be valid iterators.
605    * @pre Iterator \e from must not be grater than Iterator \e to.
606    *
607    */
608   void Insert( Iterator at, Iterator from, Iterator to )
609   {
610     DALI_ASSERT_VECTOR( ( at <= End() ) && ( at >= Begin() ) && "Iterator not inside vector" );
611     DALI_ASSERT_VECTOR( ( from <= to ) && "from address can't be greater than to" );
612
613     if( from == to )
614     {
615       // nothing to copy.
616       return;
617     }
618
619     VectorAlgorithms<BaseType>::Insert( reinterpret_cast< char* >( at ),
620                                         reinterpret_cast< char* >( from ),
621                                         reinterpret_cast< char* >( to ),
622                                         sizeof( ItemType ) );
623   }
624
625   /**
626    * @brief Reserves space in the vector.
627    *
628    * Reserving less than current Capacity is a no-op.
629    * @SINCE_1_0.0
630    * @param[in] count Count of elements to reserve
631    */
632   void Reserve( SizeType count )
633   {
634     VectorAlgorithms<BaseType>::Reserve( count, sizeof( ItemType ) );
635   }
636
637   /**
638    * @brief Resizes the vector. Does not change capacity.
639    *
640    * @SINCE_1_0.0
641    * @param[in] count Count to resize to
642    */
643   void Resize( SizeType count )
644   {
645     ItemType item = ItemType();
646     Resize(count, item);
647   }
648
649   /**
650    * @brief Resizes the vector. Does not change capacity.
651    *
652    * @SINCE_1_0.0
653    * @param[in] count Count to resize to
654    * @param[in] item An item to insert to the new indices
655    */
656   void Resize( SizeType count, const ItemType& item )
657   {
658     const SizeType oldCount = VectorBase::Count();
659     if( count <= oldCount )
660     {
661       // getting smaller so just set count
662       VectorBase::SetCount( count );
663     }
664     else
665     {
666       // remember how many new items get added
667       SizeType newItems = count - oldCount;
668       Reserve( count );
669       for( ; newItems > 0u; --newItems )
670       {
671         PushBack( item );
672       }
673     }
674   }
675
676   /**
677    * @brief Erases an element.
678    *
679    * Does not change capacity. Other elements get moved.
680    *
681    * @SINCE_1_0.0
682    * @param[in] iterator Iterator pointing to the item to remove
683    * @return Iterator pointing to next element
684    * @pre Iterator \e iterator must be within the vector's range ( Vector::Begin(), Vector::End() - 1 ).
685    *
686    */
687   Iterator Erase( Iterator iterator )
688   {
689     DALI_ASSERT_VECTOR( (iterator < End()) && (iterator >= Begin()) && "Iterator not inside vector" );
690     if( iterator < ( End() - 1u ) )
691     {
692       VectorAlgorithms<BaseType>::Erase( reinterpret_cast< char* >( iterator ), sizeof( ItemType ) );
693     }
694     else
695     {
696       // just remove the element
697       Remove( iterator );
698     }
699     return iterator;
700   }
701
702   /**
703    * @brief Erases a range of elements.
704    *
705    * Does not change capacity. Other elements get moved.
706    *
707    * @SINCE_1_0.0
708    * @param[in] first Iterator to the first element to be erased
709    * @param[in] last Iterator to the last element to be erased
710    *
711    * @return Iterator pointing to the next element of the last one
712    * @pre Iterator \e first must be in the vector's range ( Vector::Begin(), Vector::End() ).
713    * @pre Iterator \e last must be in the vector's range ( Vector::Begin(), Vector::End() ).
714    * @pre Iterator \e first must not be grater than Iterator \e last.
715    *
716    */
717   Iterator Erase( Iterator first, Iterator last )
718   {
719     DALI_ASSERT_VECTOR( ( first <= End() ) && ( first >= Begin() ) && "Iterator not inside vector" );
720     DALI_ASSERT_VECTOR( ( last <= End() ) && ( last >= Begin() ) && "Iterator not inside vector" );
721     DALI_ASSERT_VECTOR( ( first <= last ) && "first iterator greater than last" );
722
723     Iterator nextElement;
724
725     if( last == End() )
726     {
727       // Erase up to the end.
728       VectorBase::SetCount( VectorBase::Count() - ( last - first ) );
729       nextElement = End();
730     }
731     else
732     {
733       nextElement = reinterpret_cast<Iterator>( VectorAlgorithms<BaseType>::Erase( reinterpret_cast< char* >( first ),
734                                                                                    reinterpret_cast< char* >( last ),
735                                                                                    sizeof( ItemType ) ) );
736     }
737
738     return nextElement;
739   }
740
741   /**
742    * @brief Removes an element.
743    *
744    * Does not maintain order. Swaps the element with end and
745    * decreases size by one.  This is much faster than Erase so use
746    * this in case order does not matter. Does not change capacity.
747    *
748    * @SINCE_1_0.0
749    * @param[in] iterator Iterator pointing to the item to remove
750    * @pre Iterator \e iterator must be in the vector's range ( Vector::Begin(), Vector::End() - 1 ).
751    *
752    */
753   void Remove( Iterator iterator )
754   {
755     DALI_ASSERT_VECTOR( (iterator < End()) && (iterator >= Begin()) && "Iterator not inside vector" );
756
757     Iterator last = End() - 1u;
758     if( last > iterator )
759     {
760       std::swap( *iterator, *last );
761     }
762     VectorBase::SetCount( VectorBase::Count() - 1u );
763   }
764
765   /**
766    * @brief Swaps the contents of two vectors.
767    *
768    * @SINCE_1_0.0
769    * @param[in] vector Vector to swap with
770    */
771   void Swap( Vector& vector )
772   {
773     VectorBase::Swap( vector );
774   }
775
776   /**
777    * @brief Clears the contents of the vector. Keeps its capacity.
778    * @SINCE_1_0.0
779    */
780   void Clear()
781   {
782     VectorAlgorithms<BaseType>::Clear();
783   }
784
785   /**
786    * @brief Releases the memory that the vector holds.
787    * @SINCE_1_0.0
788    */
789   void Release()
790   {
791     VectorAlgorithms<BaseType>::Release();
792   }
793 };
794
795 /**
796  * @}
797  */
798 } // namespace Dali
799
800 #endif /* __DALI_VECTOR_H__ */