Skip to content

Commit 9795eab

Browse files
authored
Merge pull request #722 from jmr1/vector_reserve
vector::reserve() implemented
2 parents c36f051 + da05ba9 commit 9795eab

File tree

2 files changed

+38
-2
lines changed

2 files changed

+38
-2
lines changed

include/boost/compute/container/vector.hpp

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -435,8 +435,27 @@ class vector
435435

436436
void reserve(size_type size, command_queue &queue)
437437
{
438-
(void) size;
439-
(void) queue;
438+
if(size > max_size()){
439+
throw std::length_error("vector::reserve");
440+
}
441+
if(capacity() < size){
442+
// allocate new buffer
443+
pointer new_data =
444+
m_allocator.allocate(
445+
static_cast<size_type>(
446+
static_cast<float>(size) * _growth_factor()
447+
)
448+
);
449+
450+
// copy old values to the new buffer
451+
::boost::compute::copy(m_data, m_data + m_size, new_data, queue);
452+
453+
// free old memory
454+
m_allocator.deallocate(m_data, m_size);
455+
456+
// set new data
457+
m_data = new_data;
458+
}
440459
}
441460

442461
void reserve(size_type size)

test/test_vector.cpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,23 @@ BOOST_AUTO_TEST_CASE(resize)
6262
BOOST_CHECK_EQUAL(int_vector.size(), size_t(5));
6363
}
6464

65+
BOOST_AUTO_TEST_CASE(reserve)
66+
{
67+
const float growth_factor = 1.5f;
68+
69+
bc::vector<int> int_vector(10, context);
70+
BOOST_CHECK_EQUAL(int_vector.size(), size_t(10));
71+
BOOST_CHECK_EQUAL(int_vector.capacity(), size_t(10));
72+
73+
int_vector.reserve(20, queue);
74+
BOOST_CHECK_EQUAL(int_vector.size(), size_t(10));
75+
BOOST_CHECK_EQUAL(int_vector.capacity(), size_t(20 * growth_factor));
76+
77+
int_vector.reserve(5, queue);
78+
BOOST_CHECK_EQUAL(int_vector.size(), size_t(10));
79+
BOOST_CHECK_EQUAL(int_vector.capacity(), size_t(20 * growth_factor));
80+
}
81+
6582
BOOST_AUTO_TEST_CASE(array_operator)
6683
{
6784
bc::vector<int> vector(10, context);

0 commit comments

Comments
 (0)