]> www.infradead.org Git - users/jedix/linux-maple.git/commitdiff
rust: reduce the need for boilerplate code in simple drivers
authorWedson Almeida Filho <wedsonaf@google.com>
Fri, 23 Apr 2021 12:08:15 +0000 (13:08 +0100)
committerMiguel Ojeda <ojeda@kernel.org>
Tue, 27 Apr 2021 03:06:13 +0000 (05:06 +0200)
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 <wedsonaf@google.com>
[normalized title]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
rust/kernel/file_operations.rs
rust/kernel/lib.rs
samples/rust/rust_chrdev.rs

index f54ddd0b1da092bb2ed2e2bcf3e36bbb7153bc09..da13d4b6b0dbf74b4d4bde1186756ab0ffb93150 100644 (file)
@@ -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`.
@@ -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.
     ///
index c9ffeaae18a00fdef4162fca4f06434c2e6d06e0..8f5a637f41672dad93e88d7b5554cbdd771055a6 100644 (file)
@@ -15,6 +15,7 @@
 #![feature(
     allocator_api,
     alloc_error_handler,
+    associated_type_defaults,
     const_fn,
     const_mut_refs,
     const_panic,
index e3231c4f45046ccb021f881b4c9c5d803ff1c1e4..78423b1e3d116f9cddb21ce6cefa4d778cd3b84e 100644 (file)
@@ -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<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!();
 }