fidl_fuchsia_power_suspend/
fidl_fuchsia_power_suspend.rs

1// WARNING: This file is machine generated by fidlgen.
2
3#![warn(clippy::all)]
4#![allow(unused_parens, unused_mut, unused_imports, nonstandard_style)]
5
6use bitflags::bitflags;
7use fidl::client::QueryResponseFut;
8use fidl::encoding::{MessageBufFor, ProxyChannelBox, ResourceDialect};
9use fidl::endpoints::{ControlHandle as _, Responder as _};
10pub use fidl_fuchsia_power_suspend__common::*;
11use futures::future::{self, MaybeDone, TryFutureExt};
12use zx_status;
13
14#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
15pub struct StatsMarker;
16
17impl fidl::endpoints::ProtocolMarker for StatsMarker {
18    type Proxy = StatsProxy;
19    type RequestStream = StatsRequestStream;
20    #[cfg(target_os = "fuchsia")]
21    type SynchronousProxy = StatsSynchronousProxy;
22
23    const DEBUG_NAME: &'static str = "fuchsia.power.suspend.Stats";
24}
25impl fidl::endpoints::DiscoverableProtocolMarker for StatsMarker {}
26
27pub trait StatsProxyInterface: Send + Sync {
28    type WatchResponseFut: std::future::Future<Output = Result<SuspendStats, fidl::Error>> + Send;
29    fn r#watch(&self) -> Self::WatchResponseFut;
30}
31#[derive(Debug)]
32#[cfg(target_os = "fuchsia")]
33pub struct StatsSynchronousProxy {
34    client: fidl::client::sync::Client,
35}
36
37#[cfg(target_os = "fuchsia")]
38impl fidl::endpoints::SynchronousProxy for StatsSynchronousProxy {
39    type Proxy = StatsProxy;
40    type Protocol = StatsMarker;
41
42    fn from_channel(inner: fidl::Channel) -> Self {
43        Self::new(inner)
44    }
45
46    fn into_channel(self) -> fidl::Channel {
47        self.client.into_channel()
48    }
49
50    fn as_channel(&self) -> &fidl::Channel {
51        self.client.as_channel()
52    }
53}
54
55#[cfg(target_os = "fuchsia")]
56impl StatsSynchronousProxy {
57    pub fn new(channel: fidl::Channel) -> Self {
58        let protocol_name = <StatsMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME;
59        Self { client: fidl::client::sync::Client::new(channel, protocol_name) }
60    }
61
62    pub fn into_channel(self) -> fidl::Channel {
63        self.client.into_channel()
64    }
65
66    /// Waits until an event arrives and returns it. It is safe for other
67    /// threads to make concurrent requests while waiting for an event.
68    pub fn wait_for_event(
69        &self,
70        deadline: zx::MonotonicInstant,
71    ) -> Result<StatsEvent, fidl::Error> {
72        StatsEvent::decode(self.client.wait_for_event(deadline)?)
73    }
74
75    /// Gets the suspend statistics for the sytem.
76    ///
77    /// Uses the hanging get pattern: the first call to this method will return
78    /// immediately. For subsequent calls, the server will return only when
79    /// suspend stats have changed.
80    pub fn r#watch(&self, ___deadline: zx::MonotonicInstant) -> Result<SuspendStats, fidl::Error> {
81        let _response = self.client.send_query::<fidl::encoding::EmptyPayload, SuspendStats>(
82            (),
83            0x1c90507c87636a84,
84            fidl::encoding::DynamicFlags::empty(),
85            ___deadline,
86        )?;
87        Ok(_response)
88    }
89}
90
91#[cfg(target_os = "fuchsia")]
92impl From<StatsSynchronousProxy> for zx::Handle {
93    fn from(value: StatsSynchronousProxy) -> Self {
94        value.into_channel().into()
95    }
96}
97
98#[cfg(target_os = "fuchsia")]
99impl From<fidl::Channel> for StatsSynchronousProxy {
100    fn from(value: fidl::Channel) -> Self {
101        Self::new(value)
102    }
103}
104
105#[cfg(target_os = "fuchsia")]
106impl fidl::endpoints::FromClient for StatsSynchronousProxy {
107    type Protocol = StatsMarker;
108
109    fn from_client(value: fidl::endpoints::ClientEnd<StatsMarker>) -> Self {
110        Self::new(value.into_channel())
111    }
112}
113
114#[derive(Debug, Clone)]
115pub struct StatsProxy {
116    client: fidl::client::Client<fidl::encoding::DefaultFuchsiaResourceDialect>,
117}
118
119impl fidl::endpoints::Proxy for StatsProxy {
120    type Protocol = StatsMarker;
121
122    fn from_channel(inner: ::fidl::AsyncChannel) -> Self {
123        Self::new(inner)
124    }
125
126    fn into_channel(self) -> Result<::fidl::AsyncChannel, Self> {
127        self.client.into_channel().map_err(|client| Self { client })
128    }
129
130    fn as_channel(&self) -> &::fidl::AsyncChannel {
131        self.client.as_channel()
132    }
133}
134
135impl StatsProxy {
136    /// Create a new Proxy for fuchsia.power.suspend/Stats.
137    pub fn new(channel: ::fidl::AsyncChannel) -> Self {
138        let protocol_name = <StatsMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME;
139        Self { client: fidl::client::Client::new(channel, protocol_name) }
140    }
141
142    /// Get a Stream of events from the remote end of the protocol.
143    ///
144    /// # Panics
145    ///
146    /// Panics if the event stream was already taken.
147    pub fn take_event_stream(&self) -> StatsEventStream {
148        StatsEventStream { event_receiver: self.client.take_event_receiver() }
149    }
150
151    /// Gets the suspend statistics for the sytem.
152    ///
153    /// Uses the hanging get pattern: the first call to this method will return
154    /// immediately. For subsequent calls, the server will return only when
155    /// suspend stats have changed.
156    pub fn r#watch(
157        &self,
158    ) -> fidl::client::QueryResponseFut<SuspendStats, fidl::encoding::DefaultFuchsiaResourceDialect>
159    {
160        StatsProxyInterface::r#watch(self)
161    }
162}
163
164impl StatsProxyInterface for StatsProxy {
165    type WatchResponseFut =
166        fidl::client::QueryResponseFut<SuspendStats, fidl::encoding::DefaultFuchsiaResourceDialect>;
167    fn r#watch(&self) -> Self::WatchResponseFut {
168        fn _decode(
169            mut _buf: Result<<fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc, fidl::Error>,
170        ) -> Result<SuspendStats, fidl::Error> {
171            let _response = fidl::client::decode_transaction_body::<
172                SuspendStats,
173                fidl::encoding::DefaultFuchsiaResourceDialect,
174                0x1c90507c87636a84,
175            >(_buf?)?;
176            Ok(_response)
177        }
178        self.client.send_query_and_decode::<fidl::encoding::EmptyPayload, SuspendStats>(
179            (),
180            0x1c90507c87636a84,
181            fidl::encoding::DynamicFlags::empty(),
182            _decode,
183        )
184    }
185}
186
187pub struct StatsEventStream {
188    event_receiver: fidl::client::EventReceiver<fidl::encoding::DefaultFuchsiaResourceDialect>,
189}
190
191impl std::marker::Unpin for StatsEventStream {}
192
193impl futures::stream::FusedStream for StatsEventStream {
194    fn is_terminated(&self) -> bool {
195        self.event_receiver.is_terminated()
196    }
197}
198
199impl futures::Stream for StatsEventStream {
200    type Item = Result<StatsEvent, fidl::Error>;
201
202    fn poll_next(
203        mut self: std::pin::Pin<&mut Self>,
204        cx: &mut std::task::Context<'_>,
205    ) -> std::task::Poll<Option<Self::Item>> {
206        match futures::ready!(futures::stream::StreamExt::poll_next_unpin(
207            &mut self.event_receiver,
208            cx
209        )?) {
210            Some(buf) => std::task::Poll::Ready(Some(StatsEvent::decode(buf))),
211            None => std::task::Poll::Ready(None),
212        }
213    }
214}
215
216#[derive(Debug)]
217pub enum StatsEvent {
218    #[non_exhaustive]
219    _UnknownEvent {
220        /// Ordinal of the event that was sent.
221        ordinal: u64,
222    },
223}
224
225impl StatsEvent {
226    /// Decodes a message buffer as a [`StatsEvent`].
227    fn decode(
228        mut buf: <fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc,
229    ) -> Result<StatsEvent, fidl::Error> {
230        let (bytes, _handles) = buf.split_mut();
231        let (tx_header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
232        debug_assert_eq!(tx_header.tx_id, 0);
233        match tx_header.ordinal {
234            _ if tx_header.dynamic_flags().contains(fidl::encoding::DynamicFlags::FLEXIBLE) => {
235                Ok(StatsEvent::_UnknownEvent { ordinal: tx_header.ordinal })
236            }
237            _ => Err(fidl::Error::UnknownOrdinal {
238                ordinal: tx_header.ordinal,
239                protocol_name: <StatsMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
240            }),
241        }
242    }
243}
244
245/// A Stream of incoming requests for fuchsia.power.suspend/Stats.
246pub struct StatsRequestStream {
247    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
248    is_terminated: bool,
249}
250
251impl std::marker::Unpin for StatsRequestStream {}
252
253impl futures::stream::FusedStream for StatsRequestStream {
254    fn is_terminated(&self) -> bool {
255        self.is_terminated
256    }
257}
258
259impl fidl::endpoints::RequestStream for StatsRequestStream {
260    type Protocol = StatsMarker;
261    type ControlHandle = StatsControlHandle;
262
263    fn from_channel(channel: ::fidl::AsyncChannel) -> Self {
264        Self { inner: std::sync::Arc::new(fidl::ServeInner::new(channel)), is_terminated: false }
265    }
266
267    fn control_handle(&self) -> Self::ControlHandle {
268        StatsControlHandle { inner: self.inner.clone() }
269    }
270
271    fn into_inner(
272        self,
273    ) -> (::std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>, bool)
274    {
275        (self.inner, self.is_terminated)
276    }
277
278    fn from_inner(
279        inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
280        is_terminated: bool,
281    ) -> Self {
282        Self { inner, is_terminated }
283    }
284}
285
286impl futures::Stream for StatsRequestStream {
287    type Item = Result<StatsRequest, fidl::Error>;
288
289    fn poll_next(
290        mut self: std::pin::Pin<&mut Self>,
291        cx: &mut std::task::Context<'_>,
292    ) -> std::task::Poll<Option<Self::Item>> {
293        let this = &mut *self;
294        if this.inner.check_shutdown(cx) {
295            this.is_terminated = true;
296            return std::task::Poll::Ready(None);
297        }
298        if this.is_terminated {
299            panic!("polled StatsRequestStream after completion");
300        }
301        fidl::encoding::with_tls_decode_buf::<_, fidl::encoding::DefaultFuchsiaResourceDialect>(
302            |bytes, handles| {
303                match this.inner.channel().read_etc(cx, bytes, handles) {
304                    std::task::Poll::Ready(Ok(())) => {}
305                    std::task::Poll::Pending => return std::task::Poll::Pending,
306                    std::task::Poll::Ready(Err(zx_status::Status::PEER_CLOSED)) => {
307                        this.is_terminated = true;
308                        return std::task::Poll::Ready(None);
309                    }
310                    std::task::Poll::Ready(Err(e)) => {
311                        return std::task::Poll::Ready(Some(Err(fidl::Error::ServerRequestRead(
312                            e.into(),
313                        ))))
314                    }
315                }
316
317                // A message has been received from the channel
318                let (header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
319
320                std::task::Poll::Ready(Some(match header.ordinal {
321                    0x1c90507c87636a84 => {
322                        header.validate_request_tx_id(fidl::MethodType::TwoWay)?;
323                        let mut req = fidl::new_empty!(
324                            fidl::encoding::EmptyPayload,
325                            fidl::encoding::DefaultFuchsiaResourceDialect
326                        );
327                        fidl::encoding::Decoder::<fidl::encoding::DefaultFuchsiaResourceDialect>::decode_into::<fidl::encoding::EmptyPayload>(&header, _body_bytes, handles, &mut req)?;
328                        let control_handle = StatsControlHandle { inner: this.inner.clone() };
329                        Ok(StatsRequest::Watch {
330                            responder: StatsWatchResponder {
331                                control_handle: std::mem::ManuallyDrop::new(control_handle),
332                                tx_id: header.tx_id,
333                            },
334                        })
335                    }
336                    _ if header.tx_id == 0
337                        && header
338                            .dynamic_flags()
339                            .contains(fidl::encoding::DynamicFlags::FLEXIBLE) =>
340                    {
341                        Ok(StatsRequest::_UnknownMethod {
342                            ordinal: header.ordinal,
343                            control_handle: StatsControlHandle { inner: this.inner.clone() },
344                            method_type: fidl::MethodType::OneWay,
345                        })
346                    }
347                    _ if header
348                        .dynamic_flags()
349                        .contains(fidl::encoding::DynamicFlags::FLEXIBLE) =>
350                    {
351                        this.inner.send_framework_err(
352                            fidl::encoding::FrameworkErr::UnknownMethod,
353                            header.tx_id,
354                            header.ordinal,
355                            header.dynamic_flags(),
356                            (bytes, handles),
357                        )?;
358                        Ok(StatsRequest::_UnknownMethod {
359                            ordinal: header.ordinal,
360                            control_handle: StatsControlHandle { inner: this.inner.clone() },
361                            method_type: fidl::MethodType::TwoWay,
362                        })
363                    }
364                    _ => Err(fidl::Error::UnknownOrdinal {
365                        ordinal: header.ordinal,
366                        protocol_name: <StatsMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
367                    }),
368                }))
369            },
370        )
371    }
372}
373
374/// A protocol for retrieving statistics related to suspend/resume operations.
375#[derive(Debug)]
376pub enum StatsRequest {
377    /// Gets the suspend statistics for the sytem.
378    ///
379    /// Uses the hanging get pattern: the first call to this method will return
380    /// immediately. For subsequent calls, the server will return only when
381    /// suspend stats have changed.
382    Watch { responder: StatsWatchResponder },
383    /// An interaction was received which does not match any known method.
384    #[non_exhaustive]
385    _UnknownMethod {
386        /// Ordinal of the method that was called.
387        ordinal: u64,
388        control_handle: StatsControlHandle,
389        method_type: fidl::MethodType,
390    },
391}
392
393impl StatsRequest {
394    #[allow(irrefutable_let_patterns)]
395    pub fn into_watch(self) -> Option<(StatsWatchResponder)> {
396        if let StatsRequest::Watch { responder } = self {
397            Some((responder))
398        } else {
399            None
400        }
401    }
402
403    /// Name of the method defined in FIDL
404    pub fn method_name(&self) -> &'static str {
405        match *self {
406            StatsRequest::Watch { .. } => "watch",
407            StatsRequest::_UnknownMethod { method_type: fidl::MethodType::OneWay, .. } => {
408                "unknown one-way method"
409            }
410            StatsRequest::_UnknownMethod { method_type: fidl::MethodType::TwoWay, .. } => {
411                "unknown two-way method"
412            }
413        }
414    }
415}
416
417#[derive(Debug, Clone)]
418pub struct StatsControlHandle {
419    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
420}
421
422impl fidl::endpoints::ControlHandle for StatsControlHandle {
423    fn shutdown(&self) {
424        self.inner.shutdown()
425    }
426    fn shutdown_with_epitaph(&self, status: zx_status::Status) {
427        self.inner.shutdown_with_epitaph(status)
428    }
429
430    fn is_closed(&self) -> bool {
431        self.inner.channel().is_closed()
432    }
433    fn on_closed(&self) -> fidl::OnSignalsRef<'_> {
434        self.inner.channel().on_closed()
435    }
436
437    #[cfg(target_os = "fuchsia")]
438    fn signal_peer(
439        &self,
440        clear_mask: zx::Signals,
441        set_mask: zx::Signals,
442    ) -> Result<(), zx_status::Status> {
443        use fidl::Peered;
444        self.inner.channel().signal_peer(clear_mask, set_mask)
445    }
446}
447
448impl StatsControlHandle {}
449
450#[must_use = "FIDL methods require a response to be sent"]
451#[derive(Debug)]
452pub struct StatsWatchResponder {
453    control_handle: std::mem::ManuallyDrop<StatsControlHandle>,
454    tx_id: u32,
455}
456
457/// Set the the channel to be shutdown (see [`StatsControlHandle::shutdown`])
458/// if the responder is dropped without sending a response, so that the client
459/// doesn't hang. To prevent this behavior, call `drop_without_shutdown`.
460impl std::ops::Drop for StatsWatchResponder {
461    fn drop(&mut self) {
462        self.control_handle.shutdown();
463        // Safety: drops once, never accessed again
464        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
465    }
466}
467
468impl fidl::endpoints::Responder for StatsWatchResponder {
469    type ControlHandle = StatsControlHandle;
470
471    fn control_handle(&self) -> &StatsControlHandle {
472        &self.control_handle
473    }
474
475    fn drop_without_shutdown(mut self) {
476        // Safety: drops once, never accessed again due to mem::forget
477        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
478        // Prevent Drop from running (which would shut down the channel)
479        std::mem::forget(self);
480    }
481}
482
483impl StatsWatchResponder {
484    /// Sends a response to the FIDL transaction.
485    ///
486    /// Sets the channel to shutdown if an error occurs.
487    pub fn send(self, mut payload: &SuspendStats) -> Result<(), fidl::Error> {
488        let _result = self.send_raw(payload);
489        if _result.is_err() {
490            self.control_handle.shutdown();
491        }
492        self.drop_without_shutdown();
493        _result
494    }
495
496    /// Similar to "send" but does not shutdown the channel if an error occurs.
497    pub fn send_no_shutdown_on_err(self, mut payload: &SuspendStats) -> Result<(), fidl::Error> {
498        let _result = self.send_raw(payload);
499        self.drop_without_shutdown();
500        _result
501    }
502
503    fn send_raw(&self, mut payload: &SuspendStats) -> Result<(), fidl::Error> {
504        self.control_handle.inner.send::<SuspendStats>(
505            payload,
506            self.tx_id,
507            0x1c90507c87636a84,
508            fidl::encoding::DynamicFlags::empty(),
509        )
510    }
511}
512
513mod internal {
514    use super::*;
515}