1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Copyright 2024 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use std::convert::From;
use std::convert::TryFrom;
use std::os::fd::OwnedFd;

use nix::sys::eventfd::EfdFlags;
use nix::sys::eventfd::EventFd;
use nix::unistd::read;
use nix::unistd::write;

use crate::rutabaga_os::AsBorrowedDescriptor;
use crate::rutabaga_os::AsRawDescriptor;
use crate::rutabaga_os::OwnedDescriptor;
use crate::rutabaga_utils::RutabagaError;
use crate::rutabaga_utils::RutabagaHandle;
use crate::rutabaga_utils::RutabagaResult;
use crate::rutabaga_utils::RUTABAGA_FENCE_HANDLE_TYPE_EVENT_FD;

pub struct Event {
    descriptor: OwnedDescriptor,
}

impl Event {
    pub fn new() -> RutabagaResult<Event> {
        let owned: OwnedFd = EventFd::from_flags(EfdFlags::empty())?.into();
        Ok(Event {
            descriptor: owned.into(),
        })
    }

    pub fn signal(&mut self) -> RutabagaResult<()> {
        let _ = write(&self.descriptor, &1u64.to_ne_bytes())?;
        Ok(())
    }

    pub fn wait(&self) -> RutabagaResult<()> {
        read(self.descriptor.as_raw_descriptor(), &mut 1u64.to_ne_bytes())?;
        Ok(())
    }

    pub fn try_clone(&self) -> RutabagaResult<Event> {
        let clone = self.descriptor.try_clone()?;
        Ok(Event { descriptor: clone })
    }
}

impl TryFrom<RutabagaHandle> for Event {
    type Error = RutabagaError;
    fn try_from(handle: RutabagaHandle) -> Result<Self, Self::Error> {
        if handle.handle_type != RUTABAGA_FENCE_HANDLE_TYPE_EVENT_FD {
            return Err(RutabagaError::InvalidRutabagaHandle);
        }

        Ok(Event {
            descriptor: handle.os_handle,
        })
    }
}

impl From<Event> for RutabagaHandle {
    fn from(evt: Event) -> Self {
        RutabagaHandle {
            os_handle: evt.descriptor,
            handle_type: RUTABAGA_FENCE_HANDLE_TYPE_EVENT_FD,
        }
    }
}

impl AsBorrowedDescriptor for Event {
    fn as_borrowed_descriptor(&self) -> &OwnedDescriptor {
        &self.descriptor
    }
}