bc_envelope/base/wrap.rs
1use anyhow::{ bail, Result };
2
3use crate::{ Envelope, Error };
4
5use super::envelope::EnvelopeCase;
6
7/// Support for wrapping and unwrapping envelopes.
8impl Envelope {
9 /// Returns a new envelope which wraps the current envelope.
10 ///
11 /// Wrapping an envelope allows you to treat an envelope (including its assertions)
12 /// as a single unit, making it possible to add assertions about the envelope as a whole.
13 ///
14 /// # Examples
15 ///
16 /// ```
17 /// # use bc_envelope::prelude::*;
18 /// # use indoc::indoc;
19 /// // Create an envelope with an assertion
20 /// let envelope = Envelope::new("Hello.")
21 /// .add_assertion("language", "English");
22 ///
23 /// // Wrap it to add an assertion about the envelope as a whole
24 /// let wrapped = envelope.wrap_envelope()
25 /// .add_assertion("authenticated", true);
26 ///
27 /// assert_eq!(wrapped.format(), indoc! {r#"
28 /// {
29 /// "Hello." [
30 /// "language": "English"
31 /// ]
32 /// } [
33 /// "authenticated": true
34 /// ]
35 /// "#}.trim());
36 /// ```
37 pub fn wrap_envelope(&self) -> Self {
38 Self::new_wrapped(self.clone())
39 }
40
41 /// Unwraps and returns the inner envelope.
42 ///
43 /// This extracts the envelope contained within a wrapped envelope.
44 ///
45 /// # Errors
46 ///
47 /// Returns `EnvelopeError::NotWrapped` if this is not a wrapped envelope.
48 ///
49 /// # Examples
50 ///
51 /// ```
52 /// # use bc_envelope::prelude::*;
53 /// // Create an envelope and wrap it
54 /// let envelope = Envelope::new("Hello.");
55 /// let wrapped = envelope.wrap_envelope();
56 ///
57 /// // Unwrap to get the original envelope
58 /// let unwrapped = wrapped.unwrap_envelope().unwrap();
59 /// assert_eq!(unwrapped.format_flat(), r#""Hello.""#);
60 /// ```
61 pub fn unwrap_envelope(&self) -> Result<Self> {
62 match self.subject().case() {
63 EnvelopeCase::Wrapped { envelope, .. } => Ok(envelope.clone()),
64 _ => bail!(Error::NotWrapped),
65 }
66 }
67}