base: improve the WaitContext doc test

Use the PollToken derive and the build_with() function to make the
example more representative of actual uses.

BUG=None
TEST=cargo doc
TEST=cargo test -p base --doc wait_context

Change-Id: I1f154dfd6247786024dc94035ea63db11968e85a
Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/platform/crosvm/+/3630424
Reviewed-by: Dennis Kempin <denniskempin@google.com>
Reviewed-by: Noah Gold <nkgold@google.com>
Tested-by: kokoro <noreply+kokoro@google.com>
Commit-Queue: Daniel Verkamp <dverkamp@chromium.org>
This commit is contained in:
Daniel Verkamp 2022-05-04 16:29:38 -07:00 committed by Chromeos LUCI
parent c7e45226be
commit 4fb38ced74
2 changed files with 41 additions and 17 deletions

View file

@ -44,24 +44,48 @@ pub enum EventType {
/// # Example
///
/// ```
/// # use base::{
/// Result, Event, WaitContext,
/// };
/// # fn test() -> Result<()> {
/// let evt1 = Event::new()?;
/// let evt2 = Event::new()?;
/// evt2.write(1)?;
/// use base::{Event, PollToken, Result, WaitContext};
///
/// let ctx: WaitContext<u32> = WaitContext::new()?;
/// ctx.add(&evt1, 1)?;
/// ctx.add(&evt2, 2)?;
/// #[derive(PollToken, Copy, Clone, Debug, PartialEq)]
/// enum ExampleToken {
/// SomeEvent(u32),
/// AnotherEvent,
/// }
///
/// let events = ctx.wait()?;
/// let tokens: Vec<u32> = events.iter().filter(|e| e.is_readable)
/// .map(|e| e.token).collect();
/// assert_eq!(tokens, [2]);
/// # Ok(())
/// # }
/// let evt1 = Event::new()?;
/// let evt2 = Event::new()?;
/// let another_evt = Event::new()?;
///
/// let ctx: WaitContext<ExampleToken> = WaitContext::build_with(&[
/// (&evt1, ExampleToken::SomeEvent(1)),
/// (&evt2, ExampleToken::SomeEvent(2)),
/// (&another_evt, ExampleToken::AnotherEvent),
/// ])?;
///
/// // Trigger one of the `SomeEvent` events.
/// evt2.write(1)?;
///
/// // Wait for an event to fire. `wait()` will return immediately in this example because `evt2`
/// // has already been triggered, but in normal use, `wait()` will block until at least one event
/// // is signaled by another thread or process.
/// let events = ctx.wait()?;
/// let tokens: Vec<ExampleToken> = events.iter().filter(|e| e.is_readable)
/// .map(|e| e.token).collect();
/// assert_eq!(tokens, [ExampleToken::SomeEvent(2)]);
///
/// // Reset evt2 so it doesn't trigger again in the next `wait()` call.
/// let _ = evt2.read()?;
///
/// // Trigger a different event.
/// another_evt.write(1)?;
///
/// let events = ctx.wait()?;
/// let tokens: Vec<ExampleToken> = events.iter().filter(|e| e.is_readable)
/// .map(|e| e.token).collect();
/// assert_eq!(tokens, [ExampleToken::AnotherEvent]);
///
/// let _ = another_evt.read()?;
/// # Ok::<(), base::Error>(())
/// ```
pub struct WaitContext<T: EventToken>(EventContext<T>);

@ -1 +1 @@
Subproject commit ff062d54f9a419e149f726b69aea8cd509158927
Subproject commit 4170a270c9db983ffdbbd6c464494fc4432319b3