Include MappedRwLocKWriteGuard from lock_api or parking_lot · Issue #260 · rust-lang/libs-team (original) (raw)

Proposal

Problem statement

In case a multi-level representation in a struct, I'd like to expose the as minimal interface as I can. Guarding the enclosed data in a granular way with RwLock requires part of the structure to be enclosed in it. For the desired granularity RwLock might be present at whatever level of an internal structure, i.e. an RwLock<> might contain an internal struct or enum which should not be exposed to the public implementation interface of the type, however the data contained in these internal structures should be.

Motivating examples or use cases

enum Container<T>{
    Empty, Emptied, Full(T)
}

use std::sync::{RwLock, RwLockReadGuard};

struct Ship<T>{
    content: Vec<RwLock<Container<T>>>
}

impl<T> Ship<T>{

    pub fn get_enum(&self, index: usize) -> Option<RwLockReadGuard<'_, Container<T>>>{
       self.content[index].read().ok()
    }

    // The below code fails to compile: 
    // pub fn get(&self, index: usize) -> Option<&T>{
    //   match self.content[index].borrow().ok().unwrap() {
    //       Container::Full(c) => Some(c), 
    //       _=> None
    //   }
    // }
    
    pub fn get_mut(&mut self, index: usize) -> Option<&mut T>{
       match self.content[index].get_mut().ok().unwrap() {
           Container::Full(c) => Some(c), 
           _=> None
       }
    }
}

Solution sketch

Both lock_api and parking_slot crates have the solution implemented in them:
https://docs.rs/parking_lot/latest/parking_lot/type.MappedRwLockWriteGuard.html
https://docs.rs/lock_api/latest/lock_api/struct.MappedRwLockWriteGuard.html

Alternatives

As of now limiting structure for RwLock to only contain what is to be exposed to the public interface.

Related SO Question:
https://stackoverflow.com/questions/76943416/rust-destructure-enum-protected-by-stdsyncrwlock-return-with-reference?noredirect=1#76943458

What happens now?

This issue is part of the libs-api team API change proposal process. Once this issue is filed the libs-api team will review open proposals as capability becomes available. Current response times do not have a clear estimate, but may be up to several months.

Possible responses

The libs team may respond in various different ways. First, the team will consider the problem (this doesn't require any concrete solution or alternatives to have been proposed):

Second, if there's a concrete solution: