linux-gpio.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
From: Kent Gibson <warthog618@gmail.com>
To: Bartosz Golaszewski <brgl@bgdev.pl>
Cc: "Viresh Kumar" <viresh.kumar@linaro.org>,
	"Linus Walleij" <linus.walleij@linaro.org>,
	"Vincent Guittot" <vincent.guittot@linaro.org>,
	linux-gpio@vger.kernel.org,
	"Miguel Ojeda" <miguel.ojeda.sandonis@gmail.com>,
	"Alex Bennée" <alex.bennee@linaro.org>,
	stratos-dev@op-lists.linaro.org,
	"Gerard Ryan" <g.m0n3y.2503@gmail.com>
Subject: Re: [PATCH V6 3/8] libgpiod: Add rust wrapper crate
Date: Thu, 29 Sep 2022 19:43:16 +0800	[thread overview]
Message-ID: <YzWE1BpdCEqJqDJN@sol> (raw)
In-Reply-To: <CAMRc=McSZWLdPNESPLfDD4UgyvtyU7BcvB-ZZrvDWM3LDYjEMA@mail.gmail.com>

On Thu, Sep 29, 2022 at 09:37:40AM +0200, Bartosz Golaszewski wrote:
> On Thu, Sep 29, 2022 at 8:54 AM Viresh Kumar <viresh.kumar@linaro.org> wrote:
> >
> > On 28-09-22, 19:54, Bartosz Golaszewski wrote:
> > > On Wed, Sep 28, 2022 at 5:17 PM Viresh Kumar <viresh.kumar@linaro.org> wrote:
> > > > Hmm, so what exactly do we want to do here then ?
> > > >
> > > > - Don't allow events to be referenced ? i.e. make event_clone() the default
> > > >   behavior ?
> > > >
> > >
> > > God no, that would be wasteful.
> > >
> > > > - Don't allow read_edge_event() to be called twice for a buffer ? that will be
> > > >   inefficient though.
> > > >
> > >
> > > Not good either.
> >
> > As I expected for both of them :)
> >
> > > > - Somehow guarantee that reference to all the events are dropped before issuing
> > > >   read_edge_event() again, else make it fail ? I am not sure how straight
> > > >   forward that can be though.
> > >
> > > In C++ the preferred way is to do buffer.get_event(0) which will
> > > return a constant reference. If you store that reference as const
> > > edge_event& ev = buffer.get_event(0) and reuse it after rereading into
> > > that buffer and the program crashes - that's on you. In most cases you
> > > should just do buffer.get_event(0).line_offset() etc. If you do:
> > >
> > > edge_event event = buffer.get_event(0);
> > >
> > > You'll copy the event and it will survive the overwriting of the buffer.
> >
> > Right, same happens here.
> >
> > > I'm a Rust beginner but my understanding is that the whole idea of the
> > > language design is to *not* allow a situation where the program can
> > > crash. It should be detected at build-time. We must not rely on
> > > "contracts" defined by documentation.
> >
> > If everything was written in Rust, then this problem won't occur for sure. But
> > in this case part of the code is available via FFI (foreign function interface)
> > and they guarantees are a bit limited there and depend on what the FFI
> > guarantees.
> >
> > > Is there a way to invalidate a reference in Rust? Have a small (cheap)
> > > object in the buffer which the event references and which would get
> > > dropped when reading into the buffer?
> >
> > I am not sure. There are locks, but then they have a cost.
> >
> 
> I'm not talking about locking, this should be left to the user of the module.
> 
> Can we force-drop an object still referenced by other objects in Rust?
> This is what I had in mind - a small, dummy, cheap object inside the
> buffer that's created when reading into the buffer. Each even would
> reference it and then Rust would not allow us to drop it as long as
> there are references to it. Does it make sense? Is that possible?
> 

No, Rust will explicitly prevent you from dropping referenced objects.

But is this the sort of thing you mean:

use std::process::ExitCode;

#[derive(Clone)]
struct Event {
    pub id: u8
}

struct Events {
    b: Vec<Event>
}

impl Events {
    pub fn get(&self, idx: usize) -> Option<&Event> {
        self.b.get(idx)
    }
}

struct Buffer {
    count: u8,
    events: Option<Events>,
}

impl Buffer {
    
    pub fn read(&mut self) -> Result<&Events, ()> {
        self.count += 1;
        self.events = Some(Events{b: vec![Event{id: self.count}]});
        self.events.as_ref().ok_or(())
    }
}

fn main() -> Result<ExitCode, ()>{
    let mut b = Buffer{count: 0, events:None};
    let mut ee = b.read()?;
    let e = ee.get(0);
    println!("{:?}", e.unwrap().id);
    let cloned_e = e.unwrap().clone();
    drop(e); // <-- comment out to try to create a dangling event reference
    ee = b.read()?;
    let e = ee.get(0); // <-- comment out to try to create a dangling event reference
    println!("{:?}", cloned_e.id);
    println!("{:?}", e.unwrap().id);
    Ok(ExitCode::from(42))
}

That is a skeletal proof of concept - the small, dummy, cheap object is
the Vec in Events.  Is that cheap enough? You might be able to replace
that with something cheaper, but Events needs to be able to pull an
Event reference from somewhere (from the borrow checker's PoV) so it
made this demo simpler.

Comment out the two lines to try to carry e across the buffer read().
The compiler will not allow it, as e already borrows from b.

In an actual implementation Event would wrap the C event, and Events.get()
would get the event pointer for the Event and return that as a reference.
The Event clone would call into C, rather than being derived as it is here.

Key points:  Buffer has to own the Events snapshot that is returned by
reference by read().  The return by reference creates a borrow on the
Buffer.  The read() requires a &mut to prevent the Buffer being read
while there are any borrows outstanding.
The Events returns individual events by reference to create a borrow on
the Events to prevent it (and the Buffer) being dropped or modified.
The Event clone returns a concrete event that does not have a borrow of
the Events or Buffer.

There may well be better ways to do this, and you would really want to
do some benchmarking to compare it with the immediate clone option - it
may well be worse, but hopefully it at least demonstrates the semantics
you are after.

Cheers,
Kent.

  parent reply	other threads:[~2022-09-29 11:43 UTC|newest]

Thread overview: 37+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2022-09-26 11:08 [PATCH V6 0/8] libgpiod: Add Rust bindings Viresh Kumar
2022-09-26 11:08 ` [PATCH V6 1/8] libgpiod: Add libgpiod-sys rust crate Viresh Kumar
2022-09-26 11:08 ` [PATCH V6 2/8] libgpiod-sys: Add pre generated rust bindings Viresh Kumar
2022-09-26 11:08 ` [PATCH V6 3/8] libgpiod: Add rust wrapper crate Viresh Kumar
2022-09-26 13:29   ` Bartosz Golaszewski
2022-09-26 15:26     ` Viresh Kumar
2022-09-27 13:18       ` Bartosz Golaszewski
2022-09-27 13:57         ` Viresh Kumar
2022-09-27 15:25           ` Bartosz Golaszewski
2022-09-28 11:10             ` Viresh Kumar
2022-09-28 12:20               ` Bartosz Golaszewski
2022-09-28 15:17                 ` Viresh Kumar
2022-09-28 17:54                   ` Bartosz Golaszewski
2022-09-29  6:54                     ` Viresh Kumar
2022-09-29  7:37                       ` Bartosz Golaszewski
2022-09-29  8:58                         ` Viresh Kumar
2022-09-29 11:16                           ` Bartosz Golaszewski
2022-09-29 11:43                         ` Kent Gibson [this message]
2022-09-29 13:55                     ` Miguel Ojeda
2022-10-11  4:16                       ` Viresh Kumar
2022-10-11  4:25                         ` Kent Gibson
2022-10-11  4:37                           ` Viresh Kumar
2022-10-11  4:46                             ` Viresh Kumar
2022-10-13  6:12                         ` Viresh Kumar
2022-10-14  9:45                           ` Bartosz Golaszewski
2022-10-14  9:57                             ` Viresh Kumar
2022-10-14 14:25                               ` Bartosz Golaszewski
2022-10-14 16:06                                 ` Kent Gibson
2022-10-17 11:26                                   ` Viresh Kumar
2022-10-17 11:34                                     ` Kent Gibson
2022-10-17 11:37                                       ` Viresh Kumar
2022-09-26 11:08 ` [PATCH V6 4/8] libgpiod: Add rust examples Viresh Kumar
2022-09-26 11:08 ` [PATCH V6 5/8] libgpiod: Add gpiosim rust crate Viresh Kumar
2022-09-26 11:08 ` [PATCH V6 6/8] gpiosim: Add pre generated rust bindings Viresh Kumar
2022-09-26 11:08 ` [PATCH V6 7/8] libgpiod: Add rust tests Viresh Kumar
2022-09-26 11:08 ` [PATCH V6 8/8] libgpiod: Integrate building of rust bindings with make Viresh Kumar
2022-09-26 15:57 ` [PATCH V6 0/8] libgpiod: Add Rust bindings Viresh Kumar

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=YzWE1BpdCEqJqDJN@sol \
    --to=warthog618@gmail.com \
    --cc=alex.bennee@linaro.org \
    --cc=brgl@bgdev.pl \
    --cc=g.m0n3y.2503@gmail.com \
    --cc=linus.walleij@linaro.org \
    --cc=linux-gpio@vger.kernel.org \
    --cc=miguel.ojeda.sandonis@gmail.com \
    --cc=stratos-dev@op-lists.linaro.org \
    --cc=vincent.guittot@linaro.org \
    --cc=viresh.kumar@linaro.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).