rocketmq_common/common/attribute/enum_attribute.rs
1/*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17use std::collections::HashSet;
18
19use cheetah_string::CheetahString;
20
21use crate::common::attribute::Attribute;
22use crate::common::attribute::AttributeBase;
23
24#[derive(Debug, Clone)]
25pub struct EnumAttribute {
26 attribute: AttributeBase,
27 universe: HashSet<CheetahString>,
28 default_value: CheetahString,
29}
30
31impl EnumAttribute {
32 /// Create a new enum attribute with the specified properties
33 ///
34 /// # Arguments
35 ///
36 /// * `name` - The name of the attribute
37 /// * `changeable` - Whether the attribute can be changed after creation
38 /// * `universe` - Set of valid values this attribute can take
39 /// * `default_value` - Default value for this attribute (must be in universe)
40 ///
41 /// # Returns
42 ///
43 /// A new EnumAttribute instance, or an error if the default value is not in the universe
44 pub fn new(
45 name: CheetahString,
46 changeable: bool,
47 universe: HashSet<CheetahString>,
48 default_value: CheetahString,
49 ) -> Self {
50 Self {
51 attribute: AttributeBase::new(name, changeable),
52 universe,
53 default_value,
54 }
55 }
56
57 /// Get the default value for this attribute
58 #[inline]
59 pub fn default_value(&self) -> &str {
60 &self.default_value
61 }
62
63 /// Get the set of valid values for this attribute
64 #[inline]
65 pub fn universe(&self) -> &HashSet<CheetahString> {
66 &self.universe
67 }
68}
69
70impl Attribute for EnumAttribute {
71 #[inline]
72 fn verify(&self, value: &str) -> Result<(), String> {
73 if !self.universe.contains(value) {
74 return Err(format!(
75 "Value '{}' is not in the valid set: {:?}",
76 value, self.universe
77 ));
78 }
79 Ok(())
80 }
81
82 #[inline]
83 fn name(&self) -> &CheetahString {
84 self.attribute.name()
85 }
86
87 #[inline]
88 fn is_changeable(&self) -> bool {
89 self.attribute.is_changeable()
90 }
91}