Yaml node.size() returns 0

Viewed 33

I've been experimenting with serialization and to get the hang of it I made a simple Test. I first call a function to Serialize my custom Color struct (a simple struct having the == operator and floats for r, g, b, and alpha values), this works, I can look into the file on my computer and the values are there:

    YAML::Emitter out;

    out << YAML::BeginSeq;
    out << "Material";
    out << YAML::BeginMap;
    out << YAML::Key << "color";
    out << YAML::Value << material.color;
    out << YAML::EndMap;
    out << YAML::EndSeq;

    std::ofstream fout("assets/SerializationTest/Test.mat");
    fout << out.c_str();

I have the overload operator<< for my Color struct that looks like this:

YAML::Emitter& operator<<(YAML::Emitter& out, const Color& col) {

    out << YAML::Flow;
    out << YAML::BeginSeq << col.r << col.g << col.b << col.a << YAML::EndSeq;
    return out;
    
}

and the convert struct that looks like this:

template<>
struct convert<Copper::Color> {

    static Node encode(const Copper::Color& col) {

        Node node;
        node.push_back(col.r);
        node.push_back(col.g);
        node.push_back(col.b);
        node.push_back(col.a);

        return node;
        
    }

    static bool decode(const Node& node, Copper::Color& col) {
        
        if(!node.IsSequence() || node.size() != 4) return false;

        col.r = node[0].as<float>();
        col.g = node[1].as<float>();
        col.b = node[2].as<float>();
        col.a = node[3].as<float>();
        return true;
        
    }
    
};

Then I try to Load the File like this:

YAML::Node data = YAML::LoadFile("assets/SerializationTest/Test.mat");
Color col = data["color"].as<Color>();

But for some reason there is an error, I've figured out that in the decode function node.size() returns 0, I tracked the issue down and found out that it was caused because the variable m_isDefined from the file node_data.cpp is false. I tried to look this issue up but everywhere I looked it was either a completely different case or the questions wasn't even related to this. Any Ideas why this might be happening ?

1 Answers

Your code constructs the following YAML:

- Material
- color: [1, 2, 3, 4] # don't know the actual values

You can't do data["color"] on this structure because the root node is a sequence. Do

data[1]["color"]

instead.

Related