From: Wedson Almeida Filho Date: Fri, 23 Apr 2021 12:08:15 +0000 (+0100) Subject: rust: reduce the need for boilerplate code in simple drivers X-Git-Url: https://www.infradead.org/git/?a=commitdiff_plain;h=89478a8ce0a2471876b39dd080e0a08d98a28ad9;p=users%2Fjedix%2Flinux-maple.git rust: 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 [normalized title] Signed-off-by: Miguel Ojeda --- diff --git a/rust/kernel/file_operations.rs b/rust/kernel/file_operations.rs index f54ddd0b1da09..da13d4b6b0dbf 100644 --- a/rust/kernel/file_operations.rs +++ b/rust/kernel/file_operations.rs @@ -520,6 +520,12 @@ pub trait FileOpener: FileOperations { fn open(context: &T) -> KernelResult; } +impl> + Default> FileOpener<()> for T { + fn open(_: &()) -> KernelResult { + 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`. @@ -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; + type Wrapper: PointerWrapper = Box; /// Cleans up after the last reference to the file goes away. /// diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index c9ffeaae18a00..8f5a637f41672 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -15,6 +15,7 @@ #![feature( allocator_api, alloc_error_handler, + associated_type_defaults, const_fn, const_mut_refs, const_panic, diff --git a/samples/rust/rust_chrdev.rs b/samples/rust/rust_chrdev.rs index e3231c4f45046..78423b1e3d116 100644 --- a/samples/rust/rust_chrdev.rs +++ b/samples/rust/rust_chrdev.rs @@ -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, @@ -23,18 +20,10 @@ module! { }, } +#[derive(Default)] struct RustFile; -impl FileOpener<()> for RustFile { - fn open(_ctx: &()) -> KernelResult { - pr_info!("rust file was opened!\n"); - Ok(Box::try_new(Self)?) - } -} - impl FileOperations for RustFile { - type Wrapper = Box; - kernel::declare_file_operations!(); }