Skip to content

Commit ed3c7bf

Browse files
authored
Use with_mut/with for Ptr::write/Ptr::read (#292)
This just simplifies the implementation of Ptr::write/Ptr::read
1 parent 4bdef2b commit ed3c7bf

1 file changed

Lines changed: 4 additions & 41 deletions

File tree

‎libcc2rs/src/rc.rs‎

Lines changed: 4 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -368,26 +368,7 @@ impl<T> Ptr<T> {
368368
where
369369
T: ByteRepr,
370370
{
371-
match &self.kind {
372-
PtrKind::Null => panic!("ub: null pointer"),
373-
PtrKind::StackSingle(weak) | PtrKind::HeapSingle(weak) => {
374-
let rc = weak.upgrade().expect("ub: dangling pointer");
375-
*rc.borrow_mut() = value;
376-
}
377-
PtrKind::Vec(weak) => {
378-
let rc = weak.upgrade().expect("ub: dangling pointer");
379-
rc.borrow_mut()[self.offset] = value;
380-
}
381-
PtrKind::StackArray(weak) | PtrKind::HeapArray(weak) => {
382-
let rc = weak.upgrade().expect("ub: dangling pointer");
383-
rc.borrow_mut()[self.offset] = value;
384-
}
385-
PtrKind::Reinterpreted(data) => {
386-
let mut buf = vec![0u8; T::byte_size()];
387-
value.to_bytes(&mut buf);
388-
data.alloc.write_bytes(self.offset, &buf);
389-
}
390-
}
371+
self.with_mut(|v| *v = value);
391372
}
392373

393374
pub fn to_strong(&self) -> Value<T> {
@@ -448,6 +429,7 @@ impl<T> Ptr<T> {
448429
match &self.kind {
449430
PtrKind::Null => panic!("ub: null pointer"),
450431
PtrKind::StackSingle(weak) | PtrKind::HeapSingle(weak) => {
432+
assert_eq!(self.offset, 0, "ub: invalid offset");
451433
let rc = weak.upgrade().expect("ub: dangling pointer");
452434
let mut borrow = rc.borrow_mut();
453435
f(&mut *borrow)
@@ -481,6 +463,7 @@ impl<T> Ptr<T> {
481463
match &self.kind {
482464
PtrKind::Null => panic!("ub: null pointer"),
483465
PtrKind::StackSingle(weak) | PtrKind::HeapSingle(weak) => {
466+
assert_eq!(self.offset, 0, "ub: invalid offset");
484467
let rc = weak.upgrade().expect("ub: dangling pointer");
485468
let borrow = rc.borrow();
486469
f(&*borrow)
@@ -507,27 +490,7 @@ impl<T> Ptr<T> {
507490

508491
impl<T: Clone + ByteRepr> Ptr<T> {
509492
pub fn read(&self) -> T {
510-
match self.kind {
511-
PtrKind::Null => panic!("ub: null pointer"),
512-
PtrKind::StackSingle(ref weak) | PtrKind::HeapSingle(ref weak) => {
513-
assert_eq!(self.offset, 0, "ub: invalid offset");
514-
weak.upgrade()
515-
.expect("ub: dangling pointer")
516-
.borrow()
517-
.clone()
518-
}
519-
PtrKind::Vec(ref weak) => {
520-
weak.upgrade().expect("ub: dangling pointer").borrow()[self.offset].clone()
521-
}
522-
PtrKind::StackArray(ref weak) | PtrKind::HeapArray(ref weak) => {
523-
weak.upgrade().expect("ub: dangling pointer").borrow()[self.offset].clone()
524-
}
525-
PtrKind::Reinterpreted(ref data) => {
526-
let mut buf = vec![0u8; T::byte_size()];
527-
data.alloc.read_bytes(self.offset, &mut buf);
528-
T::from_bytes(&buf)
529-
}
530-
}
493+
self.with(|v| v.clone())
531494
}
532495
}
533496

0 commit comments

Comments
 (0)