arcnmx / serde-value

Serialization value trees
http://arcnmx.github.io/serde-value/serde_value/
MIT License
43 stars 30 forks source link

javascript style coerce_to_string or Into<string> #34

Open lizelive opened 3 years ago

lizelive commented 3 years ago
fn coerce_to_string(value: serde_value::Value) -> String {
    match value {
        serde_value::Value::Bool(v) => v.to_string(),
        serde_value::Value::U8(v) => v.to_string(),
        serde_value::Value::U16(v) => v.to_string(),
        serde_value::Value::U32(v) => v.to_string(),
        serde_value::Value::U64(v) => v.to_string(),
        serde_value::Value::I8(v) => v.to_string(),
        serde_value::Value::I16(v) => v.to_string(),
        serde_value::Value::I32(v) => v.to_string(),
        serde_value::Value::I64(v) => v.to_string(),
        serde_value::Value::F32(v) => v.to_string(),
        serde_value::Value::F64(v) => v.to_string(),
        serde_value::Value::Char(v) => v.to_string(),
        serde_value::Value::String(v) => v,
        serde_value::Value::Unit => "".to_string(),
        serde_value::Value::Option(v) => match v {
            Some(v) => coerce_to_string(*v),
            None => "null".to_string(),
        },
        serde_value::Value::Newtype(v) => coerce_to_string(*v),
        serde_value::Value::Seq(v) => {
            let l: Vec<_> = v.into_iter().map(coerce_to_string).collect();
            l.join(",")
        }
        serde_value::Value::Map(_) => "[object Object]".to_string(),
        serde_value::Value::Bytes(v) => {
            let l: Vec<_> = v.into_iter().map(|v| v.to_string()).collect();
            l.join(",")
        }
    }
}