Skip to content

Commit

Permalink
parse_into clears sequences before filling them
Browse files Browse the repository at this point in the history
  • Loading branch information
grisumbras committed Oct 9, 2023
1 parent f144f38 commit 75981e7
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 7 deletions.
8 changes: 8 additions & 0 deletions example/parse_into.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,10 @@ struct options

iterator
end();

void
clear()
{ }
};

struct coordinate
Expand Down Expand Up @@ -112,6 +116,10 @@ struct accumulator

iterator
end() { return nullptr; }

void
clear()
{ }
};

struct coordinates2
Expand Down
38 changes: 31 additions & 7 deletions include/boost/json/detail/parse_into.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -502,6 +502,32 @@ std::true_type check_inserter( It1, It2 )
return {};
}

template<class T>
void
clear_container(
T&,
mp11::mp_int<2>)
{
}

template<class T>
void
clear_container(
T& target,
mp11::mp_int<1>)
{
target.clear();
}

template<class T>
void
clear_container(
T& target,
mp11::mp_int<0>)
{
target.clear();
}

template< class V, class P >
class converting_handler<sequence_conversion_tag, V, P>
: public composite_handler<
Expand Down Expand Up @@ -553,14 +579,11 @@ class converting_handler<sequence_conversion_tag, V, P>
bool on_array_begin( error_code& ec )
{
if( this->inner_active_ )
{
return this->inner_.on_array_begin( ec );
}
else
{
this->inner_active_ = true;
return true;
}

this->inner_active_ = true;
clear_container( *value_, inserter_implementation<V>() );
return true;
}

bool on_array_end( error_code& ec )
Expand Down Expand Up @@ -605,6 +628,7 @@ class converting_handler<map_like_conversion_tag, V, P>
if( this->inner_active_ )
return this->inner_.on_object_begin(ec);

clear_container( *value_, inserter_implementation<V>() );
return true;
}

Expand Down
14 changes: 14 additions & 0 deletions test/parse_into.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,13 @@ class parse_into_test
error::size_mismatch, {1, 2, 3} );

testParseInto< std::vector<std::array<int, 4>> >( {arr,arr,arr} );

std::vector<int> v;
parse_into(v, "[1,2,3,4]");
BOOST_TEST( v.size() == 4 );

parse_into(v, "[5,6,7]");
BOOST_TEST( v.size() == 3 );
}

void testMap()
Expand All @@ -272,6 +279,13 @@ class parse_into_test
error::not_object, { "1", 1, "2", 2} );
testParseIntoErrors< std::map<std::string, std::map<std::string, int>> >(
error::not_object, { {"1", {}}, {"2", {"3", 4}} } );

std::map<std::string, int> m;
parse_into(m, R"( {"1": 1, "2": 2, "3": 3} )");
BOOST_TEST( m.size() == 3 );

parse_into(m, R"( {"4": 4, "5": 5} )");
BOOST_TEST( m.size() == 2 );
}

void testTuple()
Expand Down

0 comments on commit 75981e7

Please sign in to comment.