Commit 1dcceaf5 authored by Petr Lapukhov's avatar Petr Lapukhov Committed by Facebook Github Bot

add insert() method for dynamic::array

Summary: We have insert() API for underlying object, but not the array. With array, insert() has same semantic as in std::vector, shifting elements to the right. To insert at arbitrary offset use something like `arr.insert(arr.begin() + 10, elem)`; This calls one of specializations of std::vector's insert() underneath.

Reviewed By: yfeldblum

Differential Revision: D10372068

fbshipit-source-id: 54bb7ea80b36bf1b893d88b82a11afa08ad0c0e2
parent e840c2d4
......@@ -850,11 +850,17 @@ inline std::size_t dynamic::count(StringPiece key) const {
}
template <class K, class V>
inline void dynamic::insert(K&& key, V&& val) {
inline dynamic::IfNotIterator<K, void> dynamic::insert(K&& key, V&& val) {
auto& obj = get<ObjectImpl>();
obj[std::forward<K>(key)] = std::forward<V>(val);
}
template <class T>
inline dynamic::iterator dynamic::insert(const_iterator pos, T&& value) {
auto& arr = get<Array>();
return arr.insert(pos, std::forward<T>(value));
}
inline void dynamic::update(const dynamic& mergeObj) {
if (!isObject() || !mergeObj.isObject()) {
throw_exception<TypeError>("object", type(), mergeObj.type());
......
......@@ -370,6 +370,10 @@ struct dynamic : private boost::operators<dynamic> {
std::is_convertible<K, dynamic>::value,
T>;
template <typename K, typename T>
using IfNotIterator =
std::enable_if_t<!std::is_convertible<K, iterator>::value, T>;
public:
/*
* You can iterate over the keys, values, or items (std::pair of key and
......@@ -553,7 +557,16 @@ struct dynamic : private boost::operators<dynamic> {
* Invalidates iterators.
*/
template <class K, class V>
void insert(K&&, V&& val);
IfNotIterator<K, void> insert(K&&, V&& val);
/*
* Inserts the supplied value into array, or throw if not array
* Shifts existing values in the array to the right
*
* Invalidates iterators.
*/
template <class T>
iterator insert(const_iterator pos, T&& value);
/*
* These functions merge two folly dynamic objects.
......
......@@ -175,6 +175,27 @@ TEST(Dynamic, ObjectBasics) {
EXPECT_EQ(mergeObj1, combinedPreferObj1);
}
TEST(Dynamic, ArrayInsertErase) {
auto arr = dynamic::array(1, 2, 3, 4, 5, 6);
arr.erase(arr.begin() + 3);
EXPECT_EQ(5, arr[3].asInt());
arr.insert(arr.begin() + 3, 4);
EXPECT_EQ(4, arr[3].asInt());
EXPECT_EQ(5, arr[4].asInt());
auto x = dynamic::array(55, 66);
arr.insert(arr.begin() + 4, std::move(x));
EXPECT_EQ(55, arr[4][0].asInt());
EXPECT_EQ(66, arr[4][1].asInt());
EXPECT_EQ(5, arr[5].asInt());
dynamic obj = dynamic::object;
obj.insert(3, 4);
EXPECT_EQ(4, obj[3].asInt());
}
namespace {
struct StaticStrings {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment