Skip to main content

ferogram_tl_parser/tl/
parameter.rs

1// Copyright (c) Ankit Chaubey <ankitchaubey.dev@gmail.com>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3//
4// ferogram: async Telegram MTProto client in Rust
5// https://github.com/ankit-chaubey/ferogram
6//
7// If you use or modify this code, keep this notice at the top of your file
8// and include the LICENSE-MIT or LICENSE-APACHE file from this repository:
9// https://github.com/ankit-chaubey/ferogram
10
11use std::fmt;
12use std::str::FromStr;
13
14use crate::errors::ParamParseError;
15use crate::tl::ParameterType;
16
17/// A single `name:Type` parameter inside a TL definition.
18#[derive(Clone, Debug, PartialEq, Eq, Hash)]
19pub struct Parameter {
20    /// The parameter name as it appears in the TL schema.
21    pub name: String,
22    /// The resolved type of this parameter.
23    pub ty: ParameterType,
24}
25
26impl fmt::Display for Parameter {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        write!(f, "{}:{}", self.name, self.ty)
29    }
30}
31
32impl FromStr for Parameter {
33    type Err = ParamParseError;
34
35    /// Parses a single parameter token such as `flags:#`, `id:long`, or
36    /// `photo:flags.0?InputPhoto`.
37    ///
38    /// Returns `Err(ParamParseError::TypeDef { name })` for the special
39    /// `{X:Type}` generic-parameter-definition syntax so callers can handle it
40    /// without the overhead of `?`.
41    fn from_str(token: &str) -> Result<Self, Self::Err> {
42        // Generic type-definition `{X:Type}`: not a real parameter
43        if let Some(inner) = token.strip_prefix('{') {
44            return Err(match inner.strip_suffix(":Type}") {
45                Some(name) => ParamParseError::TypeDef { name: name.into() },
46                None => ParamParseError::MissingDef,
47            });
48        }
49
50        let (name, ty_str) = token
51            .split_once(':')
52            .ok_or(ParamParseError::NotImplemented)?;
53
54        if name.is_empty() || ty_str.is_empty() {
55            return Err(ParamParseError::Empty);
56        }
57
58        Ok(Self {
59            name: name.to_owned(),
60            ty: ty_str.parse()?,
61        })
62    }
63}