Skip to content

Commit b455d0a

Browse files
authored
Merge pull request #95 from dtolnay/deref
Deref and DerefMut for UniquePtr
2 parents ad26677 + b5609f8 commit b455d0a

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

src/unique_ptr.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use std::ffi::c_void;
33
use std::fmt::{self, Debug, Display};
44
use std::marker::PhantomData;
55
use std::mem;
6+
use std::ops::{Deref, DerefMut};
67
use std::ptr;
78

89
/// Binding to C++ `std::unique_ptr<T, std::default_delete<T>>`.
@@ -94,6 +95,32 @@ where
9495
}
9596
}
9697

98+
impl<T> Deref for UniquePtr<T>
99+
where
100+
T: UniquePtrTarget,
101+
{
102+
type Target = T;
103+
104+
fn deref(&self) -> &Self::Target {
105+
match self.as_ref() {
106+
Some(target) => target,
107+
None => panic!("called deref on a null UniquePtr<{}>", T::__NAME),
108+
}
109+
}
110+
}
111+
112+
impl<T> DerefMut for UniquePtr<T>
113+
where
114+
T: UniquePtrTarget,
115+
{
116+
fn deref_mut(&mut self) -> &mut Self::Target {
117+
match self.as_mut() {
118+
Some(target) => target,
119+
None => panic!("called deref_mut on a null UniquePtr<{}>", T::__NAME),
120+
}
121+
}
122+
}
123+
97124
impl<T> Debug for UniquePtr<T>
98125
where
99126
T: Debug + UniquePtrTarget,

tests/unique_ptr.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
use cxx::{CxxString, UniquePtr};
2+
3+
#[test]
4+
#[should_panic = "called deref on a null UniquePtr<CxxString>"]
5+
fn test_deref_null() {
6+
let unique_ptr = UniquePtr::<CxxString>::null();
7+
let _: &CxxString = &unique_ptr;
8+
}

0 commit comments

Comments
 (0)