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::errors::Errno;
12use std::borrow::Cow;
13use std::panic::Location;
14use std::sync::Arc;
15
16#[derive(Clone)]
17pub struct StubBytesFile {
18    data: Arc<Mutex<Vec<u8>>>,
19    bug: BugRef,
20    location: &'static Location<'static>,
21}
22
23impl StubBytesFile {
24    #[track_caller]
25    pub fn new_node(bug: BugRef) -> impl FsNodeOps {
26        Self::new_node_with_data(bug, vec![])
27    }
28
29    #[track_caller]
30    pub fn new_node_with_data(bug: BugRef, initial_data: impl Into<Vec<u8>>) -> impl FsNodeOps {
31        let location = Location::caller();
32        let file = BytesFile::new(StubBytesFile {
33            data: Arc::new(Mutex::new(initial_data.into())),
34            bug,
35            location,
36        });
37        SimpleFileNode::new(move |_, _| Ok(file.clone()))
38    }
39}
40
41impl BytesFileOps for StubBytesFile {
42    fn write(&self, _current_task: &CurrentTask, data: Vec<u8>) -> Result<(), Errno> {
43        *self.data.lock() = data;
44        Ok(())
45    }
46    fn read(&self, _current_task: &CurrentTask) -> Result<Cow<'_, [u8]>, Errno> {
47        Ok(self.data.lock().clone().into())
48    }
49
50    fn open(
51        &self,
52        _locked: &mut Locked<FileOpsCore>,
53        file: &FileObject,
54        current_task: &CurrentTask,
55    ) -> Result<(), Errno> {
56        let path = file.name.path(current_task);
57        starnix_logging::__track_stub_inner(
58            self.bug,
59            path.to_str_lossy().as_ref(),
60            None,
61            self.location,
62        );
63        Ok(())
64    }
65}