toml icon indicating copy to clipboard operation
toml copied to clipboard

Generic Value parsing

Open unicorn-madness13 opened this issue 1 year ago • 7 comments

For context, I am writing a command line application that provides configuration support via a TOML file. Much like how Git provides the config command to set config values, my app will do the same. I am wondering what the best way is to parse user input to a valid toml::Value (for example, if the user provides "true" it should be parsed to Value::Boolean(true)).

What I ended up doing is something along these lines:

fn parse(val: &str) -> toml::Value {
    let i64_val: Result<i64, _> = val.parse();
    if i64_val.is_ok() {
        return toml::Value::try_from(i64_val.unwrap()).unwrap();
    }
    
    let f64_val: Result<f64, _> = val.parse();
    if f64_val.is_ok() {
        return toml::Value::try_from(f64_val.unwrap()).unwrap();
    }
    
    let bool_val: Result<bool, _> = val.parse();
    if bool_val.is_ok() {
        return toml::Value::try_from(bool_val.unwrap()).unwrap();
    }
    
    toml::Value::try_from(val).unwrap()
}

which seems rather hacky, imo. I was hoping that this method would be available on the enum already, but it does not appear to be.

Would it be possible implement a method similar to this on the Value enum? I imagine it would return a Result instead of the actual instance, but it would be a nice convenience method.

Having skimmed the value.rs file, it looks rather easy to add but that might just be my naivety.

unicorn-madness13 avatar Jun 20 '23 15:06 unicorn-madness13