Skip to main content

rocketmq_model/
boundary_type.rs

1// Copyright 2023 The RocketMQ Rust Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt;
16use std::str::FromStr;
17
18use serde::Deserialize;
19use serde::Deserializer;
20use serde::Serialize;
21use serde::Serializer;
22
23/// Selects the lower or upper offset when timestamps map to a range.
24#[derive(Debug, PartialEq, Eq, Default, Clone, Copy)]
25pub enum BoundaryType {
26    #[default]
27    Lower,
28    Upper,
29}
30
31impl BoundaryType {
32    /// Returns the lower-case boundary name used by RocketMQ APIs.
33    pub fn get_name(&self) -> &'static str {
34        match self {
35            BoundaryType::Lower => "lower",
36            BoundaryType::Upper => "upper",
37        }
38    }
39
40    /// Parses a boundary name using the Java-compatible fallback behavior.
41    ///
42    /// Values other than `upper`, matched without case sensitivity, resolve to
43    /// [`BoundaryType::Lower`].
44    pub fn get_type(name: &str) -> BoundaryType {
45        if name.eq_ignore_ascii_case("upper") {
46            BoundaryType::Upper
47        } else {
48            BoundaryType::Lower
49        }
50    }
51}
52
53impl Serialize for BoundaryType {
54    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
55    where
56        S: Serializer,
57    {
58        let name = match self {
59            BoundaryType::Lower => "LOWER",
60            BoundaryType::Upper => "UPPER",
61        };
62        serializer.serialize_str(name)
63    }
64}
65
66impl<'de> Deserialize<'de> for BoundaryType {
67    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
68    where
69        D: Deserializer<'de>,
70    {
71        let value = String::deserialize(deserializer)?;
72        Ok(BoundaryType::get_type(&value))
73    }
74}
75
76impl fmt::Display for BoundaryType {
77    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78        match self {
79            BoundaryType::Lower => write!(f, "LOWER"),
80            BoundaryType::Upper => write!(f, "UPPER"),
81        }
82    }
83}
84
85impl FromStr for BoundaryType {
86    type Err = String;
87
88    fn from_str(value: &str) -> Result<Self, Self::Err> {
89        Ok(BoundaryType::get_type(value))
90    }
91}
92
93#[cfg(test)]
94mod tests {
95    use super::*;
96
97    #[test]
98    fn names_and_parsing_preserve_java_compatibility() {
99        assert_eq!(BoundaryType::Lower.get_name(), "lower");
100        assert_eq!(BoundaryType::Upper.get_name(), "upper");
101        assert_eq!(BoundaryType::get_type("UPPER"), BoundaryType::Upper);
102        assert_eq!(BoundaryType::get_type("invalid"), BoundaryType::Lower);
103        assert_eq!("upper".parse::<BoundaryType>().unwrap(), BoundaryType::Upper);
104    }
105
106    #[test]
107    fn serde_and_display_use_uppercase_names() {
108        let encoded = serde_json::to_string(&BoundaryType::Upper).unwrap();
109        assert_eq!(encoded, r#""UPPER""#);
110        assert_eq!(
111            serde_json::from_str::<BoundaryType>(&encoded).unwrap(),
112            BoundaryType::Upper
113        );
114        assert_eq!(format!("{}", BoundaryType::Lower), "LOWER");
115    }
116
117    #[test]
118    fn invalid_serialized_values_fall_back_to_lower() {
119        assert_eq!(
120            serde_json::from_str::<BoundaryType>(r#""unknown""#).unwrap(),
121            BoundaryType::Lower
122        );
123    }
124}