Skip to main content

virtual_file_system/
readiness.rs

1use file_system::{AccessFlags, CharacterDevice, IoErrorKind, ReadyEvents};
2use synchronization::Arc;
3
4use crate::{ItemStatic, Result, SynchronousFile, pipe::Pipe};
5
6/// A readiness probe detached from the I/O context. Retaining this probe does
7/// not retain the opening or postpone pipe EOF. Character devices are static.
8#[derive(Clone)]
9pub struct FileReadiness {
10    source: Source,
11    access: AccessFlags,
12}
13
14#[derive(Clone)]
15enum Source {
16    Immediate,
17    Pipe(Arc<Pipe>),
18    Character(&'static dyn CharacterDevice),
19    Invalid,
20}
21
22impl FileReadiness {
23    pub fn is_pipe(&self) -> bool {
24        matches!(self.source, Source::Pipe(_))
25    }
26
27    /// Return the events and whether they came from a precise readiness probe.
28    pub fn events(&self, mut interests: ReadyEvents) -> Result<(ReadyEvents, bool)> {
29        interests.set(
30            ReadyEvents::READ,
31            interests.contains(ReadyEvents::READ) && self.access.contains(AccessFlags::Read),
32        );
33        interests.set(
34            ReadyEvents::WRITE,
35            interests.contains(ReadyEvents::WRITE) && self.access.contains(AccessFlags::Write),
36        );
37        match &self.source {
38            Source::Immediate => Ok((interests, true)),
39            Source::Pipe(pipe) => Ok((pipe.readiness(self.access, interests), true)),
40            Source::Character(device) => Ok(match device.readiness(interests)? {
41                Some(events) => (events, true),
42                None => (interests, false),
43            }),
44            Source::Invalid => Err(IoErrorKind::BadDescriptor),
45        }
46    }
47}
48
49impl SynchronousFile<'_> {
50    pub fn readiness(&self) -> FileReadiness {
51        let source = match &self.item {
52            ItemStatic::File(_) | ItemStatic::BlockDevice(_) => Source::Immediate,
53            ItemStatic::Pipe(pipe) => Source::Pipe(pipe.clone()),
54            ItemStatic::CharacterDevice(device) => Source::Character(*device),
55            _ => Source::Invalid,
56        };
57        FileReadiness {
58            source,
59            access: self.flags.get_access(),
60        }
61    }
62
63    pub fn pipe_bytes_available(&self) -> Result<usize> {
64        match &self.item {
65            ItemStatic::Pipe(pipe) => Ok(pipe.bytes_available()),
66            _ => Err(IoErrorKind::Unsupported),
67        }
68    }
69}