Re: [PATCH 4/7] rust: file: add `FileDescriptorReservation`
From: Alice Ryhl
Date: Thu Nov 30 2023 - 04:23:29 EST
Christian Brauner <brauner@xxxxxxxxxx> writes:
> On Wed, Nov 29, 2023 at 06:14:24PM +0100, Alice Ryhl wrote:
> > On Wed, Nov 29, 2023 at 5:55 PM Alice Ryhl <aliceryhl@xxxxxxxxxx> wrote:
> >
> > > >> + pub fn commit(self, file: ARef<File>) {
> > > >> + // SAFETY: `self.fd` was previously returned by `get_unused_fd_flags`, and `file.ptr` is
> > > >> + // guaranteed to have an owned ref count by its type invariants.
> > > >> + unsafe { bindings::fd_install(self.fd, file.0.get()) };
> > > >
> > > > Why file.0.get()? Where did that come from?
> > >
> > > This gets a raw pointer to the C type.
> > >
> > > The `.0` part is a field access. `ARef` struct is a tuple struct, so its
> > > fields are unnamed. However, the fields can still be accessed by index.
> >
> > Oh, sorry, this is wrong. Let me try again:
> >
> > This gets a raw pointer to the C type. The `.0` part accesses the
> > field of type `Opaque<bindings::file>` in the Rust wrapper. Recall
> > that File is defined like this:
> >
> > pub struct File(Opaque<bindings::file>);
> >
> > The above syntax defines a tuple struct, which means that the fields
> > are unnamed. The `.0` syntax accesses the first field of a tuple
> > struct [1].
> >
> > The `.get()` method is from the `Opaque` struct, which returns a raw
> > pointer to the C type being wrapped.
>
> It'd be nice if this could be written in a more obvious/elegant way. And
> if not a comment would help. I know there'll be more text then code but
> until this is second nature to read I personally won't mind... Because
> searching for this specific syntax isn't really possible.
Adding a comment to every instance of this is probably not realisitic.
This kind of code will be very common in abstraction code. However,
there are two other options that I think are reasonable:
1. I can change the definition of `File` so that the field has a name:
struct File {
inner: Opaque<bindings::file>,
}
Then, it would say `file.inner.get()`.
2. Alternatively, I can add a method to file:
impl File {
#[inline]
pub fn as_ptr(&self) -> *mut bindings::file {
self.0.get()
}
}
And then write `file.as_ptr()` whenever I want a pointer.
Alice