Skip to content

Commit cb5ad84

Browse files
authored
Reduce code duplication in PolicyBuilder already set checks. (#11666)
1 parent a5b1ffd commit cb5ad84

File tree

1 file changed

+20
-19
lines changed

1 file changed

+20
-19
lines changed

src/rust/src/x509/verify.rs

+20-19
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,20 @@ pyo3::create_exception!(
5454
pyo3::exceptions::PyException
5555
);
5656

57+
macro_rules! policy_builder_set_once_check {
58+
($self: ident, $property: ident, $human_readable_name: literal) => {
59+
if $self.$property.is_some() {
60+
return Err(CryptographyError::from(
61+
pyo3::exceptions::PyValueError::new_err(concat!(
62+
"The ",
63+
$human_readable_name,
64+
" may only be set once."
65+
)),
66+
));
67+
}
68+
};
69+
}
70+
5771
#[pyo3::pyclass(frozen, module = "cryptography.x509.verification")]
5872
pub(crate) struct PolicyBuilder {
5973
time: Option<asn1::DateTime>,
@@ -77,13 +91,8 @@ impl PolicyBuilder {
7791
py: pyo3::Python<'_>,
7892
new_time: pyo3::Bound<'_, pyo3::PyAny>,
7993
) -> CryptographyResult<PolicyBuilder> {
80-
if self.time.is_some() {
81-
return Err(CryptographyError::from(
82-
pyo3::exceptions::PyValueError::new_err(
83-
"The validation time may only be set once.",
84-
),
85-
));
86-
}
94+
policy_builder_set_once_check!(self, time, "validation time");
95+
8796
Ok(PolicyBuilder {
8897
time: Some(py_to_datetime(py, new_time)?),
8998
store: self.store.as_ref().map(|s| s.clone_ref(py)),
@@ -92,11 +101,8 @@ impl PolicyBuilder {
92101
}
93102

94103
fn store(&self, new_store: pyo3::Py<PyStore>) -> CryptographyResult<PolicyBuilder> {
95-
if self.store.is_some() {
96-
return Err(CryptographyError::from(
97-
pyo3::exceptions::PyValueError::new_err("The trust store may only be set once."),
98-
));
99-
}
104+
policy_builder_set_once_check!(self, store, "trust store");
105+
100106
Ok(PolicyBuilder {
101107
time: self.time.clone(),
102108
store: Some(new_store),
@@ -109,13 +115,8 @@ impl PolicyBuilder {
109115
py: pyo3::Python<'_>,
110116
new_max_chain_depth: u8,
111117
) -> CryptographyResult<PolicyBuilder> {
112-
if self.max_chain_depth.is_some() {
113-
return Err(CryptographyError::from(
114-
pyo3::exceptions::PyValueError::new_err(
115-
"The maximum chain depth may only be set once.",
116-
),
117-
));
118-
}
118+
policy_builder_set_once_check!(self, max_chain_depth, "maximum chain depth");
119+
119120
Ok(PolicyBuilder {
120121
time: self.time.clone(),
121122
store: self.store.as_ref().map(|s| s.clone_ref(py)),

0 commit comments

Comments
 (0)