opencv/manual/core/
inplace.rs

1use crate::boxed_ref::BoxedRefMut;
2use crate::traits::Boxed;
3
4pub trait ModifyInplace {
5	/// Helper function to call OpenCV functions that allow in-place modification of a `Mat` or another similar object. By passing
6	/// a mutable reference to the `Mat` to this function your closure will get called with the read reference and a write references
7	/// to the same `Mat`. This is unsafe in a general case as it leads to having non-exclusive mutable access to the internal data,
8	/// but it can be useful for some performance sensitive operations. One example of an OpenCV function that allows such in-place
9	/// modification is `imgproc::threshold`.
10	///
11	/// # Safety
12	/// Caller must make sure that any functions called inside the closure can act on a `Mat` in-place.
13	unsafe fn modify_inplace<Res>(&mut self, f: impl FnOnce(&Self, &mut Self) -> Res) -> Res;
14}
15
16impl<Mat: Boxed> ModifyInplace for Mat {
17	#[inline(always)]
18	unsafe fn modify_inplace<Res>(&mut self, f: impl FnOnce(&Self, &mut Self) -> Res) -> Res {
19		let mut m_alias = unsafe { Mat::from_raw(self.as_raw_mut()) };
20		let out = f(self, &mut m_alias);
21		// prevent running destructor on m_alias
22		let _ = m_alias.into_raw();
23		out
24	}
25}
26
27impl<Mat: Boxed> ModifyInplace for BoxedRefMut<'_, Mat> {
28	#[inline(always)]
29	unsafe fn modify_inplace<Res>(&mut self, f: impl FnOnce(&Self, &mut Self) -> Res) -> Res {
30		let mut m_alias = BoxedRefMut::from(unsafe { Mat::from_raw(self.reference.as_raw_mut()) });
31		let out = f(self, &mut m_alias);
32		// prevent running destructor on m_alias
33		let _ = m_alias.reference.into_raw();
34		out
35	}
36}