11#![ cfg( all( feature = "std" , feature = "lender" ) ) ]
22
33use lazy_static:: lazy_static;
4- use std:: collections:: HashSet ;
4+ use std:: any:: TypeId ;
5+ use std:: collections:: HashMap ;
56use std:: sync:: { RwLock , RwLockWriteGuard } ;
67
78use crate :: error:: PointerError ;
89
910lazy_static ! {
10- static ref LENT_POINTERS : RwLock <HashSet <usize >> = RwLock :: new( HashSet :: new( ) ) ;
11+ static ref LENT_POINTERS : RwLock <HashMap <usize , TypeId >> = RwLock :: new( HashMap :: new( ) ) ;
1112}
1213
1314/// Check if a pointer was [`lent`](lend).
@@ -17,12 +18,13 @@ lazy_static! {
1718/// If the [`RwLock`] used is poisoned, but it only happens if a panic happens
1819/// while holding it. And it's specially reviewed and in a small module to
1920/// avoid panics while holding it.
20- pub ( super ) fn is_lent < T > ( pointer : * const T ) -> bool {
21+ pub ( super ) fn lent_type_of < T > ( pointer : * const T ) -> Option < TypeId > {
2122 let Ok ( lent_pointers) = LENT_POINTERS . read ( ) else {
2223 log:: error!( "RwLock poisoned, it is not possible to check pointers" ) ;
2324 unreachable ! ( ) ;
2425 } ;
25- return lent_pointers. contains ( & ( pointer as usize ) ) ;
26+
27+ lent_pointers. get ( & ( pointer as usize ) ) . copied ( )
2628}
2729
2830/// Use only when lend memory as a [`raw`](crate::raw) pointer.
@@ -32,15 +34,16 @@ pub(super) fn is_lent<T>(pointer: *const T) -> bool {
3234/// If the [`RwLock`] used is poisoned, but it only happens if a panic happens
3335/// while holding it. And it's specially reviewed and in a small module to
3436/// avoid panics while holding it.
35- pub ( super ) fn lend < T > ( pointer : * const T ) -> Result < ( ) , PointerError > {
37+ pub ( super ) fn lend < T : ' static > ( pointer : * const T ) -> Result < ( ) , PointerError > {
3638 let mut lent_pointers = writable_lent_pointers ( ) ;
3739
3840 if let Err ( error) = lent_pointers. try_reserve ( 1 ) {
3941 log:: error!( "Can not alloc memory to lent a pointer: {error}" ) ;
4042 return Err ( PointerError :: from ( error) ) ;
4143 }
42- lent_pointers. insert ( pointer as usize ) ;
43- return Ok ( ( ) ) ;
44+
45+ lent_pointers. insert ( pointer as usize , TypeId :: of :: < T > ( ) ) ;
46+ Ok ( ( ) )
4447}
4548
4649/// Use only when [`own_back`](crate::own_back) memory.
@@ -54,7 +57,7 @@ pub(super) fn retrieve<T>(pointer: *const T) {
5457 writable_lent_pointers ( ) . remove ( & ( pointer as usize ) ) ;
5558}
5659
57- fn writable_lent_pointers ( ) -> RwLockWriteGuard < ' static , HashSet < usize > > {
60+ fn writable_lent_pointers ( ) -> RwLockWriteGuard < ' static , HashMap < usize , TypeId > > {
5861 let Ok ( lent_pointers) = LENT_POINTERS . write ( ) else {
5962 log:: error!( "RwLock poisoned, it is not possible to add or remove pointers" ) ;
6063 unreachable ! ( ) ;
0 commit comments