Making DALi public API typesafe using guaranteed types; uint8_t, uint32_t
[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) 2018 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 copiable 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 /**
224  * @brief Vector algorithm variant for trivial types.
225  *
226  * Trivial types do not need destructor or copy constructor called.
227  * @SINCE_1_0.0
228  */
229 template< bool IsTrivial >
230 class VectorAlgorithms : public VectorBase
231 {
232 protected: // API for deriving classes
233
234   typedef VectorBase::SizeType SizeType;
235
236   /**
237    * @brief Empty constructor.
238    * @SINCE_1_0.0
239    */
240   VectorAlgorithms()
241   { }
242
243   /**
244    * @brief Empty destructor.
245    * @SINCE_1_0.0
246    */
247   ~VectorAlgorithms()
248   { }
249
250   /**
251    * @brief Copy vector contents.
252    *
253    * @SINCE_1_0.0
254    * @param[in] rhs VectorBase object to copy from
255    * @param[in] elementSize Size of the content
256    */
257   void Copy( const VectorBase& rhs, SizeType elementSize )
258   {
259     if( rhs.Capacity() > 0u )
260     {
261       VectorBase::Copy( rhs, elementSize );
262     }
263     else
264     {
265       VectorBase::Release();
266     }
267   }
268
269   /**
270    * @brief Reserves space in the vector.
271    *
272    * @SINCE_1_0.0
273    * @param[in] count Count of elements to reserve
274    * @param[in] elementSize Size of a single element
275    */
276   void Reserve( SizeType count, SizeType elementSize )
277   {
278     VectorBase::Reserve( count, elementSize );
279   }
280
281   /**
282    * @brief Resizes the vector. Does not change capacity.
283    *
284    * @SINCE_1_0.0
285    * @param[in] count Count to resize to
286    * @param[in] elementSize Size of a single element
287    */
288   void Resize( SizeType count, SizeType elementSize )
289   {
290     // reserve will copy old elements as well
291     Reserve( count, elementSize );
292   }
293
294   /**
295    * @brief Clears the contents.
296    *
297    * For simple types, nothing to do.
298    * @SINCE_1_0.0
299    */
300   void Clear()
301   {
302     if( mData )
303     {
304       VectorBase::SetCount( 0u );
305     }
306   }
307
308   /**
309    * @brief Releases the vector.
310    * @SINCE_1_0.0
311    */
312   void Release()
313   {
314     VectorBase::Release();
315   }
316
317   /**
318    * @brief Erases an element. Does not change capacity.
319    *
320    * @SINCE_1_0.0
321    * @param[in] address Address to erase from
322    * @param[in] elementSize Size to erase
323    */
324   void Erase( char* address, SizeType elementSize )
325   {
326     VectorBase::Erase( address, elementSize );
327   }
328
329   /**
330    * @brief Erases a range of elements. Does not change capacity.
331    *
332    * @SINCE_1_0.0
333    * @param[in] first Address to the first element to be erased
334    * @param[in] last Address to the last element to be erased
335    * @param[in] elementSize Size of one of the elements to be erased
336    * @return Address pointing to the next element of the last one
337    */
338   char* Erase( char* first, char* last, SizeType elementSize )
339   {
340     return VectorBase::Erase( first, last, elementSize );
341   }
342
343   /**
344    * @brief Inserts the given elements into the vector.
345    *
346    * @SINCE_1_0.0
347    * @param[in] at Address where to insert the elements into the vector
348    * @param[in] from Address to the first element to be inserted
349    * @param[in] to Address to the last element to be inserted
350    * @param[in] elementSize Size of one of the elements to be inserted
351    */
352   void Insert( char* at, char* from, char* to, SizeType elementSize )
353   {
354     const SizeType size = to - from;
355     const SizeType count = Count();
356     const SizeType newCount = count + size / elementSize;
357
358     if( newCount > Capacity() )
359     {
360       // Calculate the at offset as the pointer is invalid after the Reserve() call.
361       std::size_t offset = at - reinterpret_cast<char*>( mData );
362
363       // need more space
364       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.
365
366       // Set the new at pointer.
367       at = reinterpret_cast<char*>( mData ) + offset;
368     }
369     // set new count first as otherwise the debug assert will hit us
370     SetCount( newCount );
371
372     // Move current items to a new position inside the vector.
373     CopyMemory( at + size,
374                 at,
375                 ( reinterpret_cast<char*>( mData ) + count * elementSize ) - at );
376
377     // Copy the given items.
378     CopyMemory( at, from, size );
379   }
380 };
381
382 /**
383  * @brief Vector algorithm variant for complex types.
384  *
385  * Not yet supported so will lead to compile error
386  * as constructor and destructor are private.
387  * TODO add support for this variant.
388  * @SINCE_1_0.0
389  */
390 template<>
391 class VectorAlgorithms< false > : public VectorBase
392 {
393 private:
394   VectorAlgorithms()
395   { }
396   ~VectorAlgorithms()
397   { }
398 };
399
400 /**
401  * @brief Vector class with minimum space allocation when it's empty.
402  *
403  * @SINCE_1_0.0
404  * @param type The type of the data that the vector holds
405  */
406 template< class T, bool IsTrivialType = TypeTraits<T>::IS_TRIVIAL_TYPE == true >
407 class Vector : public VectorAlgorithms< IsTrivialType >
408 {
409 public: // API
410
411   /**
412    * @brief Type definitions.
413    * @SINCE_1_0.0
414    */
415   typedef VectorBase::SizeType SizeType; ///< Size type @SINCE_1_0.0
416   typedef T* Iterator;  ///< Most simple Iterator is a pointer @SINCE_1_0.0
417   typedef const T* ConstIterator; ///< Const iterator @SINCE_1_0.0
418   typedef T  ItemType; ///< Item type @SINCE_1_0.0
419
420   /**
421    * @brief Enumeration for BaseType.
422    * @SINCE_1_0.0
423    */
424   enum
425   {
426     BaseType = IsTrivialType ///< @SINCE_1_0.0
427   };
428
429   /**
430    * @brief Default constructor. Does not allocate any space.
431    * @SINCE_1_0.0
432    */
433   Vector()
434   { }
435
436   /**
437    * @brief Destructor. Releases the allocated space.
438    * @SINCE_1_0.0
439    */
440   ~Vector()
441   {
442     Release();
443   }
444
445   /**
446    * @brief Copy constructor.
447    *
448    * @SINCE_1_0.0
449    * @param[in] vector Vector to copy from
450    */
451   Vector( const Vector& vector )
452   {
453     // reuse assignment
454     operator=( vector );
455   }
456
457   /**
458    * @brief Assignment operator.
459    *
460    * @SINCE_1_0.0
461    * @param[in] vector Vector to assign from
462    * @return Reference to self for chaining
463    */
464   Vector& operator=( const Vector& vector )
465   {
466     if( this != &vector )
467     {
468       VectorAlgorithms<BaseType>::Copy( vector, sizeof( ItemType ) );
469     }
470     return *this;
471   }
472
473   /**
474    * @brief Iterator to the beginning of the data.
475    * @SINCE_1_0.0
476    * @return Iterator to the beginning of the data
477    */
478   Iterator Begin() const
479   {
480     ItemType* address = reinterpret_cast<ItemType*>( VectorBase::mData );
481     return address;
482   }
483
484   /**
485    * @brief Iterator to the end of the data (one past last element).
486    * @SINCE_1_0.0
487    * @return Iterator to the end of the data (one past last element)
488    */
489   Iterator End() const
490   {
491     ItemType* address = reinterpret_cast<ItemType*>( VectorBase::mData );
492     address += VectorBase::Count();
493     return address;
494   }
495
496   /**
497    * Support for C++11 Range-based for loop: for( item : container ).
498    * @SINCE_1_2.60
499    * @return The start iterator
500    */
501   Iterator begin() const
502   {
503     return Begin();
504   }
505
506   /**
507    * Support for C++11 Range-based for loop: for( item : container ).
508    * @SINCE_1_2.60
509    * @return The end iterator
510    */
511   Iterator end() const
512   {
513     return End();
514   }
515
516   /**
517    * @brief Subscript operator.
518    * @SINCE_1_0.0
519    * @param[in] index Index of the element
520    * @return Reference to the element for given index
521    * @pre Index must be in the vector's range.
522    */
523   ItemType& operator[]( SizeType index )
524   {
525     // reuse the const version
526     return const_cast< ItemType& >( const_cast< const Vector< ItemType >& >( *this )[ index ] );
527   }
528
529   /**
530    * @brief Subscript operator.
531    * @SINCE_1_0.0
532    * @param[in] index Index of the element
533    * @return Reference to the element for given index
534    * @pre Index must be in the vector's range.
535    */
536   const ItemType& operator[]( SizeType index ) const
537   {
538     DALI_ASSERT_VECTOR( VectorBase::mData && "Vector is empty" );
539     DALI_ASSERT_VECTOR( index < VectorBase::Count() && "Index out of bounds" );
540     ItemType* address = reinterpret_cast<ItemType*>( VectorBase::mData );
541     address += index;
542     return *address;
543   }
544
545   /**
546    * @brief Pushes back an element to the vector.
547    *
548    * The underlying storage may be reallocated to provide space.
549    * If this occurs, all pre-existing pointers into the vector will
550    * become invalid.
551    *
552    * @SINCE_1_0.0
553    * @param[in] element Element to be added
554    */
555   void PushBack( const ItemType& element )
556   {
557     const SizeType count = VectorBase::Count();
558     const SizeType newCount = count + 1u;
559     const SizeType capacity = VectorBase::Capacity();
560     if( newCount > capacity )
561     {
562       // need more space
563       Reserve( newCount << 1u ); // reserve double the current count
564     }
565     // set new count first as otherwise the debug assert will hit us
566     VectorBase::SetCount( newCount );
567     operator[]( count ) = element;
568   }
569
570   /**
571    * @brief Inserts an element to the vector.
572    *
573    * Elements after \e at are moved one position to the right.
574    *
575    * The underlying storage may be reallocated to provide space.
576    * If this occurs, all pre-existing pointers into the vector will
577    * become invalid.
578    *
579    * @SINCE_1_0.0
580    * @param[in] at Iterator where to insert the elements into the vector
581    * @param[in] element An element to be added
582    * @pre Iterator at must be in the vector's range ( Vector::Begin(), Vector::End() ).
583    */
584   void Insert( Iterator at, const ItemType& element )
585   {
586     DALI_ASSERT_VECTOR( ( at <= End() ) && ( at >= Begin() ) && "Iterator not inside vector" );
587     const SizeType size = sizeof( ItemType );
588     char* address = const_cast<char*>( reinterpret_cast<const char*>( &element ) );
589     VectorAlgorithms<BaseType>::Insert( reinterpret_cast< char* >( at ),
590                                         address,
591                                         address + size,
592                                         size );
593   }
594
595   /**
596    * @brief Inserts the given elements into the vector.
597    *
598    * Elements after \e at are moved the number of given elements positions to the right.
599    *
600    * The underlying storage may be reallocated to provide space.
601    * If this occurs, all pre-existing pointers into the vector will
602    * become invalid.
603    *
604    * @SINCE_1_0.0
605    * @param[in] at Iterator where to insert the elements into the vector
606    * @param[in] from Iterator to the first element to be inserted
607    * @param[in] to Iterator to the last element to be inserted
608    * @pre Iterator \e at must be in the vector's range ( Vector::Begin(), Vector::End() ).
609    * @pre Iterators \e from and \e to must be valid iterators.
610    * @pre Iterator \e from must not be grater than Iterator \e to.
611    *
612    */
613   void Insert( Iterator at, Iterator from, Iterator to )
614   {
615     DALI_ASSERT_VECTOR( ( at <= End() ) && ( at >= Begin() ) && "Iterator not inside vector" );
616     DALI_ASSERT_VECTOR( ( from <= to ) && "from address can't be greater than to" );
617
618     if( from == to )
619     {
620       // nothing to copy.
621       return;
622     }
623
624     VectorAlgorithms<BaseType>::Insert( reinterpret_cast< char* >( at ),
625                                         reinterpret_cast< char* >( from ),
626                                         reinterpret_cast< char* >( to ),
627                                         sizeof( ItemType ) );
628   }
629
630   /**
631    * @brief Reserves space in the vector.
632    *
633    * Reserving less than current Capacity is a no-op.
634    * @SINCE_1_0.0
635    * @param[in] count Count of elements to reserve
636    */
637   void Reserve( SizeType count )
638   {
639     VectorAlgorithms<BaseType>::Reserve( count, sizeof( ItemType ) );
640   }
641
642   /**
643    * @brief Resizes the vector. Does not change capacity.
644    *
645    * @SINCE_1_0.0
646    * @param[in] count Count to resize to
647    */
648   void Resize( SizeType count )
649   {
650     ItemType item = ItemType();
651     Resize(count, item);
652   }
653
654   /**
655    * @brief Resizes the vector. Does not change capacity.
656    *
657    * @SINCE_1_0.0
658    * @param[in] count Count to resize to
659    * @param[in] item An item to insert to the new indices
660    */
661   void Resize( SizeType count, const ItemType& item )
662   {
663     const SizeType oldCount = VectorBase::Count();
664     if( count <= oldCount )
665     {
666       // getting smaller so just set count
667       VectorBase::SetCount( count );
668     }
669     else
670     {
671       // remember how many new items get added
672       SizeType newItems = count - oldCount;
673       Reserve( count );
674       for( ; newItems > 0u; --newItems )
675       {
676         PushBack( item );
677       }
678     }
679   }
680
681   /**
682    * @brief Erases an element.
683    *
684    * Does not change capacity. Other elements get moved.
685    *
686    * @SINCE_1_0.0
687    * @param[in] iterator Iterator pointing to the item to remove
688    * @return Iterator pointing to next element
689    * @pre Iterator \e iterator must be within the vector's range ( Vector::Begin(), Vector::End() - 1 ).
690    *
691    */
692   Iterator Erase( Iterator iterator )
693   {
694     DALI_ASSERT_VECTOR( (iterator < End()) && (iterator >= Begin()) && "Iterator not inside vector" );
695     if( iterator < ( End() - 1u ) )
696     {
697       VectorAlgorithms<BaseType>::Erase( reinterpret_cast< char* >( iterator ), sizeof( ItemType ) );
698     }
699     else
700     {
701       // just remove the element
702       Remove( iterator );
703     }
704     return iterator;
705   }
706
707   /**
708    * @brief Erases a range of elements.
709    *
710    * Does not change capacity. Other elements get moved.
711    *
712    * @SINCE_1_0.0
713    * @param[in] first Iterator to the first element to be erased
714    * @param[in] last Iterator to the last element to be erased
715    *
716    * @return Iterator pointing to the next element of the last one
717    * @pre Iterator \e first must be in the vector's range ( Vector::Begin(), Vector::End() ).
718    * @pre Iterator \e last must be in the vector's range ( Vector::Begin(), Vector::End() ).
719    * @pre Iterator \e first must not be grater than Iterator \e last.
720    *
721    */
722   Iterator Erase( Iterator first, Iterator last )
723   {
724     DALI_ASSERT_VECTOR( ( first <= End() ) && ( first >= Begin() ) && "Iterator not inside vector" );
725     DALI_ASSERT_VECTOR( ( last <= End() ) && ( last >= Begin() ) && "Iterator not inside vector" );
726     DALI_ASSERT_VECTOR( ( first <= last ) && "first iterator greater than last" );
727
728     Iterator nextElement;
729
730     if( last == End() )
731     {
732       // Erase up to the end.
733       VectorBase::SetCount( VectorBase::Count() - ( last - first ) );
734       nextElement = End();
735     }
736     else
737     {
738       nextElement = reinterpret_cast<Iterator>( VectorAlgorithms<BaseType>::Erase( reinterpret_cast< char* >( first ),
739                                                                                    reinterpret_cast< char* >( last ),
740                                                                                    sizeof( ItemType ) ) );
741     }
742
743     return nextElement;
744   }
745
746   /**
747    * @brief Removes an element.
748    *
749    * Does not maintain order. Swaps the element with end and
750    * decreases size by one.  This is much faster than Erase so use
751    * this in case order does not matter. Does not change capacity.
752    *
753    * @SINCE_1_0.0
754    * @param[in] iterator Iterator pointing to the item to remove
755    * @pre Iterator \e iterator must be in the vector's range ( Vector::Begin(), Vector::End() - 1 ).
756    *
757    */
758   void Remove( Iterator iterator )
759   {
760     DALI_ASSERT_VECTOR( (iterator < End()) && (iterator >= Begin()) && "Iterator not inside vector" );
761
762     Iterator last = End() - 1u;
763     if( last > iterator )
764     {
765       std::swap( *iterator, *last );
766     }
767     VectorBase::SetCount( VectorBase::Count() - 1u );
768   }
769
770   /**
771    * @brief Swaps the contents of two vectors.
772    *
773    * @SINCE_1_0.0
774    * @param[in] vector Vector to swap with
775    */
776   void Swap( Vector& vector )
777   {
778     VectorBase::Swap( vector );
779   }
780
781   /**
782    * @brief Clears the contents of the vector. Keeps its capacity.
783    * @SINCE_1_0.0
784    */
785   void Clear()
786   {
787     VectorAlgorithms<BaseType>::Clear();
788   }
789
790   /**
791    * @brief Releases the memory that the vector holds.
792    * @SINCE_1_0.0
793    */
794   void Release()
795   {
796     VectorAlgorithms<BaseType>::Release();
797   }
798 };
799
800 /**
801  * @}
802  */
803 } // namespace Dali
804
805 #endif /* __DALI_VECTOR_H__ */