openrtb2/
auction_type.rs

1/// 3.2.1 [`BidRequest#at`], 3.2.12 [`Deal#at`]
2///
3/// Auction type, where 1 = First Price, 2 = Second Price Plus. Exchange-specific auction types can
4/// be defined using values greater than 500.
5///
6/// [`BidRequest#at`]: ./struct.BidRequest.html#structfield.at
7/// [`Deal#at`]: ./struct.Deal.html#structfield.at
8#[derive(Debug, PartialEq, Eq, Clone, Copy)]
9pub enum AuctionType {
10    FirstPrice,
11    SecondPricePlus,
12    ExchangeSpecific(i32),
13}
14
15impl Default for AuctionType {
16    fn default() -> Self {
17        Self::SecondPricePlus
18    }
19}
20
21impl serde::Serialize for AuctionType {
22    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
23    where
24        S: serde::Serializer,
25    {
26        let v = match self {
27            Self::FirstPrice => 1,
28            Self::SecondPricePlus => 2,
29            Self::ExchangeSpecific(v) => *v,
30        };
31        serializer.serialize_i32(v)
32    }
33}
34
35impl<'de> serde::Deserialize<'de> for AuctionType {
36    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
37    where
38        D: serde::Deserializer<'de>,
39    {
40        let v = match i32::deserialize(deserializer)? {
41            1 => Self::FirstPrice,
42            2 => Self::SecondPricePlus,
43            v if v > 500 => Self::ExchangeSpecific(v),
44            v => {
45                let s = format!("invalid value: {}, expected 1 or 2 or greater than 500", v);
46                return Err(serde::de::Error::custom(s));
47            }
48        };
49        Ok(v)
50    }
51}
52
53#[cfg(test)]
54mod test {
55    use super::*;
56    #[test]
57    fn json() -> serde_json::Result<()> {
58        assert!(serde_json::from_str::<AuctionType>("3").is_err());
59        assert!(serde_json::from_str::<AuctionType>("500").is_err());
60
61        let json = "[1,2,501]";
62        let e1: Vec<AuctionType> = serde_json::from_str(json)?;
63        assert_eq!(serde_json::to_string(&e1)?, json);
64        assert_eq!(
65            e1,
66            vec![
67                AuctionType::FirstPrice,
68                AuctionType::SecondPricePlus,
69                AuctionType::ExchangeSpecific(501)
70            ]
71        );
72
73        Ok(())
74    }
75}