fidl_fuchsia_power_profile/
fidl_fuchsia_power_profile.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_profile_common::*;
11use futures::future::{self, MaybeDone, TryFutureExt};
12use zx_status;
13
14#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
15pub struct WatcherMarker;
16
17impl fidl::endpoints::ProtocolMarker for WatcherMarker {
18    type Proxy = WatcherProxy;
19    type RequestStream = WatcherRequestStream;
20    #[cfg(target_os = "fuchsia")]
21    type SynchronousProxy = WatcherSynchronousProxy;
22
23    const DEBUG_NAME: &'static str = "fuchsia.power.profile.Watcher";
24}
25impl fidl::endpoints::DiscoverableProtocolMarker for WatcherMarker {}
26
27pub trait WatcherProxyInterface: Send + Sync {
28    type WatchResponseFut: std::future::Future<Output = Result<Profile, fidl::Error>> + Send;
29    fn r#watch(&self) -> Self::WatchResponseFut;
30}
31#[derive(Debug)]
32#[cfg(target_os = "fuchsia")]
33pub struct WatcherSynchronousProxy {
34    client: fidl::client::sync::Client,
35}
36
37#[cfg(target_os = "fuchsia")]
38impl fidl::endpoints::SynchronousProxy for WatcherSynchronousProxy {
39    type Proxy = WatcherProxy;
40    type Protocol = WatcherMarker;
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 WatcherSynchronousProxy {
57    pub fn new(channel: fidl::Channel) -> Self {
58        let protocol_name = <WatcherMarker 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<WatcherEvent, fidl::Error> {
72        WatcherEvent::decode(self.client.wait_for_event(deadline)?)
73    }
74
75    /// Watches for changes to the system power profile.
76    ///
77    /// On a given connection, the first call will return immediately with the current system power
78    /// profile, while subsequent calls will only return a new `profile` as the system power profile
79    /// changes. This follows the
80    /// [hanging get](https://fuchsia.dev/fuchsia-src/concepts/api/fidl#hanging-get) pattern. Any
81    /// errors are considered fatal and will result in the channel being closed.
82    pub fn r#watch(&self, ___deadline: zx::MonotonicInstant) -> Result<Profile, fidl::Error> {
83        let _response =
84            self.client.send_query::<fidl::encoding::EmptyPayload, WatcherWatchResponse>(
85                (),
86                0x5f29be53ad34a947,
87                fidl::encoding::DynamicFlags::empty(),
88                ___deadline,
89            )?;
90        Ok(_response.profile)
91    }
92}
93
94#[derive(Debug, Clone)]
95pub struct WatcherProxy {
96    client: fidl::client::Client<fidl::encoding::DefaultFuchsiaResourceDialect>,
97}
98
99impl fidl::endpoints::Proxy for WatcherProxy {
100    type Protocol = WatcherMarker;
101
102    fn from_channel(inner: ::fidl::AsyncChannel) -> Self {
103        Self::new(inner)
104    }
105
106    fn into_channel(self) -> Result<::fidl::AsyncChannel, Self> {
107        self.client.into_channel().map_err(|client| Self { client })
108    }
109
110    fn as_channel(&self) -> &::fidl::AsyncChannel {
111        self.client.as_channel()
112    }
113}
114
115impl WatcherProxy {
116    /// Create a new Proxy for fuchsia.power.profile/Watcher.
117    pub fn new(channel: ::fidl::AsyncChannel) -> Self {
118        let protocol_name = <WatcherMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME;
119        Self { client: fidl::client::Client::new(channel, protocol_name) }
120    }
121
122    /// Get a Stream of events from the remote end of the protocol.
123    ///
124    /// # Panics
125    ///
126    /// Panics if the event stream was already taken.
127    pub fn take_event_stream(&self) -> WatcherEventStream {
128        WatcherEventStream { event_receiver: self.client.take_event_receiver() }
129    }
130
131    /// Watches for changes to the system power profile.
132    ///
133    /// On a given connection, the first call will return immediately with the current system power
134    /// profile, while subsequent calls will only return a new `profile` as the system power profile
135    /// changes. This follows the
136    /// [hanging get](https://fuchsia.dev/fuchsia-src/concepts/api/fidl#hanging-get) pattern. Any
137    /// errors are considered fatal and will result in the channel being closed.
138    pub fn r#watch(
139        &self,
140    ) -> fidl::client::QueryResponseFut<Profile, fidl::encoding::DefaultFuchsiaResourceDialect>
141    {
142        WatcherProxyInterface::r#watch(self)
143    }
144}
145
146impl WatcherProxyInterface for WatcherProxy {
147    type WatchResponseFut =
148        fidl::client::QueryResponseFut<Profile, fidl::encoding::DefaultFuchsiaResourceDialect>;
149    fn r#watch(&self) -> Self::WatchResponseFut {
150        fn _decode(
151            mut _buf: Result<<fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc, fidl::Error>,
152        ) -> Result<Profile, fidl::Error> {
153            let _response = fidl::client::decode_transaction_body::<
154                WatcherWatchResponse,
155                fidl::encoding::DefaultFuchsiaResourceDialect,
156                0x5f29be53ad34a947,
157            >(_buf?)?;
158            Ok(_response.profile)
159        }
160        self.client.send_query_and_decode::<fidl::encoding::EmptyPayload, Profile>(
161            (),
162            0x5f29be53ad34a947,
163            fidl::encoding::DynamicFlags::empty(),
164            _decode,
165        )
166    }
167}
168
169pub struct WatcherEventStream {
170    event_receiver: fidl::client::EventReceiver<fidl::encoding::DefaultFuchsiaResourceDialect>,
171}
172
173impl std::marker::Unpin for WatcherEventStream {}
174
175impl futures::stream::FusedStream for WatcherEventStream {
176    fn is_terminated(&self) -> bool {
177        self.event_receiver.is_terminated()
178    }
179}
180
181impl futures::Stream for WatcherEventStream {
182    type Item = Result<WatcherEvent, fidl::Error>;
183
184    fn poll_next(
185        mut self: std::pin::Pin<&mut Self>,
186        cx: &mut std::task::Context<'_>,
187    ) -> std::task::Poll<Option<Self::Item>> {
188        match futures::ready!(futures::stream::StreamExt::poll_next_unpin(
189            &mut self.event_receiver,
190            cx
191        )?) {
192            Some(buf) => std::task::Poll::Ready(Some(WatcherEvent::decode(buf))),
193            None => std::task::Poll::Ready(None),
194        }
195    }
196}
197
198#[derive(Debug)]
199pub enum WatcherEvent {}
200
201impl WatcherEvent {
202    /// Decodes a message buffer as a [`WatcherEvent`].
203    fn decode(
204        mut buf: <fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc,
205    ) -> Result<WatcherEvent, fidl::Error> {
206        let (bytes, _handles) = buf.split_mut();
207        let (tx_header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
208        debug_assert_eq!(tx_header.tx_id, 0);
209        match tx_header.ordinal {
210            _ => Err(fidl::Error::UnknownOrdinal {
211                ordinal: tx_header.ordinal,
212                protocol_name: <WatcherMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
213            }),
214        }
215    }
216}
217
218/// A Stream of incoming requests for fuchsia.power.profile/Watcher.
219pub struct WatcherRequestStream {
220    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
221    is_terminated: bool,
222}
223
224impl std::marker::Unpin for WatcherRequestStream {}
225
226impl futures::stream::FusedStream for WatcherRequestStream {
227    fn is_terminated(&self) -> bool {
228        self.is_terminated
229    }
230}
231
232impl fidl::endpoints::RequestStream for WatcherRequestStream {
233    type Protocol = WatcherMarker;
234    type ControlHandle = WatcherControlHandle;
235
236    fn from_channel(channel: ::fidl::AsyncChannel) -> Self {
237        Self { inner: std::sync::Arc::new(fidl::ServeInner::new(channel)), is_terminated: false }
238    }
239
240    fn control_handle(&self) -> Self::ControlHandle {
241        WatcherControlHandle { inner: self.inner.clone() }
242    }
243
244    fn into_inner(
245        self,
246    ) -> (::std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>, bool)
247    {
248        (self.inner, self.is_terminated)
249    }
250
251    fn from_inner(
252        inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
253        is_terminated: bool,
254    ) -> Self {
255        Self { inner, is_terminated }
256    }
257}
258
259impl futures::Stream for WatcherRequestStream {
260    type Item = Result<WatcherRequest, fidl::Error>;
261
262    fn poll_next(
263        mut self: std::pin::Pin<&mut Self>,
264        cx: &mut std::task::Context<'_>,
265    ) -> std::task::Poll<Option<Self::Item>> {
266        let this = &mut *self;
267        if this.inner.check_shutdown(cx) {
268            this.is_terminated = true;
269            return std::task::Poll::Ready(None);
270        }
271        if this.is_terminated {
272            panic!("polled WatcherRequestStream after completion");
273        }
274        fidl::encoding::with_tls_decode_buf::<_, fidl::encoding::DefaultFuchsiaResourceDialect>(
275            |bytes, handles| {
276                match this.inner.channel().read_etc(cx, bytes, handles) {
277                    std::task::Poll::Ready(Ok(())) => {}
278                    std::task::Poll::Pending => return std::task::Poll::Pending,
279                    std::task::Poll::Ready(Err(zx_status::Status::PEER_CLOSED)) => {
280                        this.is_terminated = true;
281                        return std::task::Poll::Ready(None);
282                    }
283                    std::task::Poll::Ready(Err(e)) => {
284                        return std::task::Poll::Ready(Some(Err(fidl::Error::ServerRequestRead(
285                            e.into(),
286                        ))))
287                    }
288                }
289
290                // A message has been received from the channel
291                let (header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
292
293                std::task::Poll::Ready(Some(match header.ordinal {
294                    0x5f29be53ad34a947 => {
295                        header.validate_request_tx_id(fidl::MethodType::TwoWay)?;
296                        let mut req = fidl::new_empty!(
297                            fidl::encoding::EmptyPayload,
298                            fidl::encoding::DefaultFuchsiaResourceDialect
299                        );
300                        fidl::encoding::Decoder::<fidl::encoding::DefaultFuchsiaResourceDialect>::decode_into::<fidl::encoding::EmptyPayload>(&header, _body_bytes, handles, &mut req)?;
301                        let control_handle = WatcherControlHandle { inner: this.inner.clone() };
302                        Ok(WatcherRequest::Watch {
303                            responder: WatcherWatchResponder {
304                                control_handle: std::mem::ManuallyDrop::new(control_handle),
305                                tx_id: header.tx_id,
306                            },
307                        })
308                    }
309                    _ => Err(fidl::Error::UnknownOrdinal {
310                        ordinal: header.ordinal,
311                        protocol_name:
312                            <WatcherMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
313                    }),
314                }))
315            },
316        )
317    }
318}
319
320/// Protocol for observing changes to the system power profile.
321#[derive(Debug)]
322pub enum WatcherRequest {
323    /// Watches for changes to the system power profile.
324    ///
325    /// On a given connection, the first call will return immediately with the current system power
326    /// profile, while subsequent calls will only return a new `profile` as the system power profile
327    /// changes. This follows the
328    /// [hanging get](https://fuchsia.dev/fuchsia-src/concepts/api/fidl#hanging-get) pattern. Any
329    /// errors are considered fatal and will result in the channel being closed.
330    Watch { responder: WatcherWatchResponder },
331}
332
333impl WatcherRequest {
334    #[allow(irrefutable_let_patterns)]
335    pub fn into_watch(self) -> Option<(WatcherWatchResponder)> {
336        if let WatcherRequest::Watch { responder } = self {
337            Some((responder))
338        } else {
339            None
340        }
341    }
342
343    /// Name of the method defined in FIDL
344    pub fn method_name(&self) -> &'static str {
345        match *self {
346            WatcherRequest::Watch { .. } => "watch",
347        }
348    }
349}
350
351#[derive(Debug, Clone)]
352pub struct WatcherControlHandle {
353    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
354}
355
356impl fidl::endpoints::ControlHandle for WatcherControlHandle {
357    fn shutdown(&self) {
358        self.inner.shutdown()
359    }
360    fn shutdown_with_epitaph(&self, status: zx_status::Status) {
361        self.inner.shutdown_with_epitaph(status)
362    }
363
364    fn is_closed(&self) -> bool {
365        self.inner.channel().is_closed()
366    }
367    fn on_closed(&self) -> fidl::OnSignalsRef<'_> {
368        self.inner.channel().on_closed()
369    }
370
371    #[cfg(target_os = "fuchsia")]
372    fn signal_peer(
373        &self,
374        clear_mask: zx::Signals,
375        set_mask: zx::Signals,
376    ) -> Result<(), zx_status::Status> {
377        use fidl::Peered;
378        self.inner.channel().signal_peer(clear_mask, set_mask)
379    }
380}
381
382impl WatcherControlHandle {}
383
384#[must_use = "FIDL methods require a response to be sent"]
385#[derive(Debug)]
386pub struct WatcherWatchResponder {
387    control_handle: std::mem::ManuallyDrop<WatcherControlHandle>,
388    tx_id: u32,
389}
390
391/// Set the the channel to be shutdown (see [`WatcherControlHandle::shutdown`])
392/// if the responder is dropped without sending a response, so that the client
393/// doesn't hang. To prevent this behavior, call `drop_without_shutdown`.
394impl std::ops::Drop for WatcherWatchResponder {
395    fn drop(&mut self) {
396        self.control_handle.shutdown();
397        // Safety: drops once, never accessed again
398        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
399    }
400}
401
402impl fidl::endpoints::Responder for WatcherWatchResponder {
403    type ControlHandle = WatcherControlHandle;
404
405    fn control_handle(&self) -> &WatcherControlHandle {
406        &self.control_handle
407    }
408
409    fn drop_without_shutdown(mut self) {
410        // Safety: drops once, never accessed again due to mem::forget
411        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
412        // Prevent Drop from running (which would shut down the channel)
413        std::mem::forget(self);
414    }
415}
416
417impl WatcherWatchResponder {
418    /// Sends a response to the FIDL transaction.
419    ///
420    /// Sets the channel to shutdown if an error occurs.
421    pub fn send(self, mut profile: Profile) -> Result<(), fidl::Error> {
422        let _result = self.send_raw(profile);
423        if _result.is_err() {
424            self.control_handle.shutdown();
425        }
426        self.drop_without_shutdown();
427        _result
428    }
429
430    /// Similar to "send" but does not shutdown the channel if an error occurs.
431    pub fn send_no_shutdown_on_err(self, mut profile: Profile) -> Result<(), fidl::Error> {
432        let _result = self.send_raw(profile);
433        self.drop_without_shutdown();
434        _result
435    }
436
437    fn send_raw(&self, mut profile: Profile) -> Result<(), fidl::Error> {
438        self.control_handle.inner.send::<WatcherWatchResponse>(
439            (profile,),
440            self.tx_id,
441            0x5f29be53ad34a947,
442            fidl::encoding::DynamicFlags::empty(),
443        )
444    }
445}
446
447mod internal {
448    use super::*;
449}