5 * Copyright (c) 2020 Samsung Electronics Co., Ltd.
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
24 #include <cstdint> // uint32_t
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>
32 * @brief For DALi internal use, asserts are enabled in debug builds.
34 * For Application use, asserts can be enabled manually.
37 #if defined(DEBUG_ENABLED)
38 #define ENABLE_VECTOR_ASSERTS
41 #if defined(ENABLE_VECTOR_ASSERTS)
42 #define DALI_ASSERT_VECTOR(cond) DALI_ASSERT_ALWAYS(cond)
44 #define DALI_ASSERT_VECTOR(cond)
50 * @addtogroup dali_core_common
55 * @brief Base class to handle the memory of simple vector.
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.
62 class DALI_CORE_API VectorBase
65 using SizeType = std::size_t;
67 protected: // Construction
69 * @brief Default constructor. Does not allocate space.
77 * Does not release the space. Derived class needs to call Release.
78 * Not virtual as this should not be called directly and we do not want
79 * a vtable for this class as it would unnecessarily increase size.
86 * @brief This method is inlined as it's needed frequently for Vector::End() iterator.
89 * @return The count of elements in this vector
91 SizeType Count() const
96 SizeType* metadata = reinterpret_cast<SizeType*>(mData);
97 items = *(metadata - 1u);
103 * @brief Gets the count of elements in this vector.
105 * @return The count of elements in this vector
107 SizeType Size() const
113 * @brief @ return if the vector is empty.
115 * @return True if the count of elements is empty
119 return Count() == 0u;
123 * @brief Gets the capacity of this vector.
125 * @return The capacity of this vector
127 SizeType Capacity() const;
130 * @brief Releases the data.
132 * Does not call destructors on objects held.
137 protected: // for Derived classes
139 * @brief Helper to set the count.
142 * @param[in] count Number of elements in the vector
144 void SetCount(SizeType count);
147 * @brief Reserves space in the vector.
150 * @param[in] count Count of elements to reserve
151 * @param[in] elementSize Size of a single element
153 void Reserve(SizeType count, SizeType elementSize);
156 * @brief Copy a vector.
159 * @param[in] vector Vector to copy from
160 * @param[in] elementSize Size of a single element
162 void Copy(const VectorBase& vector, SizeType elementSize);
165 * @brief Swaps the contents of two vectors.
168 * @param[in] vector Vector to swap with
170 void Swap(VectorBase& vector);
173 * @brief Erases an element.
175 * Does not change capacity.
177 * @param[in] address Address to erase from
178 * @param[in] elementSize Size to erase
179 * @pre Last element cannot be erased as there is nothing to move.
181 void Erase(char* address, SizeType elementSize);
184 * @brief Erases a range of elements.
186 * Does not change capacity.
188 * @param[in] first Address to the first element to be erased
189 * @param[in] last Address to the last element to be erased
190 * @param[in] elementSize Size of one of the elements to be erased
191 * @return Address pointing to the next element of the last one
193 char* Erase(char* first, char* last, SizeType elementSize);
196 * @brief Copies a number of bytes from \e source to \e destination.
198 * \e source and \e destination must not overlap.
201 * @param[in] destination Pointer to the destination address
202 * @param[in] source Pointer to the source address
203 * @param[in] numberOfBytes The number of bytes to be copied
205 void CopyMemory(char* destination, const char* source, size_t numberOfBytes);
208 // not copyable as it does not know the size of elements
209 VectorBase(const VectorBase&) = delete; ///< Deleted copy constructor. @SINCE_1_0.0
210 VectorBase& operator=(const VectorBase&) = delete; ///< Deleted copy assignment operator. @SINCE_1_0.0
212 // not movable as this is handled by deriving classes
213 VectorBase(VectorBase&&) = delete; ///< Deleted move constructor. @SINCE_1_9.25
214 VectorBase& operator=(VectorBase&&) = delete; ///< Deleted copy assignment operator. @SINCE_1_9.25
217 void* mData; ///< Pointer to the data.
222 * @brief Vector algorithm variant for trivial types.
224 * Trivial types do not need destructor or copy constructor called.
227 template<bool IsTrivial>
228 class VectorAlgorithms : public VectorBase
230 protected: // API for deriving classes
231 using SizeType = VectorBase::SizeType;
234 * @brief Empty constructor.
242 * @brief Empty destructor.
250 * @brief Copy vector contents.
253 * @param[in] rhs VectorBase object to copy from
254 * @param[in] elementSize Size of the content
256 void Copy(const VectorBase& rhs, SizeType elementSize)
258 if(rhs.Capacity() > 0u)
260 VectorBase::Copy(rhs, elementSize);
264 VectorBase::Release();
269 * @brief Reserves space in the vector.
272 * @param[in] count Count of elements to reserve
273 * @param[in] elementSize Size of a single element
275 void Reserve(SizeType count, SizeType elementSize)
277 VectorBase::Reserve(count, elementSize);
281 * @brief Resizes the vector. Does not change capacity.
284 * @param[in] count Count to resize to
285 * @param[in] elementSize Size of a single element
287 void Resize(SizeType count, SizeType elementSize)
289 // reserve will copy old elements as well
290 Reserve(count, elementSize);
294 * @brief Clears the contents.
296 * For simple types, nothing to do.
303 VectorBase::SetCount(0u);
308 * @brief Releases the vector.
313 VectorBase::Release();
317 * @brief Erases an element. Does not change capacity.
320 * @param[in] address Address to erase from
321 * @param[in] elementSize Size to erase
323 void Erase(uint8_t* address, SizeType elementSize)
325 VectorBase::Erase(reinterpret_cast<char*>(address), elementSize);
329 * @brief Erases a range of elements. Does not change capacity.
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
337 uint8_t* Erase(uint8_t* first, uint8_t* last, SizeType elementSize)
339 return reinterpret_cast<uint8_t*>(VectorBase::Erase(reinterpret_cast<char*>(first), reinterpret_cast<char*>(last), elementSize));
343 * @brief Inserts the given elements into the vector.
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
351 void Insert(uint8_t* at, uint8_t* from, uint8_t* to, SizeType elementSize)
353 const SizeType size = to - from;
354 const SizeType count = Count();
355 const SizeType newCount = count + size / elementSize;
357 if(newCount > Capacity())
359 // Calculate the at offset as the pointer is invalid after the Reserve() call.
360 std::size_t offset = at - reinterpret_cast<uint8_t*>(mData);
363 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 // Set the new at pointer.
366 at = reinterpret_cast<uint8_t*>(mData) + offset;
368 // set new count first as otherwise the debug assert will hit us
371 // Move current items to a new position inside the vector.
372 CopyMemory(reinterpret_cast<char*>(at + size),
373 reinterpret_cast<const char*>(at),
374 (reinterpret_cast<uint8_t*>(mData) + count * elementSize) - at);
376 // Copy the given items.
377 CopyMemory(reinterpret_cast<char*>(at), reinterpret_cast<const char*>(from), size);
384 * @brief Vector algorithm variant for complex types.
386 * Not yet supported so will lead to compile error
387 * as constructor and destructor are private.
388 * TODO add support for this variant.
392 class VectorAlgorithms<false> : public VectorBase
405 * @brief Vector class with minimum space allocation when it's empty.
408 * @param type The type of the data that the vector holds
410 template<class T, bool IsTrivialType = TypeTraits<T>::IS_TRIVIAL_TYPE == true>
411 class Vector : public VectorAlgorithms<IsTrivialType>
415 * @brief Type definitions.
418 using SizeType = VectorBase::SizeType; ///< Size type @SINCE_1_0.0
419 using Iterator = T*; ///< Most simple Iterator is a pointer @SINCE_1_0.0
420 using ConstIterator = const T*; ///< Const iterator @SINCE_1_0.0
421 using ItemType = T; ///< Item type @SINCE_1_0.0
424 * @brief Enumeration for BaseType.
429 BaseType = IsTrivialType ///< @SINCE_1_0.0
433 * @brief Default constructor. Does not allocate any space.
441 * @brief Destructor. Releases the allocated space.
450 * @brief Copy constructor.
453 * @param[in] vector Vector to copy from
455 Vector(const Vector& vector)
457 // reuse copy assignment
462 * @brief Default move constructor.
465 * @param[in] vector Vector to move
467 Vector(Vector&& vector)
469 // reuse move assignment
470 operator=(std::move(vector));
474 * @brief Assignment operator.
477 * @param[in] vector Vector to assign from
478 * @return Reference to self for chaining
480 Vector& operator=(const Vector& vector)
484 VectorAlgorithms<BaseType>::Copy(vector, sizeof(ItemType));
490 * @brief Default move assignment operator.
493 * @param[in] vector Vector to move
495 Vector& operator=(Vector&& vector)
499 if(VectorBase::mData)
503 VectorBase::mData = vector.mData;
504 vector.mData = nullptr;
510 * @brief Iterator to the beginning of the data.
512 * @return Iterator to the beginning of the data
514 Iterator Begin() const
516 ItemType* address = reinterpret_cast<ItemType*>(VectorBase::mData);
521 * @brief Iterator to the end of the data (one past last element).
523 * @return Iterator to the end of the data (one past last element)
527 ItemType* address = reinterpret_cast<ItemType*>(VectorBase::mData);
528 address += VectorBase::Count();
533 * Support for C++11 Range-based for loop: for( item : container ).
535 * @return The start iterator
537 Iterator begin() const
543 * Support for C++11 Range-based for loop: for( item : container ).
545 * @return The end iterator
553 * @brief Subscript operator.
555 * @param[in] index Index of the element
556 * @return Reference to the element for given index
557 * @pre Index must be in the vector's range.
559 ItemType& operator[](SizeType index)
561 // reuse the const version
562 return const_cast<ItemType&>(const_cast<const Vector<ItemType>&>(*this)[index]);
566 * @brief Subscript operator.
568 * @param[in] index Index of the element
569 * @return Reference to the element for given index
570 * @pre Index must be in the vector's range.
572 const ItemType& operator[](SizeType index) const
574 DALI_ASSERT_VECTOR(VectorBase::mData && "Vector is empty");
575 DALI_ASSERT_VECTOR(index < VectorBase::Count() && "Index out of bounds");
576 ItemType* address = reinterpret_cast<ItemType*>(VectorBase::mData);
582 * @brief Pushes back an element to the vector.
584 * The underlying storage may be reallocated to provide space.
585 * If this occurs, all pre-existing pointers into the vector will
589 * @param[in] element Element to be added
591 void PushBack(const ItemType& element)
593 const SizeType count = VectorBase::Count();
594 const SizeType newCount = count + 1u;
595 const SizeType capacity = VectorBase::Capacity();
596 if(newCount > capacity)
599 Reserve(newCount << 1u); // reserve double the current count
601 // set new count first as otherwise the debug assert will hit us
602 VectorBase::SetCount(newCount);
603 operator[](count) = element;
607 * @brief Inserts an element to the vector.
609 * Elements after \e at are moved one position to the right.
611 * The underlying storage may be reallocated to provide space.
612 * If this occurs, all pre-existing pointers into the vector will
616 * @param[in] at Iterator where to insert the elements into the vector
617 * @param[in] element An element to be added
618 * @pre Iterator at must be in the vector's range ( Vector::Begin(), Vector::End() ).
620 void Insert(Iterator at, const ItemType& element)
622 DALI_ASSERT_VECTOR((at <= End()) && (at >= Begin()) && "Iterator not inside vector");
623 const SizeType size = sizeof(ItemType);
624 uint8_t* address = const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(&element));
625 VectorAlgorithms<BaseType>::Insert(reinterpret_cast<uint8_t*>(at),
632 * @brief Inserts the given elements into the vector.
634 * Elements after \e at are moved the number of given elements positions to the right.
636 * The underlying storage may be reallocated to provide space.
637 * If this occurs, all pre-existing pointers into the vector will
641 * @param[in] at Iterator where to insert the elements into the vector
642 * @param[in] from Iterator to the first element to be inserted
643 * @param[in] to Iterator to the last element to be inserted
644 * @pre Iterator \e at must be in the vector's range ( Vector::Begin(), Vector::End() ).
645 * @pre Iterators \e from and \e to must be valid iterators.
646 * @pre Iterator \e from must not be grater than Iterator \e to.
649 void Insert(Iterator at, Iterator from, Iterator to)
651 DALI_ASSERT_VECTOR((at <= End()) && (at >= Begin()) && "Iterator not inside vector");
652 DALI_ASSERT_VECTOR((from <= to) && "from address can't be greater than to");
660 VectorAlgorithms<BaseType>::Insert(reinterpret_cast<uint8_t*>(at),
661 reinterpret_cast<uint8_t*>(from),
662 reinterpret_cast<uint8_t*>(to),
667 * @brief Reserves space in the vector.
669 * Reserving less than current Capacity is a no-op.
671 * @param[in] count Count of elements to reserve
673 void Reserve(SizeType count)
675 VectorAlgorithms<BaseType>::Reserve(count, sizeof(ItemType));
679 * @brief Resizes the vector. Does not change capacity.
682 * @param[in] count Count to resize to
684 void Resize(SizeType count)
686 ItemType item = ItemType();
691 * @brief Resizes the vector without initializing the data.
693 * Can be used as a data container for reading whole file content.
695 * @param[in] count Count to resize to
697 void ResizeUninitialized(SizeType count)
700 VectorBase::SetCount(count);
704 * @brief Resizes the vector. Does not change capacity.
707 * @param[in] count Count to resize to
708 * @param[in] item An item to insert to the new indices
710 void Resize(SizeType count, const ItemType& item)
712 const SizeType oldCount = VectorBase::Count();
713 if(count <= oldCount)
715 // getting smaller so just set count
716 VectorBase::SetCount(count);
720 // remember how many new items get added
721 SizeType newItems = count - oldCount;
723 for(; newItems > 0u; --newItems)
731 * @brief Erases an element.
733 * Does not change capacity. Other elements get moved.
736 * @param[in] iterator Iterator pointing to the item to remove
737 * @return Iterator pointing to next element
738 * @pre Iterator \e iterator must be within the vector's range ( Vector::Begin(), Vector::End() - 1 ).
741 Iterator Erase(Iterator iterator)
743 DALI_ASSERT_VECTOR((iterator < End()) && (iterator >= Begin()) && "Iterator not inside vector");
744 if(iterator < (End() - 1u))
746 VectorAlgorithms<BaseType>::Erase(reinterpret_cast<uint8_t*>(iterator), sizeof(ItemType));
750 // just remove the element
757 * @brief Erases a range of elements.
759 * Does not change capacity. Other elements get moved.
762 * @param[in] first Iterator to the first element to be erased
763 * @param[in] last Iterator to the last element to be erased
765 * @return Iterator pointing to the next element of the last one
766 * @pre Iterator \e first must be in the vector's range ( Vector::Begin(), Vector::End() ).
767 * @pre Iterator \e last must be in the vector's range ( Vector::Begin(), Vector::End() ).
768 * @pre Iterator \e first must not be grater than Iterator \e last.
771 Iterator Erase(Iterator first, Iterator last)
773 DALI_ASSERT_VECTOR((first <= End()) && (first >= Begin()) && "Iterator not inside vector");
774 DALI_ASSERT_VECTOR((last <= End()) && (last >= Begin()) && "Iterator not inside vector");
775 DALI_ASSERT_VECTOR((first <= last) && "first iterator greater than last");
777 Iterator nextElement;
781 // Erase up to the end.
782 VectorBase::SetCount(VectorBase::Count() - (last - first));
787 nextElement = reinterpret_cast<Iterator>(VectorAlgorithms<BaseType>::Erase(reinterpret_cast<uint8_t*>(first),
788 reinterpret_cast<uint8_t*>(last),
796 * @brief Removes an element.
798 * Does not maintain order. Swaps the element with end and
799 * decreases size by one. This is much faster than Erase so use
800 * this in case order does not matter. Does not change capacity.
803 * @param[in] iterator Iterator pointing to the item to remove
804 * @pre Iterator \e iterator must be in the vector's range ( Vector::Begin(), Vector::End() - 1 ).
807 void Remove(Iterator iterator)
809 DALI_ASSERT_VECTOR((iterator < End()) && (iterator >= Begin()) && "Iterator not inside vector");
811 Iterator last = End() - 1u;
814 std::swap(*iterator, *last);
816 VectorBase::SetCount(VectorBase::Count() - 1u);
820 * @brief Swaps the contents of two vectors.
823 * @param[in] vector Vector to swap with
825 void Swap(Vector& vector)
827 VectorBase::Swap(vector);
831 * @brief Clears the contents of the vector. Keeps its capacity.
836 VectorAlgorithms<BaseType>::Clear();
840 * @brief Releases the memory that the vector holds.
845 VectorAlgorithms<BaseType>::Release();
850 * @brief Erases all elements that compare equal to value from the vector.
853 * @param[in] vector The vector
854 * @param[in] value The value to be removed.
856 template <class T, class U>
857 inline void Erase(Dali::Vector<T>& vector, const U& value)
859 auto begin = vector.Begin();
860 auto end = vector.End();
862 vector.Erase(std::remove(begin, end, value), end);
866 * @brief Erases all elements that satisfy the predicate from the vector.
869 * @param[in] vector The vector
870 * @param[in] predicate The predicate
872 template <class T, class Predicate>
873 inline void EraseIf(Dali::Vector<T>& vector, Predicate predicate)
875 auto begin = vector.Begin();
876 auto end = vector.End();
878 vector.Erase(std::remove_if(begin, end, predicate), end);
886 #endif // DALI_VECTOR_H