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