Skip to content

Add map-like methods to AtomicRef(Mut) which work with new objects rather than references #11

Open
@LechintanTudor

Description

@LechintanTudor

Having map methods for reference types which can only work with sub-borrows of the original object is a bit too restrictive in my opinion, and it doesn't allow certain patterns as the one presented bellow. My solution is to add an additional method to all reference types, map_into, which can create entirely new objects with the same lifetime as the original. This change requires adding additional reference types that hold T's, instead of &(mut) T's, which I've called OwnedAtomicRef and OwnedAtomicRefMut.

Here is the problem that adding map_into would solve

let values: (Box<dyn Any>, Box<dyn Any>) = (Box::new(1_u32), Box::new(2_u32));
    let cell = AtomicRefCell::new(values);

    // Create an OwnedAtomicRefMut to hold our new object which borrows the original
    let mut borrowed_values = AtomicRefMut::map_into(cell.borrow_mut(), |values| {
        (
            Box::as_mut(&mut values.0).downcast_mut::<u32>().unwrap(),
            Box::as_mut(&mut values.1).downcast_mut::<u32>().unwrap(),
        )
    });
    
    // Set the values while still holding a lock
    *borrowed_values.0 = 100;
    *borrowed_values.1 = 200;

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions