Skip to content

Commit e13752f

Browse files
committed
Implement Borrow on object types
The [`Borrow`](https://doc.rust-lang.org/std/borrow/trait.Borrow.html) trait is more restrictive than `AsRef`, but since `PartialOrd`, `Hash`, `PartialEq`, (...), are all implemented on the object pointer, it's safe, and I believe correct, to implement `Borrow`.
1 parent 5f883ca commit e13752f

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

glib/src/object.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -745,6 +745,7 @@ macro_rules! glib_object_wrapper {
745745
}
746746
}
747747

748+
748749
impl $(<$($generic $(: $bound $(+ $bound2)*)?),+>)? std::fmt::Debug for $name $(<$($generic),+>)? {
749750
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
750751
f.debug_struct(stringify!($name)).field("inner", &self.inner).finish()
@@ -1168,6 +1169,13 @@ macro_rules! glib_object_wrapper {
11681169
$crate::object::Cast::upcast_ref(self)
11691170
}
11701171
}
1172+
1173+
#[doc(hidden)]
1174+
impl $(<$($generic $(: $bound $(+ $bound2)*)?),+>)? std::borrow::Borrow<$super_name> for $name $(<$($generic),+>)? {
1175+
fn borrow(&self) -> &$super_name {
1176+
$crate::object::Cast::upcast_ref(self)
1177+
}
1178+
}
11711179
};
11721180

11731181
(@munch_impls $name:ident $(<$($generic:ident $(: $bound:tt $(+ $bound2:tt)*)?),+>)?, $super_name:path, $($implements:tt)*) => {
@@ -1237,6 +1245,13 @@ macro_rules! glib_object_wrapper {
12371245
}
12381246
}
12391247

1248+
#[doc(hidden)]
1249+
impl $(<$($generic $(: $bound $(+ $bound2)*)?),+>)? std::borrow::Borrow<$crate::object::Object> for $name $(<$($generic),+>)? {
1250+
fn borrow(&self) -> &$crate::object::Object {
1251+
$crate::object::Cast::upcast_ref(self)
1252+
}
1253+
}
1254+
12401255
#[doc(hidden)]
12411256
unsafe impl $(<$($generic $(: $bound $(+ $bound2)*)?),+>)? $crate::object::IsA<$crate::object::Object> for $name $(<$($generic),+>)? { }
12421257

@@ -4535,4 +4550,15 @@ mod tests {
45354550

45364551
assert_eq!(obj1.as_ptr(), obj2.as_ptr());
45374552
}
4553+
4554+
#[test]
4555+
fn test_borrow_hashing() {
4556+
let mut m = std::collections::HashSet::new();
4557+
let boxed_object = crate::BoxedAnyObject::new("");
4558+
4559+
m.insert(boxed_object.clone());
4560+
4561+
let object: &Object = std::borrow::Borrow::borrow(&boxed_object);
4562+
assert_eq!(m.get(object), Some(&boxed_object));
4563+
}
45384564
}

0 commit comments

Comments
 (0)