Skip to content

Commit

Permalink
Merge pull request torvalds#218 from wedsonaf/boilerplate
Browse files Browse the repository at this point in the history
Reduce the need for boilerplate code in simple drivers.
  • Loading branch information
ojeda authored Apr 23, 2021
2 parents 75cb572 + 012baf8 commit bb368ad
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 14 deletions.
8 changes: 7 additions & 1 deletion rust/kernel/file_operations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -520,6 +520,12 @@ pub trait FileOpener<T: ?Sized>: FileOperations {
fn open(context: &T) -> KernelResult<Self::Wrapper>;
}

impl<T: FileOperations<Wrapper = Box<T>> + Default> FileOpener<()> for T {
fn open(_: &()) -> KernelResult<Self::Wrapper> {
Ok(Box::try_new(T::default())?)
}
}

/// Corresponds to the kernel's `struct file_operations`.
///
/// You implement this trait whenever you would create a `struct file_operations`.
Expand All @@ -532,7 +538,7 @@ pub trait FileOperations: Send + Sync + Sized {
const TO_USE: ToUse;

/// The pointer type that will be used to hold ourselves.
type Wrapper: PointerWrapper<Self>;
type Wrapper: PointerWrapper<Self> = Box<Self>;

/// Cleans up after the last reference to the file goes away.
///
Expand Down
1 change: 1 addition & 0 deletions rust/kernel/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
#![feature(
allocator_api,
alloc_error_handler,
associated_type_defaults,
const_fn,
const_mut_refs,
const_panic,
Expand Down
15 changes: 2 additions & 13 deletions samples/rust/rust_chrdev.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,7 @@
use alloc::boxed::Box;
use core::pin::Pin;
use kernel::prelude::*;
use kernel::{
chrdev, cstr,
file_operations::{FileOpener, FileOperations},
};
use kernel::{chrdev, cstr, file_operations::FileOperations};

module! {
type: RustChrdev,
Expand All @@ -23,18 +20,10 @@ module! {
},
}

#[derive(Default)]
struct RustFile;

impl FileOpener<()> for RustFile {
fn open(_ctx: &()) -> KernelResult<Self::Wrapper> {
pr_info!("rust file was opened!\n");
Ok(Box::try_new(Self)?)
}
}

impl FileOperations for RustFile {
type Wrapper = Box<Self>;

kernel::declare_file_operations!();
}

Expand Down

0 comments on commit bb368ad

Please sign in to comment.