Skip to content

Commit

Permalink
5: read and write
Browse files Browse the repository at this point in the history
  • Loading branch information
jackos committed Jul 31, 2022
1 parent bac10ca commit eaa80f9
Showing 1 changed file with 45 additions and 5 deletions.
50 changes: 45 additions & 5 deletions samples/rust/rust_vdev.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,34 +2,74 @@
use kernel::prelude::*;

use kernel::file::{File, Operations};
use kernel::io_buffer::{IoBufferReader, IoBufferWriter};
use kernel::sync::smutex::Mutex;
use kernel::sync::{Ref, RefBorrow};
use kernel::{miscdev, Module};

module! {
type: VDev,
name: b"vdev",
license: b"GPL",
}
struct Device {
number: usize,
contents: Mutex<Vec<u8>>,
}

struct VDev {
_dev: Pin<Box<miscdev::Registration<VDev>>>,
}

#[vtable]
impl Operations for VDev {
fn open(_context: &(), _file: &File) -> Result {
pr_info!("File was opened\n");
Ok(())
type OpenData = Ref<Device>;
type Data = Ref<Device>;

fn open(context: &Ref<Device>, _file: &File) -> Result<Ref<Device>> {
pr_info!("File for device {} was opened\n", context.number);
Ok(context.clone())
}

fn read(
data: RefBorrow<'_, Device>,
_file: &File,
writer: &mut impl IoBufferWriter,
offset: u64,
) -> Result<usize> {
pr_info!("File for device {} was read\n", data.number);
let offset = offset.try_into()?;
let vec = data.contents.lock();
let len = core::cmp::min(writer.len(), vec.len().saturating_sub(offset));
writer.write_slice(&vec[offset..][..len])?;
Ok(len)
}

fn write(
data: RefBorrow<'_, Device>,
_file: &File,
reader: &mut impl IoBufferReader,
_offset: u64,
) -> Result<usize> {
pr_info!("File for device {} was written\n", data.number);
let copy = reader.read_all()?;
let len = copy.len();
*data.contents.lock() = copy;
Ok(len)
}
}

impl Module for VDev {
fn init(_name: &'static CStr, _module: &'static ThisModule) -> Result<Self> {
// Print a banner to make sure our moudle is working
pr_info!("-----------------------\n");
pr_info!("initialize vdev module!\n");
pr_info!("watching for changes...\n");
pr_info!("-----------------------\n");
let reg = miscdev::Registration::new_pinned(fmt!("vdev"), ())?;
let dev = Ref::try_new(Device {
number: 0,
contents: Mutex::new(Vec::new()),
})?;
let reg = miscdev::Registration::new_pinned(fmt!("vdev"), dev)?;
Ok(Self { _dev: reg })
}
}

0 comments on commit eaa80f9

Please sign in to comment.