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