Re: [PATCH 1/4] rust: i2c: add read and write byte data abstractions

From: Alice Ryhl
Date: Thu Oct 09 2025 - 07:31:33 EST


On Wed, Oct 08, 2025 at 06:10:43PM +0000, Markus Probst wrote:
> In addition to the core abstractions, implement
>
> * `i2c::I2cClient::read_byte` - read a byte from the i2c client
> * `i2c::I2cClient::write_byte` - write a byte to the i2c client
>
> * `i2c::I2cClient::read_byte_data` - read byte data from the i2c client
> * `i2c::I2cClient::write_byte_data` - write byte data to the i2c client
>
> * `i2c::I2cClient::read_word_data` - read word data from the i2c client
> * `i2c::I2cClient::write_word_data` - write word data to the i2c client
>
> Signed-off-by: Markus Probst <markus.probst@xxxxxxxxx>
> ---
> rust/kernel/i2c.rs | 45 +++++++++++++++++++++++++++++++++++++++++++++
> 1 file changed, 45 insertions(+)
>
> diff --git a/rust/kernel/i2c.rs b/rust/kernel/i2c.rs
> index 73858aecc131..57b02b65f90f 100644
> --- a/rust/kernel/i2c.rs
> +++ b/rust/kernel/i2c.rs
> @@ -463,6 +463,51 @@ impl<Ctx: device::DeviceContext> I2cClient<Ctx> {
> fn as_raw(&self) -> *mut bindings::i2c_client {
> self.0.get()
> }
> +
> + /// Reads a byte from the i2c client
> + pub fn read_byte(&self) -> Result<u8> {
> + // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
> + // `struct i2c_client`.
> + let value = unsafe { bindings::i2c_smbus_read_byte(self.as_raw()) };
> + to_result(value).map(|()| value as u8)
> + }
> +
> + /// Writes a byte to the i2c client
> + pub fn write_byte(&self, value: u8) -> Result<()> {
> + // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
> + // `struct i2c_client`.
> + to_result(unsafe { bindings::i2c_smbus_write_byte(self.as_raw(), value) })
> + }
> +
> + /// Reads byte data from the i2c client
> + pub fn read_byte_data(&self, reg: u8) -> Result<u8> {
> + // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
> + // `struct i2c_client`.
> + let value = unsafe { bindings::i2c_smbus_read_byte_data(self.as_raw(), reg) };
> + to_result(value).map(|()| value as u8)
> + }
> +
> + /// Writes byte data to the i2c client
> + pub fn write_byte_data(&self, reg: u8, value: u8) -> Result<()> {
> + // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
> + // `struct i2c_client`.
> + to_result(unsafe { bindings::i2c_smbus_write_byte_data(self.as_raw(), reg, value) })
> + }

I think it would be useful if the documentation for these methods has an
explanation of the difference between `write_byte` and
`write_byte_data`.

Alice