Skip to content

Commit

Permalink
Avoid calling from_json directly
Browse files Browse the repository at this point in the history
This lets us drop some of our own custom deserialization logic which
existed because we clearly weren't using this library correctly.
  • Loading branch information
falconindy committed Sep 9, 2024
1 parent 03241d6 commit eea1701
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 29 deletions.
32 changes: 9 additions & 23 deletions src/aur/json_internal.hh
Original file line number Diff line number Diff line change
Expand Up @@ -9,33 +9,15 @@
namespace aur {

void from_json(const nlohmann::json& j, Package& p);
void from_json(const nlohmann::json& j, absl::Time& t);

template <typename T>
void from_json(const nlohmann::json& j, T& v) {
if (j.is_null()) {
return;
}

v = T(j);
}

template <typename T>
void from_json(const nlohmann::json& j, std::vector<T>& v) {
if (j.is_null()) {
return;
}

v = std::vector<T>(j.cbegin(), j.cend());
}

template <typename OutputType>
using ValueCallback = std::function<void(const nlohmann::json&, OutputType&)>;

template <typename OutputType, typename FieldType>
ValueCallback<OutputType> MakeValueCallback(FieldType OutputType::*field) {
return
[=](const nlohmann::json& j, OutputType& o) { from_json(j, o.*field); };
return [=](const nlohmann::json& j, OutputType& o) {
j.get_to<FieldType>(o.*field);
};
}

template <typename OutputType>
Expand All @@ -47,8 +29,12 @@ void DeserializeJsonObject(const nlohmann::json& j,
const CallbackMap<OutputType>& callbacks,
OutputType& o) {
for (const auto& [key, value] : j.items()) {
const auto iter = callbacks.find(key);
if (iter != callbacks.end()) {
// Skip all null-valued entries.
if (value.is_null()) {
continue;
}

if (const auto iter = callbacks.find(key); iter != callbacks.end()) {
iter->second(value, o);
}
}
Expand Down
12 changes: 6 additions & 6 deletions src/aur/package.cc
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,16 @@
#include "absl/base/no_destructor.h"
#include "aur/json_internal.hh"

namespace aur {

void from_json(const nlohmann::json& j, absl::Time& t) {
if (j.is_null()) {
return;
}
namespace absl {

void from_json(const nlohmann::json& j, Time& t) {
t = absl::FromUnixSeconds(j);
}

} // namespace absl

namespace aur {

void from_json(const nlohmann::json& j, Package& p) {
// clang-format off
static const absl::NoDestructor<CallbackMap<Package>> kCallbacks({
Expand Down

0 comments on commit eea1701

Please sign in to comment.