DynamicArray.h 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #ifndef _DYNAMIC_BUFFER_H_
  2. #define _DYNAMIC_BUFFER_H_
  3. #include <cstring>
  4. namespace EmbeddedProto
  5. {
  6. //! Class template that specifies the interface of an arry with the data type.
  7. template<class DATA_TYPE>
  8. class DynamicArray
  9. {
  10. public:
  11. DynamicArray() = default;
  12. virtual ~DynamicArray() = default;
  13. //! Obtain the total number of bytes currently stored in the array.
  14. virtual uint32_t get_size() const = 0;
  15. //! Obtain the maximum number of bytes which can at most be stored in the array.
  16. virtual uint32_t get_max_size() const = 0;
  17. //! Obtain the total number of DATA_TYPE items in the array.
  18. virtual uint32_t get_length() const = 0;
  19. //! Obtain the maximum number of DATA_TYPE items which can at most be stored in the array.
  20. virtual uint32_t get_max_length() const = 0;
  21. //! Get a pointer to the first element in the array.
  22. virtual DATA_TYPE* get_data() = 0;
  23. //! Get the value at the given index.
  24. /*!
  25. \param[in] index The desired index to return.
  26. \return The value at the given index. If index is out of bound zero is returned.
  27. */
  28. virtual DATA_TYPE operator[](uint32_t index) = 0;
  29. //! Given a different array of known length copy that data into this object.
  30. /*!
  31. \param[in] data A pointer the array to copy from.
  32. \param[in] length The number of value of DATA_TYPE in the array.
  33. \return True when copying the data succedded. (Could be false if it does not fit.)
  34. */
  35. virtual bool set_data(const DATA_TYPE* data, const uint32_t length) = 0;
  36. };
  37. //! A template class that actually holds some data.
  38. /*!
  39. This is a seperate class to make it possible to not have the size defined in every function or
  40. class using this type of object.
  41. */
  42. template<class DATA_TYPE, uint32_t MAX_SIZE>
  43. class DynamicArraySize : DynamicArray<DATA_TYPE>
  44. {
  45. public:
  46. DynamicArraySize()
  47. : current_size_(0)
  48. {
  49. }
  50. uint32_t get_size() const override { return current_size_; }
  51. uint32_t get_max_size() const override { return MAX_SIZE; }
  52. DATA_TYPE* get_data() { return data_; }
  53. bool set_data(const DATA_TYPE* data, const uint32_t length) override
  54. {
  55. uint32_t size = length * sizeof(DATA_TYPE);
  56. bool result = MAX_SIZE >= size;
  57. if(result)
  58. {
  59. current_size_ = size;
  60. memcpy(data_, data, size);
  61. }
  62. return result;
  63. }
  64. private:
  65. //! Number of item in the data array.
  66. uint32_t current_size_;
  67. //! The actual data
  68. DATA_TYPE data_[MAX_SIZE];
  69. };
  70. } // End of namespace EmbeddedProto
  71. #endif // End of _DYNAMIC_BUFFER_H_