Skip to content

Commit acd9fd1

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 8310180 commit acd9fd1

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
@@ -746,6 +746,7 @@ macro_rules! glib_object_wrapper {
746746
}
747747
}
748748

749+
749750
impl $(<$($generic $(: $bound $(+ $bound2)*)?),+>)? std::fmt::Debug for $name $(<$($generic),+>)? {
750751
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
751752
f.debug_struct(stringify!($name)).field("inner", &self.inner).finish()
@@ -1175,6 +1176,13 @@ macro_rules! glib_object_wrapper {
11751176
$crate::object::Cast::upcast_ref(self)
11761177
}
11771178
}
1179+
1180+
#[doc(hidden)]
1181+
impl $(<$($generic $(: $bound $(+ $bound2)*)?),+>)? std::borrow::Borrow<$super_name> for $name $(<$($generic),+>)? {
1182+
fn borrow(&self) -> &$super_name {
1183+
$crate::object::Cast::upcast_ref(self)
1184+
}
1185+
}
11781186
};
11791187

11801188
(@munch_impls $name:ident $(<$($generic:ident $(: $bound:tt $(+ $bound2:tt)*)?),+>)?, $super_name:path, $($implements:tt)*) => {
@@ -1244,6 +1252,13 @@ macro_rules! glib_object_wrapper {
12441252
}
12451253
}
12461254

1255+
#[doc(hidden)]
1256+
impl $(<$($generic $(: $bound $(+ $bound2)*)?),+>)? std::borrow::Borrow<$crate::object::Object> for $name $(<$($generic),+>)? {
1257+
fn borrow(&self) -> &$crate::object::Object {
1258+
$crate::object::Cast::upcast_ref(self)
1259+
}
1260+
}
1261+
12471262
#[doc(hidden)]
12481263
unsafe impl $(<$($generic $(: $bound $(+ $bound2)*)?),+>)? $crate::object::IsA<$crate::object::Object> for $name $(<$($generic),+>)? { }
12491264

@@ -4636,4 +4651,15 @@ mod tests {
46364651

46374652
assert_eq!(obj1.as_ptr(), obj2.as_ptr());
46384653
}
4654+
4655+
#[test]
4656+
fn test_borrow_hashing() {
4657+
let mut m = std::collections::HashSet::new();
4658+
let boxed_object = crate::BoxedAnyObject::new("");
4659+
4660+
m.insert(boxed_object.clone());
4661+
4662+
let object: &Object = std::borrow::Borrow::borrow(&boxed_object);
4663+
assert_eq!(m.get(object), Some(&boxed_object));
4664+
}
46394665
}

0 commit comments

Comments
 (0)