bc_envelope/base/
wrap.rs

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