Skip to main content

rocketmq_model/common/attribute/
enum_attribute.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::collections::HashSet;
16
17use cheetah_string::CheetahString;
18
19use crate::common::attribute::Attribute;
20use crate::common::attribute::AttributeBase;
21
22#[derive(Debug, Clone)]
23pub struct EnumAttribute {
24    attribute: AttributeBase,
25    universe: HashSet<CheetahString>,
26    default_value: CheetahString,
27}
28
29impl EnumAttribute {
30    /// Create a new enum attribute with the specified properties
31    ///
32    /// # Arguments
33    ///
34    /// * `name` - The name of the attribute
35    /// * `changeable` - Whether the attribute can be changed after creation
36    /// * `universe` - Set of valid values this attribute can take
37    /// * `default_value` - Default value for this attribute (must be in universe)
38    ///
39    /// # Returns
40    ///
41    /// A new EnumAttribute instance, or an error if the default value is not in the universe
42    pub fn new(
43        name: CheetahString,
44        changeable: bool,
45        universe: HashSet<CheetahString>,
46        default_value: CheetahString,
47    ) -> Self {
48        Self {
49            attribute: AttributeBase::new(name, changeable),
50            universe,
51            default_value,
52        }
53    }
54
55    /// Get the default value for this attribute
56    #[inline]
57    pub fn default_value(&self) -> &str {
58        &self.default_value
59    }
60
61    /// Get the set of valid values for this attribute
62    #[inline]
63    pub fn universe(&self) -> &HashSet<CheetahString> {
64        &self.universe
65    }
66}
67
68impl Attribute for EnumAttribute {
69    #[inline]
70    fn verify(&self, value: &str) -> Result<(), String> {
71        if !self.universe.contains(value) {
72            return Err(format!(
73                "Value '{}' is not in the valid set: {:?}",
74                value, self.universe
75            ));
76        }
77        Ok(())
78    }
79
80    #[inline]
81    fn name(&self) -> &CheetahString {
82        self.attribute.name()
83    }
84
85    #[inline]
86    fn is_changeable(&self) -> bool {
87        self.attribute.is_changeable()
88    }
89}