xref: /linux/rust/kernel/debugfs/traits.rs (revision 5e40b591cb46c0379d5406fa5548c9b2a3801353)
1 // SPDX-License-Identifier: GPL-2.0
2 // Copyright (C) 2025 Google LLC.
3 
4 //! Traits for rendering or updating values exported to DebugFS.
5 
6 use crate::sync::Mutex;
7 use core::fmt::{self, Debug, Formatter};
8 
9 /// A trait for types that can be written into a string.
10 ///
11 /// This works very similarly to `Debug`, and is automatically implemented if `Debug` is
12 /// implemented for a type. It is also implemented for any writable type inside a `Mutex`.
13 ///
14 /// The derived implementation of `Debug` [may
15 /// change](https://doc.rust-lang.org/std/fmt/trait.Debug.html#stability)
16 /// between Rust versions, so if stability is key for your use case, please implement `Writer`
17 /// explicitly instead.
18 pub trait Writer {
19     /// Formats the value using the given formatter.
20     fn write(&self, f: &mut Formatter<'_>) -> fmt::Result;
21 }
22 
23 impl<T: Writer> Writer for Mutex<T> {
24     fn write(&self, f: &mut Formatter<'_>) -> fmt::Result {
25         self.lock().write(f)
26     }
27 }
28 
29 impl<T: Debug> Writer for T {
30     fn write(&self, f: &mut Formatter<'_>) -> fmt::Result {
31         writeln!(f, "{self:?}")
32     }
33 }
34