From e162a1be9e69afdfbadceed3db94ccf7e3efcf5c Mon Sep 17 00:00:00 2001 From: Dmitrii Aleksandrov Date: Thu, 9 May 2024 20:44:37 +0400 Subject: [PATCH] Add ActiveValue::try_as_ref() (#2197) --- src/entity/active_model.rs | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/src/entity/active_model.rs b/src/entity/active_model.rs index c0e344840..50c029cda 100644 --- a/src/entity/active_model.rs +++ b/src/entity/active_model.rs @@ -849,6 +849,26 @@ where None => ActiveValue::NotSet, }; } + + /// Get the inner value, unless `self` is [NotSet][ActiveValue::NotSet]. + /// + /// There's also a panicking version: [ActiveValue::as_ref]. + /// + /// ## Examples + /// + /// ``` + /// # use sea_orm::ActiveValue; + /// # + /// assert_eq!(ActiveValue::Unchanged(42).try_as_ref(), Some(&42)); + /// assert_eq!(ActiveValue::Set(42).try_as_ref(), Some(&42)); + /// assert_eq!(ActiveValue::NotSet.try_as_ref(), None::<&i32>); + /// ``` + pub fn try_as_ref(&self) -> Option<&V> { + match self { + ActiveValue::Set(value) | ActiveValue::Unchanged(value) => Some(value), + ActiveValue::NotSet => None, + } + } } impl std::convert::AsRef for ActiveValue @@ -857,7 +877,9 @@ where { /// # Panics /// - /// Panics if it is [ActiveValue::NotSet] + /// Panics if it is [ActiveValue::NotSet]. + /// + /// See [ActiveValue::try_as_ref] for a fallible non-panicking version. fn as_ref(&self) -> &V { match self { ActiveValue::Set(value) | ActiveValue::Unchanged(value) => value,