Skip to content

Commit 71082ae

Browse files
committed
Reduce the need for boilerplate code in simple drivers.
Provide a default `FileOpener` implementation for types that implement `Default`, whose wrappers are `Box`, and that have no per-device shared state. Make `Box` the default wrapper, so that drivers only need to define `Wrapper` if they need something different. Signed-off-by: Wedson Almeida Filho <[email protected]>
1 parent 3b8575d commit 71082ae

File tree

3 files changed

+10
-14
lines changed

3 files changed

+10
-14
lines changed

rust/kernel/file_operations.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -520,6 +520,12 @@ pub trait FileOpener<T: ?Sized>: FileOperations {
520520
fn open(context: &T) -> KernelResult<Self::Wrapper>;
521521
}
522522

523+
impl<T: FileOperations<Wrapper = Box<T>> + Default> FileOpener<()> for T {
524+
fn open(_: &()) -> KernelResult<Self::Wrapper> {
525+
Ok(Box::try_new(T::default())?)
526+
}
527+
}
528+
523529
/// Corresponds to the kernel's `struct file_operations`.
524530
///
525531
/// You implement this trait whenever you would create a `struct file_operations`.
@@ -532,7 +538,7 @@ pub trait FileOperations: Send + Sync + Sized {
532538
const TO_USE: ToUse;
533539

534540
/// The pointer type that will be used to hold ourselves.
535-
type Wrapper: PointerWrapper<Self>;
541+
type Wrapper: PointerWrapper<Self> = Box<Self>;
536542

537543
/// Cleans up after the last reference to the file goes away.
538544
///

rust/kernel/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
#![feature(
1616
allocator_api,
1717
alloc_error_handler,
18+
associated_type_defaults,
1819
const_fn,
1920
const_mut_refs,
2021
const_panic,

samples/rust/rust_chrdev.rs

Lines changed: 2 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,7 @@
88
use alloc::boxed::Box;
99
use core::pin::Pin;
1010
use kernel::prelude::*;
11-
use kernel::{
12-
chrdev, cstr,
13-
file_operations::{FileOpener, FileOperations},
14-
};
11+
use kernel::{chrdev, cstr, file_operations::FileOperations};
1512

1613
module! {
1714
type: RustChrdev,
@@ -23,18 +20,10 @@ module! {
2320
},
2421
}
2522

23+
#[derive(Default)]
2624
struct RustFile;
2725

28-
impl FileOpener<()> for RustFile {
29-
fn open(_ctx: &()) -> KernelResult<Self::Wrapper> {
30-
pr_info!("rust file was opened!\n");
31-
Ok(Box::try_new(Self)?)
32-
}
33-
}
34-
3526
impl FileOperations for RustFile {
36-
type Wrapper = Box<Self>;
37-
3827
kernel::declare_file_operations!();
3928
}
4029

0 commit comments

Comments
 (0)