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
// Copyright 2024 New Vector Ltd.
// Copyright 2023, 2024 The Matrix.org Foundation C.I.C.
//
// SPDX-License-Identifier: AGPL-3.0-only
// Please see LICENSE in the repository root for full details.

use serde::{Deserialize, Serialize};

/// Specifies how to format an argument.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TypeSpecifier {
    /// `b`
    BinaryNumber,

    /// `c`
    CharacterAsciiValue,

    /// `i`
    DecimalNumber,

    /// `i`
    IntegerNumber,

    /// `e`
    ScientificNotation,

    /// `u`
    UnsignedDecimalNumber,

    /// `f`
    FloatingPointNumber,

    /// `g`
    FloatingPointNumberWithSignificantDigits,

    /// `o`
    OctalNumber,

    /// `s`
    String,

    /// `t`
    TrueOrFalse,

    /// `T`
    TypeOfArgument,

    /// `v`
    PrimitiveValue,

    /// `x`
    HexadecimalNumberLowercase,

    /// `X`
    HexadecimalNumberUppercase,

    /// `j`
    Json,
}

impl TypeSpecifier {
    /// Returns true if the type specifier is a numeric type, which should be
    /// specially formatted with the zero
    const fn is_numeric(self) -> bool {
        matches!(
            self,
            Self::BinaryNumber
                | Self::DecimalNumber
                | Self::IntegerNumber
                | Self::ScientificNotation
                | Self::UnsignedDecimalNumber
                | Self::FloatingPointNumber
                | Self::FloatingPointNumberWithSignificantDigits
                | Self::OctalNumber
                | Self::HexadecimalNumberLowercase
                | Self::HexadecimalNumberUppercase
        )
    }
}

impl std::fmt::Display for TypeSpecifier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let specifier = match self {
            Self::BinaryNumber => 'b',
            Self::CharacterAsciiValue => 'c',
            Self::DecimalNumber => 'd',
            Self::IntegerNumber => 'i',
            Self::ScientificNotation => 'e',
            Self::UnsignedDecimalNumber => 'u',
            Self::FloatingPointNumber => 'f',
            Self::FloatingPointNumberWithSignificantDigits => 'g',
            Self::OctalNumber => 'o',
            Self::String => 's',
            Self::TrueOrFalse => 't',
            Self::TypeOfArgument => 'T',
            Self::PrimitiveValue => 'v',
            Self::HexadecimalNumberLowercase => 'x',
            Self::HexadecimalNumberUppercase => 'X',
            Self::Json => 'j',
        };
        write!(f, "{specifier}")
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ArgumentReference {
    Indexed(usize),
    Named(String),
}

impl std::fmt::Display for ArgumentReference {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ArgumentReference::Indexed(index) => write!(f, "{index}$"),
            ArgumentReference::Named(name) => write!(f, "({name})"),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PaddingSpecifier {
    Zero,
    Char(char),
}

impl std::fmt::Display for PaddingSpecifier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PaddingSpecifier::Zero => write!(f, "0"),
            PaddingSpecifier::Char(c) => write!(f, "'{c}"),
        }
    }
}

impl PaddingSpecifier {
    pub fn char(self) -> char {
        match self {
            PaddingSpecifier::Zero => '0',
            PaddingSpecifier::Char(c) => c,
        }
    }

    pub const fn is_zero(self) -> bool {
        match self {
            PaddingSpecifier::Zero => true,
            PaddingSpecifier::Char(_) => false,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Placeholder {
    pub type_specifier: TypeSpecifier,
    pub requested_argument: Option<ArgumentReference>,
    pub plus_sign: bool,
    pub padding_specifier: Option<PaddingSpecifier>,
    pub left_align: bool,
    pub width: Option<usize>,
    pub precision: Option<usize>,
}

impl Placeholder {
    pub fn padding_specifier_is_zero(&self) -> bool {
        self.padding_specifier
            .is_some_and(PaddingSpecifier::is_zero)
    }

    /// Whether it should be formatted as a number for the width argument
    pub fn numeric_width(&self) -> Option<usize> {
        self.width
            .filter(|_| self.padding_specifier_is_zero() && self.type_specifier.is_numeric())
    }
}

impl std::fmt::Display for Placeholder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "%")?;
        if let Some(argument) = &self.requested_argument {
            write!(f, "{argument}")?;
        }

        if self.plus_sign {
            write!(f, "+")?;
        }

        if let Some(padding_specifier) = &self.padding_specifier {
            write!(f, "{padding_specifier}")?;
        }

        if self.left_align {
            write!(f, "-")?;
        }

        if let Some(width) = self.width {
            write!(f, "{width}")?;
        }

        if let Some(precision) = self.precision {
            write!(f, ".{precision}")?;
        }

        write!(f, "{}", self.type_specifier)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Message {
    parts: Vec<Part>,
}

impl std::fmt::Display for Message {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for part in &self.parts {
            write!(f, "{part}")?;
        }
        Ok(())
    }
}

impl FromIterator<Part> for Message {
    fn from_iter<T: IntoIterator<Item = Part>>(iter: T) -> Self {
        Self {
            parts: iter.into_iter().collect(),
        }
    }
}

impl Message {
    pub(crate) fn parts(&self) -> std::slice::Iter<'_, Part> {
        self.parts.iter()
    }

    /// Create a message from a literal string, without any placeholders.
    #[must_use]
    pub fn from_literal(literal: String) -> Message {
        Message {
            parts: vec![Part::Text(literal)],
        }
    }
}

impl Serialize for Message {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let string = self.to_string();
        serializer.serialize_str(&string)
    }
}

impl<'de> Deserialize<'de> for Message {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let string = String::deserialize(deserializer)?;
        string.parse().map_err(serde::de::Error::custom)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Part {
    Percent,
    Text(String),
    Placeholder(Placeholder),
}

impl From<Placeholder> for Part {
    fn from(placeholder: Placeholder) -> Self {
        Self::Placeholder(placeholder)
    }
}

impl From<String> for Part {
    fn from(text: String) -> Self {
        Self::Text(text)
    }
}

impl std::fmt::Display for Part {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Part::Percent => write!(f, "%%"),
            Part::Text(text) => write!(f, "{text}"),
            Part::Placeholder(placeholder) => write!(f, "{placeholder}"),
        }
    }
}