mpvipc_async/
message_parser.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
//! JSON parsing logic for command responses from [`MpvIpc`](crate::ipc::MpvIpc).

use std::collections::HashMap;

use serde_json::Value;

use crate::{MpvDataType, MpvError, PlaylistEntry};

pub trait TypeHandler: Sized {
    fn get_value(value: Value) -> Result<Self, MpvError>;
    fn as_string(&self) -> String;
}

impl TypeHandler for String {
    fn get_value(value: Value) -> Result<String, MpvError> {
        value
            .as_str()
            .ok_or(MpvError::ValueContainsUnexpectedType {
                expected_type: "String".to_string(),
                received: value.clone(),
            })
            .map(|s| s.to_string())
    }

    fn as_string(&self) -> String {
        self.to_string()
    }
}

impl TypeHandler for bool {
    fn get_value(value: Value) -> Result<bool, MpvError> {
        value
            .as_bool()
            .ok_or(MpvError::ValueContainsUnexpectedType {
                expected_type: "bool".to_string(),
                received: value.clone(),
            })
    }

    fn as_string(&self) -> String {
        if *self {
            "true".to_string()
        } else {
            "false".to_string()
        }
    }
}

impl TypeHandler for f64 {
    fn get_value(value: Value) -> Result<f64, MpvError> {
        value.as_f64().ok_or(MpvError::ValueContainsUnexpectedType {
            expected_type: "f64".to_string(),
            received: value.clone(),
        })
    }

    fn as_string(&self) -> String {
        self.to_string()
    }
}

impl TypeHandler for usize {
    fn get_value(value: Value) -> Result<usize, MpvError> {
        value
            .as_u64()
            .map(|u| u as usize)
            .ok_or(MpvError::ValueContainsUnexpectedType {
                expected_type: "usize".to_string(),
                received: value.clone(),
            })
    }

    fn as_string(&self) -> String {
        self.to_string()
    }
}

impl TypeHandler for MpvDataType {
    fn get_value(value: Value) -> Result<MpvDataType, MpvError> {
        json_to_value(&value)
    }

    fn as_string(&self) -> String {
        format!("{:?}", self)
    }
}

impl TypeHandler for HashMap<String, MpvDataType> {
    fn get_value(value: Value) -> Result<HashMap<String, MpvDataType>, MpvError> {
        value
            .as_object()
            .ok_or(MpvError::ValueContainsUnexpectedType {
                expected_type: "Map<String, Value>".to_string(),
                received: value.clone(),
            })
            .and_then(json_map_to_hashmap)
    }

    fn as_string(&self) -> String {
        format!("{:?}", self)
    }
}

impl TypeHandler for Vec<PlaylistEntry> {
    fn get_value(value: Value) -> Result<Vec<PlaylistEntry>, MpvError> {
        value
            .as_array()
            .ok_or(MpvError::ValueContainsUnexpectedType {
                expected_type: "Array<Value>".to_string(),
                received: value.clone(),
            })
            .and_then(|array| json_array_to_playlist(array))
    }

    fn as_string(&self) -> String {
        format!("{:?}", self)
    }
}

pub(crate) fn json_to_value(value: &Value) -> Result<MpvDataType, MpvError> {
    match value {
        Value::Array(array) => Ok(MpvDataType::Array(json_array_to_vec(array)?)),
        Value::Bool(b) => Ok(MpvDataType::Bool(*b)),
        Value::Number(n) => {
            if n.is_i64() && n.as_i64().unwrap() == -1 {
                Ok(MpvDataType::MinusOne)
            } else if n.is_u64() {
                Ok(MpvDataType::Usize(n.as_u64().unwrap() as usize))
            } else if n.is_f64() {
                Ok(MpvDataType::Double(n.as_f64().unwrap()))
            } else {
                Err(MpvError::ValueContainsUnexpectedType {
                    expected_type: "i64, u64, or f64".to_string(),
                    received: value.clone(),
                })
            }
        }
        Value::Object(map) => Ok(MpvDataType::HashMap(json_map_to_hashmap(map)?)),
        Value::String(s) => Ok(MpvDataType::String(s.to_string())),
        Value::Null => Ok(MpvDataType::Null),
    }
}

pub(crate) fn json_map_to_hashmap(
    map: &serde_json::map::Map<String, Value>,
) -> Result<HashMap<String, MpvDataType>, MpvError> {
    let mut output_map: HashMap<String, MpvDataType> = HashMap::new();
    for (ref key, value) in map.iter() {
        output_map.insert(key.to_string(), json_to_value(value)?);
    }
    Ok(output_map)
}

pub(crate) fn json_array_to_vec(array: &[Value]) -> Result<Vec<MpvDataType>, MpvError> {
    array.iter().map(json_to_value).collect()
}

fn json_map_to_playlist_entry(
    map: &serde_json::map::Map<String, Value>,
) -> Result<PlaylistEntry, MpvError> {
    let filename = match map.get("filename") {
        Some(Value::String(s)) => s.to_string(),
        Some(data) => {
            return Err(MpvError::ValueContainsUnexpectedType {
                expected_type: "String".to_owned(),
                received: data.clone(),
            })
        }
        None => return Err(MpvError::MissingMpvData),
    };
    let title = match map.get("title") {
        Some(Value::String(s)) => Some(s.to_string()),
        Some(data) => {
            return Err(MpvError::ValueContainsUnexpectedType {
                expected_type: "String".to_owned(),
                received: data.clone(),
            })
        }
        None => None,
    };
    let current = match map.get("current") {
        Some(Value::Bool(b)) => *b,
        Some(data) => {
            return Err(MpvError::ValueContainsUnexpectedType {
                expected_type: "bool".to_owned(),
                received: data.clone(),
            })
        }
        None => false,
    };
    Ok(PlaylistEntry {
        id: 0,
        filename,
        title,
        current,
    })
}

pub(crate) fn json_array_to_playlist(array: &[Value]) -> Result<Vec<PlaylistEntry>, MpvError> {
    array
        .iter()
        .map(|entry| match entry {
            Value::Object(map) => json_map_to_playlist_entry(map),
            data => Err(MpvError::ValueContainsUnexpectedType {
                expected_type: "Map<String, Value>".to_owned(),
                received: data.clone(),
            }),
        })
        .enumerate()
        .map(|(id, entry)| {
            entry.map(|mut entry| {
                entry.id = id;
                entry
            })
        })
        .collect()
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::MpvDataType;
    use serde_json::json;
    use std::collections::HashMap;

    #[test]
    fn test_json_map_to_hashmap() {
        let json = json!({
            "array": [1, 2, 3],
            "bool": true,
            "double": 1.0,
            "usize": 1,
            "minus_one": -1,
            "null": null,
            "string": "string",
            "object": {
                "key": "value"
            }
        });

        let mut expected = HashMap::new();
        expected.insert(
            "array".to_string(),
            MpvDataType::Array(vec![
                MpvDataType::Usize(1),
                MpvDataType::Usize(2),
                MpvDataType::Usize(3),
            ]),
        );
        expected.insert("bool".to_string(), MpvDataType::Bool(true));
        expected.insert("double".to_string(), MpvDataType::Double(1.0));
        expected.insert("usize".to_string(), MpvDataType::Usize(1));
        expected.insert("minus_one".to_string(), MpvDataType::MinusOne);
        expected.insert("null".to_string(), MpvDataType::Null);
        expected.insert(
            "string".to_string(),
            MpvDataType::String("string".to_string()),
        );
        expected.insert(
            "object".to_string(),
            MpvDataType::HashMap(HashMap::from([(
                "key".to_string(),
                MpvDataType::String("value".to_string()),
            )])),
        );

        match json_map_to_hashmap(json.as_object().unwrap()) {
            Ok(m) => assert_eq!(m, expected),
            Err(e) => panic!("{:?}", e),
        }
    }

    #[test]
    fn test_json_array_to_vec() {
        let json = json!([
            [1, 2, 3],
            true,
            1.0,
            1,
            -1,
            null,
            "string",
            {
                "key": "value"
            }
        ]);

        println!("{:?}", json.as_array().unwrap());
        println!("{:?}", json_array_to_vec(json.as_array().unwrap()));

        let expected = vec![
            MpvDataType::Array(vec![
                MpvDataType::Usize(1),
                MpvDataType::Usize(2),
                MpvDataType::Usize(3),
            ]),
            MpvDataType::Bool(true),
            MpvDataType::Double(1.0),
            MpvDataType::Usize(1),
            MpvDataType::MinusOne,
            MpvDataType::Null,
            MpvDataType::String("string".to_string()),
            MpvDataType::HashMap(HashMap::from([(
                "key".to_string(),
                MpvDataType::String("value".to_string()),
            )])),
        ];

        match json_array_to_vec(json.as_array().unwrap()) {
            Ok(v) => assert_eq!(v, expected),
            Err(e) => panic!("{:?}", e),
        }
    }

    #[test]
    fn test_json_array_to_playlist() -> Result<(), MpvError> {
        let json = json!([
            {
                "filename": "file1",
                "title": "title1",
                "current": true
            },
            {
                "filename": "file2",
                "title": "title2",
                "current": false
            },
            {
                "filename": "file3",
                "current": false
            }
        ]);

        let expected = vec![
            PlaylistEntry {
                id: 0,
                filename: "file1".to_string(),
                title: Some("title1".to_string()),
                current: true,
            },
            PlaylistEntry {
                id: 1,
                filename: "file2".to_string(),
                title: Some("title2".to_string()),
                current: false,
            },
            PlaylistEntry {
                id: 2,
                filename: "file3".to_string(),
                title: None,
                current: false,
            },
        ];

        assert_eq!(json_array_to_playlist(json.as_array().unwrap())?, expected);

        Ok(())
    }
}