stephenberry / glaze

Extremely fast, in memory, JSON and interface library for modern C++
MIT License
1.23k stars 123 forks source link

can't skip null on custom lambda #1410

Open JimjunZhang opened 3 weeks ago

JimjunZhang commented 3 weeks ago

Hello, I am using custom Lambda to output a field or skip based on a condition, but I found it can't skip the null.

sample code:

struct my_struct
{
    int i = 287;
    double d = 3.14;

};
template <>
struct glz::meta<my_struct> {
    using T = my_struct;
    static constexpr auto read_test = [](T& s, const std::string& input) {};
    static constexpr auto write_test =
        [](auto& s) ->std::unique_ptr<std::string> {
        if (287 != s.i)
            return std::make_unique<std::string>("expected: not 278");
        else
            return std::unique_ptr<std::string>();
        };
    static constexpr auto value = object(
        "i", & T::i,
        "d", & T::d,
        "test", glz::custom<read_test, write_test>
    );
};

Use it:

my_struct obj;
std::string buffer;
auto ec = glz::write < glz::opts{ .prettify = true } > (obj, buffer);

The output is: { "i": 287, "d": 3.14, "test": null } But I would expect the null can be skipped. Is it to add this feature for custom lambda? thanks!

stephenberry commented 3 weeks ago

Thanks for reporting this issue. Will look into it soon.

stephenberry commented 3 weeks ago

So, this will require a significant amount of compile time programming, because we need to deduce the type of the return of the custom function. If the type is nullable then we need to decode the value within the object reading code and determine if the value is null so that we can skip writing out keys.

Because this fix would affect object serialization code, I'm going to spend some time considering this issue and tackle it when I have a good amount of time to determine a flexible solution. So, I would expect it to be a while until this feature is added. But, thanks for bringing this up!