|
1 |
| -use serde::{Deserialize, Serialize}; |
| 1 | +use serde::{Deserialize, Deserializer, Serialize, de::Error}; |
| 2 | +use serde_json::Value; |
2 | 3 |
|
3 |
| -#[derive(Debug, Default, Serialize, Deserialize, Clone)] |
| 4 | +#[derive(Debug, Default, Serialize, Clone)] |
4 | 5 | #[serde(rename_all = "camelCase")]
|
5 |
| -pub struct FormatOptions; |
| 6 | +pub struct FormatOptions { |
| 7 | + pub experimental: bool, |
| 8 | +} |
| 9 | + |
| 10 | +impl<'de> Deserialize<'de> for FormatOptions { |
| 11 | + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> |
| 12 | + where |
| 13 | + D: Deserializer<'de>, |
| 14 | + { |
| 15 | + let value = Value::deserialize(deserializer)?; |
| 16 | + FormatOptions::try_from(value).map_err(Error::custom) |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +impl TryFrom<Value> for FormatOptions { |
| 21 | + type Error = String; |
| 22 | + |
| 23 | + fn try_from(value: Value) -> Result<Self, Self::Error> { |
| 24 | + let Some(object) = value.as_object() else { |
| 25 | + return Err("no object passed".to_string()); |
| 26 | + }; |
| 27 | + |
| 28 | + Ok(Self { |
| 29 | + experimental: object |
| 30 | + .get("fmt.experimental") |
| 31 | + .is_some_and(|run| serde_json::from_value::<bool>(run.clone()).unwrap_or_default()), |
| 32 | + }) |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +#[cfg(test)] |
| 37 | +mod test { |
| 38 | + use serde_json::json; |
| 39 | + |
| 40 | + use super::FormatOptions; |
| 41 | + |
| 42 | + #[test] |
| 43 | + fn test_valid_options_json() { |
| 44 | + let json = json!({ |
| 45 | + "fmt.experimental": true, |
| 46 | + }); |
| 47 | + |
| 48 | + let options = FormatOptions::try_from(json).unwrap(); |
| 49 | + assert!(options.experimental); |
| 50 | + } |
| 51 | + |
| 52 | + #[test] |
| 53 | + fn test_empty_options_json() { |
| 54 | + let json = json!({}); |
| 55 | + |
| 56 | + let options = FormatOptions::try_from(json).unwrap(); |
| 57 | + assert!(!options.experimental); |
| 58 | + } |
| 59 | + |
| 60 | + #[test] |
| 61 | + fn test_invalid_options_json() { |
| 62 | + let json = json!({ |
| 63 | + "fmt.experimental": "what", // should be bool |
| 64 | + }); |
| 65 | + |
| 66 | + let options = FormatOptions::try_from(json).unwrap(); |
| 67 | + assert!(!options.experimental); |
| 68 | + } |
| 69 | +} |
0 commit comments