mwapi_responses/
query.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
/*
 * SPDX-FileCopyrightText: 2023 Misato Kano <me@mirror-kt.dev>
 * SPDX-License-Identifier: GPL-3.0-or-later
 */

use serde::de::{MapAccess, Visitor};
use serde::{Deserialize, Deserializer};
use std::collections::HashMap;
use std::fmt::Formatter;

#[derive(Deserialize)]
#[serde(untagged)]
enum StringyNumber {
    String(String),
    Number(i64),
}

impl StringyNumber {
    fn stringify(self) -> String {
        match self {
            Self::String(string) => string,
            Self::Number(num) => num.to_string(),
        }
    }
}

/// The `API:Querypage` generator fails when trying to deserialize it as a string because
/// the return value of continue contains a number.
/// This deserializer also treats numbers as strings and deserializes them.
pub fn deserialize_continue<'de, D>(
    deserializer: D,
) -> Result<HashMap<String, String>, D::Error>
where
    D: Deserializer<'de>,
{
    struct ContinueVisitor;

    impl<'de> Visitor<'de> for ContinueVisitor {
        type Value = HashMap<String, String>;

        fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
            formatter.write_str("'continue_' must be a string")
        }

        fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
        where
            A: MapAccess<'de>,
        {
            let mut values = HashMap::new();
            while let Some((key, value)) =
                map.next_entry::<String, StringyNumber>()?
            {
                values.insert(key, value.stringify());
            }

            Ok(values)
        }
    }

    let visitor = ContinueVisitor;
    deserializer.deserialize_map(visitor)
}