Skip to content

Commit 949736f

Browse files
committed
Add replace or push functionality
1 parent 7f3368d commit 949736f

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

rcgen/src/lib.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,30 @@ impl DistinguishedName {
349349
self.entries.push_front((ty, s.into()));
350350
}
351351

352+
/// Replaces the *fist occurrence* of a type with a new value.
353+
/// This is a convenience function to avoid duplicating values.
354+
///
355+
/// If there are multiple occurrences of a type there is currently no way of changing the besides iterating over the types and values of an existing instance and creating a new instance.
356+
///
357+
/// ```
358+
/// # use rcgen::{DistinguishedName, DnType, DnValue};
359+
/// let mut dn = DistinguishedName::new();
360+
/// dn.push(DnType::CommonName, DnValue::PrintableString("Master Cert".try_into().unwrap()));
361+
/// assert_eq!(dn.get(&DnType::CommonName).get(0), Some(&DnValue::PrintableString("Master Cert".try_into().unwrap())).as_ref());
362+
/// dn.push(DnType::CommonName, DnValue::PrintableString("Other Master Cert".try_into().unwrap()));
363+
/// assert_eq!(dn.get(&DnType::CommonName).get(0), Some(&DnValue::PrintableString("Other Master Cert".try_into().unwrap())).as_ref());
364+
/// ```
365+
pub fn replace_or_push(&mut self, ty: DnType, s: impl Into<DnValue>) {
366+
for (dn_type, dn_value) in self.entries.iter_mut() {
367+
if *dn_type == ty {
368+
*dn_value = s.into();
369+
return;
370+
}
371+
}
372+
373+
self.push(ty, s)
374+
}
375+
352376
#[cfg(feature = "x509-parser")]
353377
fn from_name(name: &x509_parser::x509::X509Name) -> Result<Self, Error> {
354378
use x509_parser::der_parser::asn1_rs::Tag;

0 commit comments

Comments
 (0)