Hi all,
To start off with the context. I am writing a fuzzy-importer that lets me import .toml files from disk into a given struct whilst allowing fields to be missing (or for extra fields to be present).
Since I don't want to implement a fuzzy function for each struct by hand, I thought I'd try my hand at using a macro to automagically derive the function.
As the base format, I am using toml::Table as an intermediary since it retains all the data, whilst not requiring me to specify a struct when loading in a file.
To read in the keys I am using the toml::Table.get() function which returns a Value type.
The issue is that each type has it's own fetch method.
e.g. .as_bool()
, .as_integer()
, .as_str()
and .as_float()
Which brings me to the question.
Since I'm using the syn crate, I theoretically have all the information about the struct necessary to assign the proper conversion method to each type.
The problem is that I don't know how to get that information out of the syn::Type type.
Long story short, I would like a struct like this:
struct MyStruct {
my_int: i32,
my_str: String,
my_other_struct: OtherStruct
}
struct OtherStruct {
str_1: String,
str_2: String
}
To generate the following reading code:
impl ReadTable for MyStruct {
fn read_data(table: toml::Table) -> Self {
Self {
my_int: table.get("my_int").unwrap_or_default().as_integer(),
my_str: table.get("my_str").unwrap_or_default().as_str().to_string(),
my_other_struct: OtherStruct::read_data(table.get("my_other_struct").unwrap()),
}
}
}
impl ReadTable for OtherStruct {
fn read_data(table: toml::Table) -> Self {
Self {
str_1: table.get("str_1").unwrap_or_default().as_str().to_string(),
str_2: table.get("str_2").unwrap_or_default().as_str().to_string(),
}
}
}
I should add that I have 90% of this code done, the only thing missing is how to distinguish which .as_x()
function I should use.
Thank you in advance for any suggestions!