]> git.proxmox.com Git - perlmod.git/commitdiff
add 'instantiate_magic_result' to allow error handling
authorWolfgang Bumiller <w.bumiller@proxmox.com>
Tue, 25 Jul 2023 08:22:30 +0000 (10:22 +0200)
committerWolfgang Bumiller <w.bumiller@proxmox.com>
Tue, 25 Jul 2023 08:22:32 +0000 (10:22 +0200)
The previous `instantiate_magic!` macro contained a '?' and thus tried
to return with an error. This is inconvenient when trying to work with
specific serialized error types.

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
perlmod/src/macros.rs

index 014d7cbc7fbae9fa38687b91fa622f389040487a..38c137ad26c4dae3c6f709699de3181d0c76f116 100644 (file)
@@ -213,6 +213,25 @@ macro_rules! declare_magic {
     };
 }
 
+/// This is a version of `instantiate_magic` without the implicit return when an error happens.
+/// Instead, this yields a `Result<Value, Error>`.
+///
+/// For a usage example see the [`magic`](crate::magic) module documentation.
+#[macro_export]
+macro_rules! instantiate_magic_result {
+    ($class:expr, $magic:expr => $value:expr) => {{
+        let value = $crate::Value::new_hash();
+        let this = $crate::Value::new_ref(&value);
+        match this.bless_sv($class) {
+            Err(err) => Err(err),
+            Ok(_) => {
+                value.add_magic($magic.with_value($value));
+                Ok(this)
+            }
+        }
+    }};
+}
+
 /// Create an empty hash ref with magic data. This is a convenience helper for `sub new`
 /// implementations.
 ///
@@ -220,10 +239,6 @@ macro_rules! declare_magic {
 #[macro_export]
 macro_rules! instantiate_magic {
     ($class:expr, $magic:expr => $value:expr) => {{
-        let value = $crate::Value::new_hash();
-        let this = $crate::Value::new_ref(&value);
-        this.bless_sv($class)?;
-        value.add_magic($magic.with_value($value));
-        this
+        $crate::instantiate_magic_result!($class, $magic => $value)?
     }};
 }