Skip to content

Commit f768e93

Browse files
authored
build: refactor json.h out of include from discordevents.h (#926)
1 parent 545e7ff commit f768e93

File tree

2 files changed

+21
-9
lines changed

2 files changed

+21
-9
lines changed

include/dpp/discordevents.h

+12-9
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@
2222

2323
#include <dpp/export.h>
2424
#include <dpp/json_fwd.h>
25-
#include <dpp/json.h>
2625
#include <dpp/json_interface.h>
2726

2827
namespace dpp {
@@ -48,21 +47,25 @@ void DPP_EXPORT set_snowflake_not_null(const nlohmann::json* j, const char *keyn
4847
*/
4948
void DPP_EXPORT set_snowflake_array_not_null(const nlohmann::json* j, const char *keyname, std::vector<class snowflake> &v);
5049

50+
/**
51+
* @brief Applies a function to each element of a json array.
52+
* @param j nlohmann::json instance to retrieve value from
53+
* @param key key name to check for the values
54+
* @param fn function to apply to each element
55+
*/
56+
void DPP_EXPORT for_each_json(nlohmann::json* parent, std::string_view key, std::function<void(const nlohmann::json*)> fn);
57+
5158
/** @brief Sets an array of objects from a json field value, if defined, else does nothing
5259
* @tparam T The class of which the array consists of. Must be derived from dpp::json_interface
5360
* @param j nlohmann::json instance to retrieve value from
5461
* @param keyname key name to check for the values
5562
* @param v Value to change
5663
*/
57-
template<class T> std::enable_if_t<std::is_base_of_v<json_interface<T>, T>, void> set_object_array_not_null(nlohmann::json* j, const char *keyname, std::vector<T> &v) {
64+
template<class T> void set_object_array_not_null(nlohmann::json* j, std::string_view key, std::vector<T>& v) {
5865
v.clear();
59-
auto k = j->find(keyname);
60-
if (k != j->end() && !k->is_null()) {
61-
v.reserve(j->at(keyname).size());
62-
for (auto &obj : j->at(keyname)) {
63-
v.emplace_back(T().fill_from_json(&obj));
64-
}
65-
}
66+
for_each_json(j, key, [&v](nlohmann::json* elem) {
67+
v.push_back(T{}.fill_from_json(elem));
68+
});
6669
}
6770

6871
/** @brief Returns a string from a json field value, if defined, else returns an empty string.

src/dpp/discordevents.cpp

+9
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,15 @@ void set_snowflake_array_not_null(const json* j, const char *keyname, std::vecto
100100
}
101101
}
102102

103+
void for_each_json(const nlohmann::json* parent, const char* key, std::function<void(const nlohmann::json*)> fn) {
104+
auto it = parent->find(key);
105+
if (it == parent->end() || it->is_null()) {
106+
return;
107+
}
108+
for (const nlohmann::json &elem : *parent) {
109+
fn(&elem);
110+
}
111+
}
103112

104113
std::string string_not_null(const json* j, const char *keyname) {
105114
/* Returns empty string if the value is not a string, or is null or not defined */

0 commit comments

Comments
 (0)