Skip to content

Commit 35691a4

Browse files
Timgrauintel-lab-lkp
authored andcommitted
rust: types: 'real-life' example for Either
Added a 'real-life' example for the type `Either`. This example uses a work queue and extends the first example in `workqueue.rs` (commit ID: 15b286d) to demonstrate how to hold and distinguish between two different data types. Suggested-by: Miguel Ojeda <ojeda@kernel.org> Link: Rust-for-Linux#1122 Signed-off-by: Timo Grautstueck <timo.grautstueck@web.de>
1 parent 673d164 commit 35691a4

1 file changed

Lines changed: 54 additions & 0 deletions

File tree

rust/kernel/types.rs

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -322,6 +322,60 @@ impl<T> Opaque<T> {
322322
/// let left_value: Either<i32, &str> = Either::Left(7);
323323
/// let right_value: Either<i32, &str> = Either::Right("right value");
324324
/// ```
325+
///
326+
/// The following example demonstrates how we can create a struct
327+
/// that uses `Either` to hold either an integer or a string.
328+
/// This struct will be scheduled on the workqueue, and when executed,
329+
/// we will perform different actions depending on whether it holds
330+
/// a `Left` value (integer) or a `Right` value (string).
331+
///
332+
/// ```
333+
/// use kernel::prelude::*;
334+
/// use kernel::sync::Arc;
335+
/// use kernel::types::Either;
336+
/// use kernel::workqueue::{self, new_work, Work, WorkItem};
337+
///
338+
/// #[pin_data]
339+
/// struct WorkStruct {
340+
/// value: Either<i32, &'static str>,
341+
/// #[pin]
342+
/// work: Work<WorkStruct>,
343+
/// }
344+
///
345+
/// impl_has_work! {
346+
/// impl HasWork<Self> for WorkStruct { self.work }
347+
/// }
348+
///
349+
/// impl WorkStruct {
350+
/// fn new(value: Either<i32, &'static str>) -> Result<Arc<Self>> {
351+
/// Arc::pin_init(pin_init!(WorkStruct {
352+
/// value,
353+
/// work <- new_work!("WorkStruct::work"),
354+
/// }), GFP_KERNEL)
355+
/// }
356+
/// }
357+
///
358+
/// impl WorkItem for WorkStruct {
359+
/// type Pointer = Arc<WorkStruct>;
360+
///
361+
/// fn run(this: Arc<WorkStruct>) {
362+
/// match &this.value {
363+
/// Either::Left(left_value) => {
364+
/// pr_info!("Left value: {}", left_value);
365+
/// pr_info!("Left value times two: {}", left_value << 1);
366+
/// }
367+
/// Either::Right(right_value) => {
368+
/// pr_info!("Right value: {}", right_value);
369+
/// pr_info!("Length of right value: {}", right_value.len());
370+
/// }
371+
/// }
372+
/// }
373+
/// }
374+
///
375+
/// fn enqueue_work(work_item: Arc<WorkStruct>) {
376+
/// let _ = workqueue::system().enqueue(work_item);
377+
/// }
378+
/// ```
325379
pub enum Either<L, R> {
326380
/// Constructs an instance of [`Either`] containing a value of type `L`.
327381
Left(L),

0 commit comments

Comments
 (0)