5 * Copyright (c) 2021 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.
25 #include <cstdint> // uint32_t
28 #include <dali/public-api/common/dali-common.h>
29 #include <dali/public-api/common/type-traits.h>
30 #include <dali/public-api/math/math-utils.h>
32 #define DALI_ASSERT_VECTOR(cond) DALI_ASSERT_ALWAYS(cond)
37 * @addtogroup dali_core_common
42 * @brief Base class to handle the memory of simple vector.
44 * Memory layout is such that it has two std::size_t to hold the count
45 * and capacity of the vector. VectorBase::mData is adjusted so that it points to the
46 * beginning of the first real item so that iterating the items is quick.
49 class DALI_CORE_API VectorBase
52 using SizeType = std::size_t;
54 protected: // Construction
56 * @brief Default constructor. Does not allocate space.
64 * Does not release the space. Derived class needs to call Release.
65 * Not virtual as this should not be called directly and we do not want
66 * a vtable for this class as it would unnecessarily increase size.
73 * @brief This method is inlined as it's needed frequently for Vector::End() iterator.
76 * @return The count of elements in this vector
78 SizeType Count() const
83 SizeType* metadata = reinterpret_cast<SizeType*>(mData);
84 items = *(metadata - 1u);
90 * @brief Gets the count of elements in this vector.
92 * @return The count of elements in this vector
100 * @brief @ return if the vector is empty.
102 * @return True if the count of elements is empty
106 return Count() == 0u;
110 * @brief Gets the capacity of this vector.
112 * @return The capacity of this vector
114 SizeType Capacity() const;
117 * @brief Releases the data.
119 * Does not call destructors on objects held.
124 protected: // for Derived classes
126 * @brief Helper to set the count.
129 * @param[in] count Number of elements in the vector
131 void SetCount(SizeType count);
134 * @brief Reserves space in the vector.
137 * @param[in] count Count of elements to reserve
138 * @param[in] elementSize Size of a single element
140 void Reserve(SizeType count, SizeType elementSize);
143 * @brief Copy a vector.
146 * @param[in] vector Vector to copy from
147 * @param[in] elementSize Size of a single element
149 void Copy(const VectorBase& vector, SizeType elementSize);
152 * @brief Swaps the contents of two vectors.
155 * @param[in] vector Vector to swap with
157 void Swap(VectorBase& vector);
160 * @brief Erases an element.
162 * Does not change capacity.
164 * @param[in] address Address to erase from
165 * @param[in] elementSize Size to erase
166 * @pre Last element cannot be erased as there is nothing to move.
168 void Erase(char* address, SizeType elementSize);
171 * @brief Erases a range of elements.
173 * Does not change capacity.
175 * @param[in] first Address to the first element to be erased
176 * @param[in] last Address to the last element to be erased
177 * @param[in] elementSize Size of one of the elements to be erased
178 * @return Address pointing to the next element of the last one
180 char* Erase(char* first, char* last, SizeType elementSize);
183 * @brief Copies a number of bytes from \e source to \e destination.
185 * \e source and \e destination must not overlap.
188 * @param[in] destination Pointer to the destination address
189 * @param[in] source Pointer to the source address
190 * @param[in] numberOfBytes The number of bytes to be copied
192 void CopyMemory(char* destination, const char* source, size_t numberOfBytes);
195 // not copyable as it does not know the size of elements
196 VectorBase(const VectorBase&) = delete; ///< Deleted copy constructor. @SINCE_1_0.0
197 VectorBase& operator=(const VectorBase&) = delete; ///< Deleted copy assignment operator. @SINCE_1_0.0
199 // not movable as this is handled by deriving classes
200 VectorBase(VectorBase&&) = delete; ///< Deleted move constructor. @SINCE_1_9.25
201 VectorBase& operator=(VectorBase&&) = delete; ///< Deleted copy assignment operator. @SINCE_1_9.25
204 void* mData; ///< Pointer to the data.
209 * @brief Vector algorithm variant for trivial types.
211 * Trivial types do not need destructor or copy constructor called.
214 template<bool IsTrivial>
215 class VectorAlgorithms : public VectorBase
217 protected: // API for deriving classes
218 using SizeType = VectorBase::SizeType;
221 * @brief Empty constructor.
224 VectorAlgorithms() = default;
227 * @brief Empty destructor.
230 ~VectorAlgorithms() = default;
233 * @brief Copy vector contents.
236 * @param[in] rhs VectorBase object to copy from
237 * @param[in] elementSize Size of the content
239 void Copy(const VectorBase& rhs, SizeType elementSize)
241 if(rhs.Capacity() > 0u)
243 VectorBase::Copy(rhs, elementSize);
247 VectorBase::Release();
252 * @brief Reserves space in the vector.
255 * @param[in] count Count of elements to reserve
256 * @param[in] elementSize Size of a single element
258 void Reserve(SizeType count, SizeType elementSize)
260 VectorBase::Reserve(count, elementSize);
264 * @brief Resizes the vector. Does not change capacity.
267 * @param[in] count Count to resize to
268 * @param[in] elementSize Size of a single element
270 void Resize(SizeType count, SizeType elementSize)
272 // reserve will copy old elements as well
273 Reserve(count, elementSize);
277 * @brief Clears the contents.
279 * For simple types, nothing to do.
286 VectorBase::SetCount(0u);
291 * @brief Releases the vector.
296 VectorBase::Release();
300 * @brief Erases an element. Does not change capacity.
303 * @param[in] address Address to erase from
304 * @param[in] elementSize Size to erase
306 void Erase(uint8_t* address, SizeType elementSize)
308 VectorBase::Erase(reinterpret_cast<char*>(address), elementSize);
312 * @brief Erases a range of elements. Does not change capacity.
315 * @param[in] first Address to the first element to be erased
316 * @param[in] last Address to the last element to be erased
317 * @param[in] elementSize Size of one of the elements to be erased
318 * @return Address pointing to the next element of the last one
320 uint8_t* Erase(uint8_t* first, uint8_t* last, SizeType elementSize)
322 return reinterpret_cast<uint8_t*>(VectorBase::Erase(reinterpret_cast<char*>(first), reinterpret_cast<char*>(last), elementSize));
326 * @brief Inserts the given elements into the vector.
329 * @param[in] at Address where to insert the elements into the vector
330 * @param[in] from Address to the first element to be inserted
331 * @param[in] to Address to the last element to be inserted
332 * @param[in] elementSize Size of one of the elements to be inserted
334 void Insert(uint8_t* at, uint8_t* from, uint8_t* to, SizeType elementSize)
336 const SizeType size = to - from;
337 const SizeType count = Count();
338 const SizeType newCount = count + size / elementSize;
340 if(newCount > Capacity())
342 // Calculate the at offset as the pointer is invalid after the Reserve() call.
343 std::size_t offset = at - reinterpret_cast<uint8_t*>(mData);
346 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.
348 // Set the new at pointer.
349 at = reinterpret_cast<uint8_t*>(mData) + offset;
351 // set new count first as otherwise the debug assert will hit us
354 // Move current items to a new position inside the vector.
355 CopyMemory(reinterpret_cast<char*>(at + size),
356 reinterpret_cast<const char*>(at),
357 (reinterpret_cast<uint8_t*>(mData) + count * elementSize) - at);
359 // Copy the given items.
360 CopyMemory(reinterpret_cast<char*>(at), reinterpret_cast<const char*>(from), size);
367 * @brief Vector algorithm variant for complex types.
369 * Not yet supported so will lead to compile error
370 * as constructor and destructor are private.
371 * TODO add support for this variant.
375 class VectorAlgorithms<false> : public VectorBase
378 VectorAlgorithms() = default;
379 ~VectorAlgorithms() = default;
384 * @brief Vector class with minimum space allocation when it's empty.
387 * @param type The type of the data that the vector holds
389 template<class T, bool IsTrivialType = TypeTraits<T>::IS_TRIVIAL_TYPE == true>
390 class Vector : public VectorAlgorithms<IsTrivialType>
394 * @brief Type definitions.
397 using SizeType = VectorBase::SizeType; ///< Size type @SINCE_1_0.0
398 using Iterator = T*; ///< Most simple Iterator is a pointer @SINCE_1_0.0
399 using ConstIterator = const T*; ///< Const iterator @SINCE_1_0.0
400 using ItemType = T; ///< Item type @SINCE_1_0.0
403 * @brief Enumeration for BaseType.
408 BaseType = IsTrivialType ///< @SINCE_1_0.0
412 * @brief Default constructor. Does not allocate any space.
418 * @brief Destructor. Releases the allocated space.
427 * @brief Copy constructor.
430 * @param[in] vector Vector to copy from
432 Vector(const Vector& vector)
434 // reuse copy assignment
439 * @brief Default move constructor.
442 * @param[in] vector Vector to move
444 Vector(Vector&& vector)
446 // reuse move assignment
447 operator=(std::move(vector));
451 * @brief Assignment operator.
454 * @param[in] vector Vector to assign from
455 * @return Reference to self for chaining
457 Vector& operator=(const Vector& vector)
461 VectorAlgorithms<BaseType>::Copy(vector, sizeof(ItemType));
467 * @brief Default move assignment operator.
470 * @param[in] vector Vector to move
472 Vector& operator=(Vector&& vector)
476 if(VectorBase::mData)
480 VectorBase::mData = vector.mData;
481 vector.mData = nullptr;
487 * @brief Iterator to the beginning of the data.
489 * @return Iterator to the beginning of the data
491 Iterator Begin() const
493 ItemType* address = reinterpret_cast<ItemType*>(VectorBase::mData);
498 * @brief Iterator to the end of the data (one past last element).
500 * @return Iterator to the end of the data (one past last element)
504 ItemType* address = reinterpret_cast<ItemType*>(VectorBase::mData);
505 address += VectorBase::Count();
510 * Support for C++11 Range-based for loop: for( item : container ).
512 * @return The start iterator
514 Iterator begin() const
520 * Support for C++11 Range-based for loop: for( item : container ).
522 * @return The end iterator
530 * @brief Subscript operator.
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.
536 ItemType& operator[](SizeType index)
538 // reuse the const version
539 return const_cast<ItemType&>(const_cast<const Vector<ItemType>&>(*this)[index]);
543 * @brief Subscript operator.
545 * @param[in] index Index of the element
546 * @return Reference to the element for given index
547 * @pre Index must be in the vector's range.
549 const ItemType& operator[](SizeType index) const
551 DALI_ASSERT_VECTOR(VectorBase::mData && "Vector is empty");
552 assert(index < VectorBase::Count());
554 ItemType* address = reinterpret_cast<ItemType*>(VectorBase::mData);
560 * @brief Pushes back an element to the vector.
562 * The underlying storage may be reallocated to provide space.
563 * If this occurs, all pre-existing pointers into the vector will
567 * @param[in] element Element to be added
569 void PushBack(const ItemType& element)
571 const SizeType count = VectorBase::Count();
572 const SizeType newCount = count + 1u;
573 const SizeType capacity = VectorBase::Capacity();
574 if(newCount > capacity)
577 Reserve(newCount << 1u); // reserve double the current count
579 // set new count first as otherwise the debug assert will hit us
580 VectorBase::SetCount(newCount);
581 operator[](count) = element;
585 * @brief Inserts an element to the vector.
587 * Elements after \e at are moved one position to the right.
589 * The underlying storage may be reallocated to provide space.
590 * If this occurs, all pre-existing pointers into the vector will
594 * @param[in] at Iterator where to insert the elements into the vector
595 * @param[in] element An element to be added
596 * @pre Iterator at must be in the vector's range ( Vector::Begin(), Vector::End() ).
598 void Insert(Iterator at, const ItemType& element)
600 DALI_ASSERT_VECTOR((at <= End()) && (at >= Begin()) && "Iterator not inside vector");
601 const SizeType size = sizeof(ItemType);
602 uint8_t* address = const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(&element));
603 VectorAlgorithms<BaseType>::Insert(reinterpret_cast<uint8_t*>(at),
610 * @brief Inserts the given elements into the vector.
612 * Elements after \e at are moved the number of given elements positions to the right.
614 * The underlying storage may be reallocated to provide space.
615 * If this occurs, all pre-existing pointers into the vector will
619 * @param[in] at Iterator where to insert the elements into the vector
620 * @param[in] from Iterator to the first element to be inserted
621 * @param[in] to Iterator to the last element to be inserted
622 * @pre Iterator \e at must be in the vector's range ( Vector::Begin(), Vector::End() ).
623 * @pre Iterators \e from and \e to must be valid iterators.
624 * @pre Iterator \e from must not be grater than Iterator \e to.
627 void Insert(Iterator at, Iterator from, Iterator to)
629 DALI_ASSERT_VECTOR((at <= End()) && (at >= Begin()) && "Iterator not inside vector");
630 DALI_ASSERT_VECTOR((from <= to) && "from address can't be greater than to");
638 VectorAlgorithms<BaseType>::Insert(reinterpret_cast<uint8_t*>(at),
639 reinterpret_cast<uint8_t*>(from),
640 reinterpret_cast<uint8_t*>(to),
645 * @brief Reserves space in the vector.
647 * Reserving less than current Capacity is a no-op.
649 * @param[in] count Count of elements to reserve
651 void Reserve(SizeType count)
653 VectorAlgorithms<BaseType>::Reserve(count, sizeof(ItemType));
657 * @brief Resizes the vector. Does not change capacity.
660 * @param[in] count Count to resize to
662 void Resize(SizeType count)
664 ItemType item = ItemType();
669 * @brief Resizes the vector without initializing the data.
671 * Can be used as a data container for reading whole file content.
673 * @param[in] count Count to resize to
675 void ResizeUninitialized(SizeType count)
678 VectorBase::SetCount(count);
682 * @brief Resizes the vector. Does not change capacity.
685 * @param[in] count Count to resize to
686 * @param[in] item An item to insert to the new indices
688 void Resize(SizeType count, const ItemType& item)
690 const SizeType oldCount = VectorBase::Count();
691 if(count <= oldCount)
693 // getting smaller so just set count
694 VectorBase::SetCount(count);
698 // remember how many new items get added
699 SizeType newItems = count - oldCount;
701 for(; newItems > 0u; --newItems)
709 * @brief Erases an element.
711 * Does not change capacity. Other elements get moved.
714 * @param[in] iterator Iterator pointing to the item to remove
715 * @return Iterator pointing to next element
716 * @pre Iterator \e iterator must be within the vector's range ( Vector::Begin(), Vector::End() - 1 ).
719 Iterator Erase(Iterator iterator)
721 DALI_ASSERT_VECTOR((iterator < End()) && (iterator >= Begin()) && "Iterator not inside vector");
722 if(iterator < (End() - 1u))
724 VectorAlgorithms<BaseType>::Erase(reinterpret_cast<uint8_t*>(iterator), sizeof(ItemType));
728 // just remove the element
735 * @brief Erases a range of elements.
737 * Does not change capacity. Other elements get moved.
740 * @param[in] first Iterator to the first element to be erased
741 * @param[in] last Iterator to the last element to be erased
743 * @return Iterator pointing to the next element of the last one
744 * @pre Iterator \e first must be in the vector's range ( Vector::Begin(), Vector::End() ).
745 * @pre Iterator \e last must be in the vector's range ( Vector::Begin(), Vector::End() ).
746 * @pre Iterator \e first must not be grater than Iterator \e last.
749 Iterator Erase(Iterator first, Iterator last)
751 DALI_ASSERT_VECTOR((first <= End()) && (first >= Begin()) && "Iterator not inside vector");
752 DALI_ASSERT_VECTOR((last <= End()) && (last >= Begin()) && "Iterator not inside vector");
753 DALI_ASSERT_VECTOR((first <= last) && "first iterator greater than last");
755 Iterator nextElement;
759 // Erase up to the end.
760 VectorBase::SetCount(VectorBase::Count() - (last - first));
765 nextElement = reinterpret_cast<Iterator>(VectorAlgorithms<BaseType>::Erase(reinterpret_cast<uint8_t*>(first),
766 reinterpret_cast<uint8_t*>(last),
774 * @brief Removes an element.
776 * Does not maintain order. Swaps the element with end and
777 * decreases size by one. This is much faster than Erase so use
778 * this in case order does not matter. Does not change capacity.
781 * @param[in] iterator Iterator pointing to the item to remove
782 * @pre Iterator \e iterator must be in the vector's range ( Vector::Begin(), Vector::End() - 1 ).
785 void Remove(Iterator iterator)
787 DALI_ASSERT_VECTOR((iterator < End()) && (iterator >= Begin()) && "Iterator not inside vector");
789 Iterator last = End() - 1u;
792 std::swap(*iterator, *last);
794 VectorBase::SetCount(VectorBase::Count() - 1u);
798 * @brief Swaps the contents of two vectors.
801 * @param[in] vector Vector to swap with
803 void Swap(Vector& vector)
805 VectorBase::Swap(vector);
809 * @brief Clears the contents of the vector. Keeps its capacity.
814 VectorAlgorithms<BaseType>::Clear();
818 * @brief Releases the memory that the vector holds.
823 VectorAlgorithms<BaseType>::Release();
828 * @brief Erases all elements that compare equal to value from the vector.
831 * @param[in] vector The vector
832 * @param[in] value The value to be removed.
834 template<class T, class U>
835 inline void Erase(Dali::Vector<T>& vector, const U& value)
837 auto begin = vector.Begin();
838 auto end = vector.End();
840 vector.Erase(std::remove(begin, end, value), end);
844 * @brief Erases all elements that satisfy the predicate from the vector.
847 * @param[in] vector The vector
848 * @param[in] predicate The predicate
850 template<class T, class Predicate>
851 inline void EraseIf(Dali::Vector<T>& vector, Predicate predicate)
853 auto begin = vector.Begin();
854 auto end = vector.End();
856 vector.Erase(std::remove_if(begin, end, predicate), end);
864 #endif // DALI_VECTOR_H