xref: /linux/rust/kernel/debugfs/traits.rs (revision 9c804d9cf2dbe90cfde89c905b45aacbd07ee537)
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::fs::file;
7 use crate::prelude::*;
8 use crate::sync::Mutex;
9 use crate::transmute::{AsBytes, FromBytes};
10 use crate::uaccess::{UserSliceReader, UserSliceWriter};
11 use core::fmt::{self, Debug, Formatter};
12 use core::str::FromStr;
13 use core::sync::atomic::{
14     AtomicI16, AtomicI32, AtomicI64, AtomicI8, AtomicIsize, AtomicU16, AtomicU32, AtomicU64,
15     AtomicU8, AtomicUsize, Ordering,
16 };
17 
18 /// A trait for types that can be written into a string.
19 ///
20 /// This works very similarly to `Debug`, and is automatically implemented if `Debug` is
21 /// implemented for a type. It is also implemented for any writable type inside a `Mutex`.
22 ///
23 /// The derived implementation of `Debug` [may
24 /// change](https://doc.rust-lang.org/std/fmt/trait.Debug.html#stability)
25 /// between Rust versions, so if stability is key for your use case, please implement `Writer`
26 /// explicitly instead.
27 pub trait Writer {
28     /// Formats the value using the given formatter.
29     fn write(&self, f: &mut Formatter<'_>) -> fmt::Result;
30 }
31 
32 impl<T: Writer> Writer for Mutex<T> {
33     fn write(&self, f: &mut Formatter<'_>) -> fmt::Result {
34         self.lock().write(f)
35     }
36 }
37 
38 impl<T: Debug> Writer for T {
39     fn write(&self, f: &mut Formatter<'_>) -> fmt::Result {
40         writeln!(f, "{self:?}")
41     }
42 }
43 
44 /// Trait for types that can be written out as binary.
45 pub trait BinaryWriter {
46     /// Writes the binary form of `self` into `writer`.
47     ///
48     /// `offset` is the requested offset into the binary representation of `self`.
49     ///
50     /// On success, returns the number of bytes written in to `writer`.
51     fn write_to_slice(
52         &self,
53         writer: &mut UserSliceWriter,
54         offset: &mut file::Offset,
55     ) -> Result<usize>;
56 }
57 
58 // Base implementation for any `T: AsBytes`.
59 impl<T: AsBytes> BinaryWriter for T {
60     fn write_to_slice(
61         &self,
62         writer: &mut UserSliceWriter,
63         offset: &mut file::Offset,
64     ) -> Result<usize> {
65         writer.write_slice_file(self.as_bytes(), offset)
66     }
67 }
68 
69 // Delegate for `Mutex<T>`: Support a `T` with an outer mutex.
70 impl<T: BinaryWriter> BinaryWriter for Mutex<T> {
71     fn write_to_slice(
72         &self,
73         writer: &mut UserSliceWriter,
74         offset: &mut file::Offset,
75     ) -> Result<usize> {
76         let guard = self.lock();
77 
78         guard.write_to_slice(writer, offset)
79     }
80 }
81 
82 /// A trait for types that can be updated from a user slice.
83 ///
84 /// This works similarly to `FromStr`, but operates on a `UserSliceReader` rather than a &str.
85 ///
86 /// It is automatically implemented for all atomic integers, or any type that implements `FromStr`
87 /// wrapped in a `Mutex`.
88 pub trait Reader {
89     /// Updates the value from the given user slice.
90     fn read_from_slice(&self, reader: &mut UserSliceReader) -> Result;
91 }
92 
93 impl<T: FromStr> Reader for Mutex<T> {
94     fn read_from_slice(&self, reader: &mut UserSliceReader) -> Result {
95         let mut buf = [0u8; 128];
96         if reader.len() > buf.len() {
97             return Err(EINVAL);
98         }
99         let n = reader.len();
100         reader.read_slice(&mut buf[..n])?;
101 
102         let s = core::str::from_utf8(&buf[..n]).map_err(|_| EINVAL)?;
103         let val = s.trim().parse::<T>().map_err(|_| EINVAL)?;
104         *self.lock() = val;
105         Ok(())
106     }
107 }
108 
109 /// Trait for types that can be constructed from a binary representation.
110 pub trait BinaryReader {
111     /// Reads the binary form of `self` from `reader`.
112     ///
113     /// `offset` is the requested offset into the binary representation of `self`.
114     ///
115     /// On success, returns the number of bytes read from `reader`.
116     fn read_from_slice(
117         &self,
118         reader: &mut UserSliceReader,
119         offset: &mut file::Offset,
120     ) -> Result<usize>;
121 }
122 
123 impl<T: AsBytes + FromBytes> BinaryReader for Mutex<T> {
124     fn read_from_slice(
125         &self,
126         reader: &mut UserSliceReader,
127         offset: &mut file::Offset,
128     ) -> Result<usize> {
129         let mut this = self.lock();
130 
131         reader.read_slice_file(this.as_bytes_mut(), offset)
132     }
133 }
134 
135 macro_rules! impl_reader_for_atomic {
136     ($(($atomic_type:ty, $int_type:ty)),*) => {
137         $(
138             impl Reader for $atomic_type {
139                 fn read_from_slice(&self, reader: &mut UserSliceReader) -> Result {
140                     let mut buf = [0u8; 21]; // Enough for a 64-bit number.
141                     if reader.len() > buf.len() {
142                         return Err(EINVAL);
143                     }
144                     let n = reader.len();
145                     reader.read_slice(&mut buf[..n])?;
146 
147                     let s = core::str::from_utf8(&buf[..n]).map_err(|_| EINVAL)?;
148                     let val = s.trim().parse::<$int_type>().map_err(|_| EINVAL)?;
149                     self.store(val, Ordering::Relaxed);
150                     Ok(())
151                 }
152             }
153         )*
154     };
155 }
156 
157 impl_reader_for_atomic!(
158     (AtomicI16, i16),
159     (AtomicI32, i32),
160     (AtomicI64, i64),
161     (AtomicI8, i8),
162     (AtomicIsize, isize),
163     (AtomicU16, u16),
164     (AtomicU32, u32),
165     (AtomicU64, u64),
166     (AtomicU8, u8),
167     (AtomicUsize, usize)
168 );
169