@@ -950,6 +950,64 @@ thread_local! {
950950}
951951
952952impl Ptr < u8 > {
953+ pub fn with_slice_mut < R > ( & self , len : usize , f : impl FnOnce ( & mut [ u8 ] ) -> R ) -> R {
954+ let off = self . offset ;
955+ match & self . kind {
956+ PtrKind :: Null => panic ! ( "ub: null pointer" ) ,
957+ PtrKind :: StackSingle ( weak) | PtrKind :: HeapSingle ( weak) => {
958+ assert ! ( off == 0 && len <= 1 , "ub: with_slice_mut out of bounds" ) ;
959+ let rc = weak. upgrade ( ) . expect ( "ub: dangling pointer" ) ;
960+ let mut b = rc. borrow_mut ( ) ;
961+ f ( & mut std:: slice:: from_mut ( & mut * b) [ ..len] )
962+ }
963+ PtrKind :: StackArray ( weak) | PtrKind :: HeapArray ( weak) => {
964+ let rc = weak. upgrade ( ) . expect ( "ub: dangling pointer" ) ;
965+ let mut b = rc. borrow_mut ( ) ;
966+ f ( & mut b[ off..off + len] )
967+ }
968+ PtrKind :: Vec ( weak) => {
969+ let rc = weak. upgrade ( ) . expect ( "ub: dangling pointer" ) ;
970+ let mut b = rc. borrow_mut ( ) ;
971+ f ( & mut b[ off..off + len] )
972+ }
973+ PtrKind :: Reinterpreted ( data) => {
974+ let mut buf = vec ! [ 0u8 ; len] ;
975+ data. alloc . read_bytes ( off, & mut buf) ;
976+ let r = f ( & mut buf) ;
977+ data. alloc . write_bytes ( off, & buf) ;
978+ r
979+ }
980+ }
981+ }
982+
983+ pub fn with_slice < R > ( & self , len : usize , f : impl FnOnce ( & [ u8 ] ) -> R ) -> R {
984+ let off = self . offset ;
985+ match & self . kind {
986+ PtrKind :: Null => panic ! ( "ub: null pointer" ) ,
987+ PtrKind :: StackSingle ( weak) | PtrKind :: HeapSingle ( weak) => {
988+ assert ! ( off == 0 && len <= 1 , "ub: with_slice out of bounds" ) ;
989+ let rc = weak. upgrade ( ) . expect ( "ub: dangling pointer" ) ;
990+ let b = rc. borrow ( ) ;
991+ f ( & std:: slice:: from_ref ( & * b) [ ..len] )
992+ }
993+ PtrKind :: StackArray ( weak) | PtrKind :: HeapArray ( weak) => {
994+ let rc = weak. upgrade ( ) . expect ( "ub: dangling pointer" ) ;
995+ let b = rc. borrow ( ) ;
996+ f ( & b[ off..off + len] )
997+ }
998+ PtrKind :: Vec ( weak) => {
999+ let rc = weak. upgrade ( ) . expect ( "ub: dangling pointer" ) ;
1000+ let b = rc. borrow ( ) ;
1001+ f ( & b[ off..off + len] )
1002+ }
1003+ PtrKind :: Reinterpreted ( data) => {
1004+ let mut buf = vec ! [ 0u8 ; len] ;
1005+ data. alloc . read_bytes ( off, & mut buf) ;
1006+ f ( & buf)
1007+ }
1008+ }
1009+ }
1010+
9531011 #[ allow( clippy:: explicit_counter_loop) ]
9541012 pub fn memcpy ( & self , src : & Self , len : usize ) {
9551013 let mut dst = self . clone ( ) ;
0 commit comments