nebgnahz / cv-rs

Rust wrapper for OpenCV (manual at this point)
https://nebgnahz.github.io/cv-rs/cv/
MIT License
204 stars 41 forks source link

Mat should have non-owning counterpart #110

Open vadixidav opened 5 years ago

vadixidav commented 5 years ago

In the documentation I found from_buffer. This method indicates that it is possible to actually invoke a double-free without doing anything. Additionally, the source of from_buffer doesn't check to see if the slice is big enough! This means that undefined behavior and segfaults could happen.

To fix this, we should create a SliceMat. This would be a cv::Mat that does not own its data. It would be templated with a lifetime param <'a> so that when it is created from a slice it wont be allowed to outlive the slice due to the Rust borrow checker. We then also need to make a newtype wrapper around just the cv::Mat pointer that opencv has and move all the shared functionality we have into there. We can call this wrapper MatRef. We then impl Deref<MatRef> for Mat and impl Deref<MatRef> for SliceMat.

Pzixel commented 5 years ago

IIRC from_buffer copies its data but I may be wrong here.

Checking array length cannot be done before Mat is constructed because different CvType require different buffer size. Only opencv itself could tell us if buffer if big enough so I think it's better to just handle OutOfBoundException in C++ or something, and return Result istead of mat.

vadixidav commented 5 years ago

Oh, I see, so right now it is just undefined behavior if your buffer is the wrong size. I will create the appropriate unit tests then and change this to get back a Result.

Pzixel commented 5 years ago

There are some hepers class (CResult, in instance) that helps you to convert C++ Exception into rust Result. See https://github.com/nebgnahz/cv-rs/blob/b60210381ef21198cf842bfeab398b077085f0f9/native/common.h#L68-L87