commit c8ff0d45255189901ef41775368c4d7ec4ffb298
parent 5f72a33625e084611a42a222cfb4729f591e50f8
Author: Morel BĂ©renger <berengermorel76@gmail.com>
Date: Mon, 30 Nov 2020 17:36:45 +0100
btl: adds vector::remain, ::real_size and ::append
Diffstat:
1 file changed, 32 insertions(+), 0 deletions(-)
diff --git a/btl/src/vector.hpp b/btl/src/vector.hpp
@@ -30,6 +30,14 @@
// is incomplete.
// Also, methods which are *not* in std::vector will be
// exposed in the end, to help handling memory.
+//
+// Bonus:
+// * vector::remains() returns the number of unused slots
+// * standalone "append" functions, which returning same
+// type as the underlying container's "push_back" method
+// * standalone "real_size" function, returning amount of
+// memory used by a container. Does *not* count dynamic
+// memory allocated by contained objects.
#ifndef VECTOR_HPP
#define VECTOR_HPP
@@ -107,6 +115,11 @@ public:
bool push_back( const T& value );
bool push_back( T&& value );
void pop_back( void );
+
+ // non-standard methods
+
+ // how much objects can still be stored before realloc
+ size_t remains( void ) const;
};
template <typename T>
@@ -414,6 +427,15 @@ void vector<T>::pop_back( void )
}
}
+// non-standard methods
+
+// how much objects can still be stored before realloc
+template <typename T>
+size_t vector<T>::remains( void ) const
+{
+ return capacity() - size();
+}
+
#else
#include <vector>
using std::vector;
@@ -453,6 +475,7 @@ auto append( C& dst, typename C::const_iterator src_start, typename C::const_ite
return false;
}
+// append a set to dst
template<typename C>
auto append( C& dst, C const& src )
-> decltype( std::declval<C>().push_back( typename C::value_type() ) )
@@ -468,4 +491,13 @@ auto append( C& dst, C const& src )
return false;
}
+// return the amount of memory used by current instance.
+// Obviously, it does not takes into account memory
+// allocated by contained objects.
+template <typename T>
+size_t real_size( vector<T> const& target )
+{
+ return sizeof( target ) + target.capacity() * sizeof( T );
+}
+
#endif