yoshuawuyts / fd-lock

Advisory cross-platform file locks using file descriptors
Apache License 2.0
76 stars 18 forks source link

mutable read guard #44

Closed tzemanovic closed 1 year ago

tzemanovic commented 1 year ago

Hi,

Thanks for this crate! I have a question - I'm finding it a bit impractical that the read guard doesn't have mutable access as e.g. reading from a file requires it (all the read methods in std::io::Read use &mut self). Because there's no DerefMut, it's not possible to call these directly on the guard without e.g. wrapping it in BufReader first, e.g.:

        let lock = RwLock::new(File::open(path).unwrap());
        let mut guard = lock.try_read().unwrap();
        let mut read = vec![];
        // doesn't compile
        guard.read_to_end(&mut read).unwrap();

Is this intended? I see that you want to allow shared read access which makes sense, but perhaps a lock/guard does not need to be re-used for that so allowing a mutable access for reading might have a more ergonomic api. Wdyt?

yoshuawuyts commented 1 year ago

Hey there, thanks for filing this issue! The Read trait is implemented for &File. Try changing your code to the following:

+use std::ops::Deref;
let lock = RwLock::new(File::open(path).unwrap());
- let mut guard = lock.try_read().unwrap();
+ let guard = lock.try_read().unwrap();
let mut read = vec![];
- guard.read_to_end(&mut read).unwrap();
+ guard.deref().read_to_end(&mut read).unwrap();
tzemanovic commented 1 year ago

I see, thank you! It’s a shame that the auto-deref doesn’t work for it