Skip to content

Commit 6c2a360

Browse files
committed
Implement vector::shrink_to_fit()
1 parent 766dc78 commit 6c2a360

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

include/boost/compute/container/vector.hpp

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -477,7 +477,22 @@ class vector
477477

478478
void shrink_to_fit(command_queue &queue)
479479
{
480-
(void) queue;
480+
pointer old_data = m_data;
481+
m_data = pointer(); // null pointer
482+
if(m_size > 0)
483+
{
484+
// allocate new buffer
485+
m_data = m_allocator.allocate(m_size);
486+
487+
// copy old values to the new buffer
488+
::boost::compute::copy(old_data, old_data + m_size, m_data, queue);
489+
}
490+
491+
if(capacity() > 0)
492+
{
493+
// free old memory
494+
m_allocator.deallocate(old_data, capacity());
495+
}
481496
}
482497

483498
void shrink_to_fit()

test/test_vector.cpp

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -472,4 +472,31 @@ BOOST_AUTO_TEST_CASE(swap_ctor_custom_alloc)
472472
CHECK_RANGE_EQUAL(int, 4, b, (11, 12, 13, 14));
473473
}
474474

475+
BOOST_AUTO_TEST_CASE(shrink_to_fit)
476+
{
477+
bc::vector<bc::int_> int_vector(5, context);
478+
BOOST_CHECK_EQUAL(int_vector.size(), 5);
479+
BOOST_CHECK(int_vector.capacity() >= 5);
480+
481+
int_vector.reserve(15);
482+
BOOST_CHECK_EQUAL(int_vector.size(), 5);
483+
BOOST_CHECK(int_vector.capacity() >= 15);
484+
485+
int_vector.shrink_to_fit();
486+
BOOST_CHECK_EQUAL(int_vector.size(), 5);
487+
BOOST_CHECK_EQUAL(int_vector.capacity(), 5);
488+
489+
int_vector.clear();
490+
BOOST_CHECK_EQUAL(int_vector.size(), 0);
491+
BOOST_CHECK_EQUAL(int_vector.capacity(), 5);
492+
493+
int_vector.shrink_to_fit();
494+
BOOST_CHECK_EQUAL(int_vector.size(), 0);
495+
BOOST_CHECK_EQUAL(int_vector.capacity(), 0);
496+
497+
int_vector.reserve(15);
498+
BOOST_CHECK_EQUAL(int_vector.size(), 0);
499+
BOOST_CHECK(int_vector.capacity() >= 15);
500+
}
501+
475502
BOOST_AUTO_TEST_SUITE_END()

0 commit comments

Comments
 (0)