5 * Copyright (c) 2024 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 constexpr static uint32_t SHRINK_REQUIRED_RATIO = 4; ///< The ratio of auto shrink to fit calling. @SINCE_2_3.22
69 protected: // Construction
71 * @brief Default constructor. Does not allocate space.
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.
88 * @brief This method is inlined as it's needed frequently for Vector::End() iterator.
91 * @return The count of elements in this vector
93 SizeType Count() const
98 SizeType* metadata = reinterpret_cast<SizeType*>(mData);
99 items = *(metadata - 1u);
105 * @brief Gets the count of elements in this vector.
107 * @return The count of elements in this vector
109 SizeType Size() const
115 * @brief @ return if the vector is empty.
117 * @return True if the count of elements is empty
121 return Count() == 0u;
125 * @brief Gets the capacity of this vector.
127 * @return The capacity of this vector
129 SizeType Capacity() const;
132 * @brief Releases the data.
134 * Does not call destructors on objects held.
139 protected: // for Derived classes
141 * @brief Helper to set the count.
144 * @param[in] count Number of elements in the vector
146 void SetCount(SizeType count);
149 * @brief Reserves space in the vector.
152 * @param[in] count Count of elements to reserve
153 * @param[in] elementSize Size of a single element
155 void Reserve(SizeType count, SizeType elementSize);
158 * @brief Copy a vector.
161 * @param[in] vector Vector to copy from
162 * @param[in] elementSize Size of a single element
164 void Copy(const VectorBase& vector, SizeType elementSize);
167 * @brief Swaps the contents of two vectors.
170 * @param[in] vector Vector to swap with
172 void Swap(VectorBase& vector);
175 * @brief Erases an element.
177 * Does not change capacity.
179 * @param[in] address Address to erase from
180 * @param[in] elementSize Size to erase
181 * @pre Last element cannot be erased as there is nothing to move.
183 void Erase(char* address, SizeType elementSize);
186 * @brief Erases a range of elements.
188 * Does not change capacity.
190 * @param[in] first Address to the first element to be erased
191 * @param[in] last Address to the last element to be erased
192 * @param[in] elementSize Size of one of the elements to be erased
193 * @return Address pointing to the next element of the last one
195 char* Erase(char* first, char* last, SizeType elementSize);
198 * @brief Copies a number of bytes from \e source to \e destination.
200 * \e source and \e destination must not overlap.
203 * @param[in] destination Pointer to the destination address
204 * @param[in] source Pointer to the source address
205 * @param[in] numberOfBytes The number of bytes to be copied
207 void CopyMemory(char* destination, const char* source, size_t numberOfBytes);
210 * @brief Replace the data as new data address.
211 * After replace, release the old data.
213 * It will be used when we want to keep the mData integrity.
215 * Does not call destructors on objects held.
216 * @param[in] newData new data address to be replaced
218 void Replace(void* newData) noexcept;
221 * @brief Fit the capacity of vector as item counts.
222 * It will be used when we want to remove unused memory.
225 * @param[in] elementSize Size of a single element
227 void ShrinkToFit(SizeType elementSize);
230 // not copyable as it does not know the size of elements
231 VectorBase(const VectorBase&) = delete; ///< Deleted copy constructor. @SINCE_1_0.0
232 VectorBase& operator=(const VectorBase&) = delete; ///< Deleted copy assignment operator. @SINCE_1_0.0
234 // not movable as this is handled by deriving classes
235 VectorBase(VectorBase&&) = delete; ///< Deleted move constructor. @SINCE_1_9.25
236 VectorBase& operator=(VectorBase&&) = delete; ///< Deleted copy assignment operator. @SINCE_1_9.25
239 void* mData; ///< Pointer to the data.
244 * @brief Vector algorithm variant for trivial types.
246 * Trivial types do not need destructor or copy constructor called.
249 template<bool IsTrivial>
250 class VectorAlgorithms : public VectorBase
252 protected: // API for deriving classes
253 using SizeType = VectorBase::SizeType;
256 * @brief Empty constructor.
259 VectorAlgorithms() = default;
262 * @brief Empty destructor.
265 ~VectorAlgorithms() = default;
268 * @brief Copy vector contents.
271 * @param[in] rhs VectorBase object to copy from
272 * @param[in] elementSize Size of the content
274 void Copy(const VectorBase& rhs, SizeType elementSize)
276 if(rhs.Capacity() > 0u)
278 VectorBase::Copy(rhs, elementSize);
282 VectorBase::Release();
287 * @brief Reserves space in the vector.
290 * @param[in] count Count of elements to reserve
291 * @param[in] elementSize Size of a single element
293 void Reserve(SizeType count, SizeType elementSize)
295 VectorBase::Reserve(count, elementSize);
299 * @brief Resizes the vector. Does not change capacity.
302 * @param[in] count Count to resize to
303 * @param[in] elementSize Size of a single element
305 void Resize(SizeType count, SizeType elementSize)
307 // reserve will copy old elements as well
308 Reserve(count, elementSize);
312 * @brief Clears the contents.
314 * For simple types, nothing to do.
321 VectorBase::SetCount(0u);
326 * @brief Releases the vector.
331 VectorBase::Release();
335 * @brief Erases an element. Does not change capacity.
338 * @param[in] address Address to erase from
339 * @param[in] elementSize Size to erase
341 void Erase(uint8_t* address, SizeType elementSize)
343 VectorBase::Erase(reinterpret_cast<char*>(address), elementSize);
347 * @brief Erases a range of elements. Does not change capacity.
350 * @param[in] first Address to the first element to be erased
351 * @param[in] last Address to the last element to be erased
352 * @param[in] elementSize Size of one of the elements to be erased
353 * @return Address pointing to the next element of the last one
355 uint8_t* Erase(uint8_t* first, uint8_t* last, SizeType elementSize)
357 return reinterpret_cast<uint8_t*>(VectorBase::Erase(reinterpret_cast<char*>(first), reinterpret_cast<char*>(last), elementSize));
361 * @brief Inserts the given elements into the vector.
364 * @param[in] at Address where to insert the elements into the vector
365 * @param[in] from Address to the first element to be inserted
366 * @param[in] to Address to the last element to be inserted
367 * @param[in] elementSize Size of one of the elements to be inserted
369 void Insert(uint8_t* at, uint8_t* from, uint8_t* to, SizeType elementSize)
371 const SizeType size = to - from;
372 const SizeType count = Count();
373 const SizeType newCount = count + size / elementSize;
375 if(newCount > Capacity())
377 // Calculate the at offset as the pointer is invalid after the Reserve() call.
378 std::size_t offset = at - reinterpret_cast<uint8_t*>(mData);
381 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.
383 // Set the new at pointer.
384 at = reinterpret_cast<uint8_t*>(mData) + offset;
386 // set new count first as otherwise the debug assert will hit us
389 // Move current items to a new position inside the vector.
390 CopyMemory(reinterpret_cast<char*>(at + size),
391 reinterpret_cast<const char*>(at),
392 (reinterpret_cast<uint8_t*>(mData) + count * elementSize) - at);
394 // Copy the given items.
395 CopyMemory(reinterpret_cast<char*>(at), reinterpret_cast<const char*>(from), size);
402 * @brief Vector algorithm variant for complex types.
404 * Not yet supported so will lead to compile error
405 * as constructor and destructor are private.
406 * TODO add support for this variant.
410 class VectorAlgorithms<false> : public VectorBase
413 VectorAlgorithms() = default;
414 ~VectorAlgorithms() = default;
419 * @brief Vector class with minimum space allocation when it's empty.
422 * @param type The type of the data that the vector holds
424 template<class T, bool IsTrivialType = TypeTraits<T>::IS_TRIVIAL_TYPE == true>
425 class Vector : public VectorAlgorithms<IsTrivialType>
429 * @brief Type definitions.
432 using SizeType = VectorBase::SizeType; ///< Size type @SINCE_1_0.0
433 using Iterator = T*; ///< Most simple Iterator is a pointer @SINCE_1_0.0
434 using ConstIterator = const T*; ///< Const iterator @SINCE_1_0.0
435 using ItemType = T; ///< Item type @SINCE_1_0.0
438 * @brief Enumeration for BaseType.
443 BaseType = IsTrivialType ///< @SINCE_1_0.0
447 * @brief Default constructor. Does not allocate any space.
453 * @brief Create vector with count, without initialize value.
456 * @param[in] count The count of vector.
458 Vector(SizeType count)
460 ResizeUninitialized(count);
464 * @brief Destructor. Releases the allocated space.
473 * @brief Copy constructor.
476 * @param[in] vector Vector to copy from
478 Vector(const Vector& vector)
480 // reuse copy assignment
485 * @brief Default move constructor.
488 * @param[in] vector Vector to move
490 Vector(Vector&& vector) noexcept
492 // reuse move assignment
493 operator=(std::move(vector));
497 * @brief Assignment operator.
500 * @param[in] vector Vector to assign from
501 * @return Reference to self for chaining
503 Vector& operator=(const Vector& vector)
507 VectorAlgorithms<BaseType>::Copy(vector, sizeof(ItemType));
513 * @brief Default move assignment operator.
516 * @param[in] vector Vector to move
518 Vector& operator=(Vector&& vector) noexcept
522 VectorAlgorithms<BaseType>::Replace(vector.mData);
523 vector.mData = nullptr;
529 * @brief Iterator to the beginning of the data.
531 * @return Iterator to the beginning of the data
533 Iterator Begin() const
535 ItemType* address = reinterpret_cast<ItemType*>(VectorBase::mData);
540 * @brief Iterator to the end of the data (one past last element).
542 * @return Iterator to the end of the data (one past last element)
546 ItemType* address = reinterpret_cast<ItemType*>(VectorBase::mData);
547 address += VectorBase::Count();
552 * Support for C++11 Range-based for loop: for( item : container ).
554 * @return The start iterator
556 Iterator begin() const
562 * Support for C++11 Range-based for loop: for( item : container ).
564 * @return The end iterator
572 * @brief Subscript operator.
574 * @param[in] index Index of the element
575 * @return Reference to the element for given index
576 * @pre Index must be in the vector's range.
578 ItemType& operator[](SizeType index)
580 // reuse the const version
581 return const_cast<ItemType&>(const_cast<const Vector<ItemType>&>(*this)[index]);
585 * @brief Subscript operator.
587 * @param[in] index Index of the element
588 * @return Reference to the element for given index
589 * @pre Index must be in the vector's range.
591 const ItemType& operator[](SizeType index) const
593 DALI_ASSERT_VECTOR(VectorBase::mData && "Vector is empty");
594 DALI_ASSERT_VECTOR(index < VectorBase::Count() && "Index out of bounds");
595 ItemType* address = reinterpret_cast<ItemType*>(VectorBase::mData);
601 * @brief Pushes back an element to the vector.
603 * The underlying storage may be reallocated to provide space.
604 * If this occurs, all pre-existing pointers into the vector will
608 * @param[in] element Element to be added
610 void PushBack(const ItemType& element)
612 const SizeType count = VectorBase::Count();
613 const SizeType newCount = count + 1u;
614 const SizeType capacity = VectorBase::Capacity();
615 if(newCount > capacity)
618 Reserve(newCount << 1u); // reserve double the current count
620 // set new count first as otherwise the debug assert will hit us
621 VectorBase::SetCount(newCount);
622 operator[](count) = element;
626 * @brief Inserts an element to the vector.
628 * Elements after \e at are moved one position to the right.
630 * The underlying storage may be reallocated to provide space.
631 * If this occurs, all pre-existing pointers into the vector will
635 * @param[in] at Iterator where to insert the elements into the vector
636 * @param[in] element An element to be added
637 * @pre Iterator at must be in the vector's range ( Vector::Begin(), Vector::End() ).
639 void Insert(Iterator at, const ItemType& element)
641 DALI_ASSERT_VECTOR((at <= End()) && (at >= Begin()) && "Iterator not inside vector");
642 const SizeType size = sizeof(ItemType);
643 uint8_t* address = const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(&element));
644 VectorAlgorithms<BaseType>::Insert(reinterpret_cast<uint8_t*>(at),
651 * @brief Inserts the given elements into the vector.
653 * Elements after \e at are moved the number of given elements positions to the right.
655 * The underlying storage may be reallocated to provide space.
656 * If this occurs, all pre-existing pointers into the vector will
660 * @param[in] at Iterator where to insert the elements into the vector
661 * @param[in] from Iterator to the first element to be inserted
662 * @param[in] to Iterator to the last element to be inserted
663 * @pre Iterator \e at must be in the vector's range ( Vector::Begin(), Vector::End() ).
664 * @pre Iterators \e from and \e to must be valid iterators.
665 * @pre Iterator \e from must not be grater than Iterator \e to.
668 void Insert(Iterator at, Iterator from, Iterator to)
670 DALI_ASSERT_VECTOR((at <= End()) && (at >= Begin()) && "Iterator not inside vector");
671 DALI_ASSERT_VECTOR((from <= to) && "from address can't be greater than to");
679 VectorAlgorithms<BaseType>::Insert(reinterpret_cast<uint8_t*>(at),
680 reinterpret_cast<uint8_t*>(from),
681 reinterpret_cast<uint8_t*>(to),
686 * @brief Reserves space in the vector.
688 * Reserving less than current Capacity is a no-op.
690 * @param[in] count Count of elements to reserve
692 void Reserve(SizeType count)
694 VectorAlgorithms<BaseType>::Reserve(count, sizeof(ItemType));
698 * @brief Resizes the vector. Does not change capacity.
701 * @param[in] count Count to resize to
703 void Resize(SizeType count)
705 ItemType item = ItemType();
710 * @brief Resizes the vector without initializing the data.
712 * Can be used as a data container for reading whole file content.
714 * @param[in] count Count to resize to
716 void ResizeUninitialized(SizeType count)
719 VectorBase::SetCount(count);
723 * @brief Resizes the vector. Does not change capacity.
726 * @param[in] count Count to resize to
727 * @param[in] item An item to insert to the new indices
729 void Resize(SizeType count, const ItemType& item)
731 const SizeType oldCount = VectorBase::Count();
732 if(count <= oldCount)
734 // getting smaller so just set count
735 VectorBase::SetCount(count);
739 // remember how many new items get added
740 SizeType newItems = count - oldCount;
742 for(; newItems > 0u; --newItems)
750 * @brief Erases an element.
752 * Does not change capacity. Other elements get moved.
755 * @param[in] iterator Iterator pointing to the item to remove
756 * @return Iterator pointing to next element
757 * @pre Iterator \e iterator must be within the vector's range ( Vector::Begin(), Vector::End() - 1 ).
760 Iterator Erase(Iterator iterator)
762 DALI_ASSERT_VECTOR((iterator < End()) && (iterator >= Begin()) && "Iterator not inside vector");
763 if(iterator < (End() - 1u))
765 VectorAlgorithms<BaseType>::Erase(reinterpret_cast<uint8_t*>(iterator), sizeof(ItemType));
769 // just remove the element
776 * @brief Erases a range of elements.
778 * Does not change capacity. Other elements get moved.
781 * @param[in] first Iterator to the first element to be erased
782 * @param[in] last Iterator to the last element to be erased
784 * @return Iterator pointing to the next element of the last one
785 * @pre Iterator \e first must be in the vector's range ( Vector::Begin(), Vector::End() ).
786 * @pre Iterator \e last must be in the vector's range ( Vector::Begin(), Vector::End() ).
787 * @pre Iterator \e first must not be grater than Iterator \e last.
790 Iterator Erase(Iterator first, Iterator last)
792 DALI_ASSERT_VECTOR((first <= End()) && (first >= Begin()) && "Iterator not inside vector");
793 DALI_ASSERT_VECTOR((last <= End()) && (last >= Begin()) && "Iterator not inside vector");
794 DALI_ASSERT_VECTOR((first <= last) && "first iterator greater than last");
796 Iterator nextElement;
800 // Erase up to the end.
801 VectorBase::SetCount(VectorBase::Count() - (last - first));
806 nextElement = reinterpret_cast<Iterator>(VectorAlgorithms<BaseType>::Erase(reinterpret_cast<uint8_t*>(first),
807 reinterpret_cast<uint8_t*>(last),
815 * @brief Removes an element.
817 * Does not maintain order. Swaps the element with end and
818 * decreases size by one. This is much faster than Erase so use
819 * this in case order does not matter. Does not change capacity.
822 * @param[in] iterator Iterator pointing to the item to remove
823 * @pre Iterator \e iterator must be in the vector's range ( Vector::Begin(), Vector::End() - 1 ).
826 void Remove(Iterator iterator)
828 DALI_ASSERT_VECTOR((iterator < End()) && (iterator >= Begin()) && "Iterator not inside vector");
830 Iterator last = End() - 1u;
833 std::swap(*iterator, *last);
835 VectorBase::SetCount(VectorBase::Count() - 1u);
839 * @brief Swaps the contents of two vectors.
842 * @param[in] vector Vector to swap with
844 void Swap(Vector& vector)
846 VectorBase::Swap(vector);
850 * @brief Clears the contents of the vector. Keeps its capacity.
855 VectorAlgorithms<BaseType>::Clear();
859 * @brief Releases the memory that the vector holds.
864 VectorAlgorithms<BaseType>::Release();
868 * @brief Fit the capacity of vector as item counts.
874 VectorBase::ShrinkToFit(sizeof(ItemType));
878 * @brief Fit the capacity of vector as item counts
879 * only if low spec memory management enabled, and the count is much smaller than capacity.
880 * It will be used when we want to remove unused memory.
884 void ShrinkToFitIfNeeded()
886 // Run ShrinkToFit only if VectorBase::Capacity() is bigger than the smallest malloc block size.
887 if(DALI_UNLIKELY(VectorBase::Count() * VectorBase::SHRINK_REQUIRED_RATIO < VectorBase::Capacity()))
889 VectorBase::ShrinkToFit(sizeof(ItemType));
895 * @brief Erases all elements that compare equal to value from the vector.
898 * @param[in] vector The vector
899 * @param[in] value The value to be removed.
901 template<class T, class U>
902 inline void Erase(Dali::Vector<T>& vector, const U& value)
904 auto begin = vector.Begin();
905 auto end = vector.End();
907 vector.Erase(std::remove(begin, end, value), end);
911 * @brief Erases all elements that satisfy the predicate from the vector.
914 * @param[in] vector The vector
915 * @param[in] predicate The predicate
917 template<class T, class Predicate>
918 inline void EraseIf(Dali::Vector<T>& vector, Predicate predicate)
920 auto begin = vector.Begin();
921 auto end = vector.End();
923 vector.Erase(std::remove_if(begin, end, predicate), end);
931 #endif // DALI_VECTOR_H