starnix_core/vfs/pseudo/
stub_bytes_file.rs

1// Copyright 2025 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use crate::task::CurrentTask;
6use crate::vfs::pseudo::simple_file::{BytesFile, BytesFileOps, SimpleFileNode};
7use crate::vfs::{FileObject, FsNodeOps};
8use bstr::ByteSlice;
9use starnix_logging::BugRef;
10use starnix_sync::{FileOpsCore, Locked, Mutex};
11use starnix_uapi::auth::Capabilities;
12use starnix_uapi::errors::Errno;
13use std::borrow::Cow;
14use std::panic::Location;
15use std::sync::Arc;
16
17#[derive(Clone)]
18pub struct StubBytesFile {
19    data: Arc<Mutex<Vec<u8>>>,
20    bug: BugRef,
21    location: &'static Location<'static>,
22}
23
24impl StubBytesFile {
25    #[track_caller]
26    pub fn new_node(bug: BugRef) -> impl FsNodeOps {
27        Self::new_node_with_data(bug, vec![])
28    }
29
30    #[track_caller]
31    pub fn new_node_with_data(bug: BugRef, initial_data: impl Into<Vec<u8>>) -> impl FsNodeOps {
32        let location = Location::caller();
33        let file = BytesFile::new(StubBytesFile {
34            data: Arc::new(Mutex::new(initial_data.into())),
35            bug,
36            location,
37        });
38        SimpleFileNode::new(move || Ok(file.clone()))
39    }
40
41    #[track_caller]
42    pub fn new_node_with_capabilities(bug: BugRef, capabilities: Capabilities) -> impl FsNodeOps {
43        let location = Location::caller();
44        let file =
45            BytesFile::new(StubBytesFile { data: Arc::new(Mutex::new(vec![])), bug, location });
46        SimpleFileNode::new_with_capabilities(move || Ok(file.clone()), capabilities)
47    }
48}
49
50impl BytesFileOps for StubBytesFile {
51    fn write(&self, _current_task: &CurrentTask, data: Vec<u8>) -> Result<(), Errno> {
52        *self.data.lock() = data;
53        Ok(())
54    }
55    fn read(&self, _current_task: &CurrentTask) -> Result<Cow<'_, [u8]>, Errno> {
56        Ok(self.data.lock().clone().into())
57    }
58
59    fn open(
60        &self,
61        _locked: &mut Locked<FileOpsCore>,
62        file: &FileObject,
63        current_task: &CurrentTask,
64    ) -> Result<(), Errno> {
65        let path = file.name.path(current_task);
66        starnix_logging::__track_stub_inner(
67            self.bug,
68            path.to_str_lossy().as_ref(),
69            None,
70            self.location,
71        );
72        Ok(())
73    }
74}