fidl_fuchsia_power_clientlevel/
fidl_fuchsia_power_clientlevel.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_clientlevel__common::*;
11use futures::future::{self, MaybeDone, TryFutureExt};
12use zx_status;
13
14#[derive(Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
15pub struct ConnectorConnectRequest {
16    pub client_type: ClientType,
17    pub watcher: fidl::endpoints::ServerEnd<WatcherMarker>,
18}
19
20impl fidl::Standalone<fidl::encoding::DefaultFuchsiaResourceDialect> for ConnectorConnectRequest {}
21
22#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
23pub struct ConnectorMarker;
24
25impl fidl::endpoints::ProtocolMarker for ConnectorMarker {
26    type Proxy = ConnectorProxy;
27    type RequestStream = ConnectorRequestStream;
28    #[cfg(target_os = "fuchsia")]
29    type SynchronousProxy = ConnectorSynchronousProxy;
30
31    const DEBUG_NAME: &'static str = "fuchsia.power.clientlevel.Connector";
32}
33impl fidl::endpoints::DiscoverableProtocolMarker for ConnectorMarker {}
34
35pub trait ConnectorProxyInterface: Send + Sync {
36    fn r#connect(
37        &self,
38        client_type: ClientType,
39        watcher: fidl::endpoints::ServerEnd<WatcherMarker>,
40    ) -> Result<(), fidl::Error>;
41}
42#[derive(Debug)]
43#[cfg(target_os = "fuchsia")]
44pub struct ConnectorSynchronousProxy {
45    client: fidl::client::sync::Client,
46}
47
48#[cfg(target_os = "fuchsia")]
49impl fidl::endpoints::SynchronousProxy for ConnectorSynchronousProxy {
50    type Proxy = ConnectorProxy;
51    type Protocol = ConnectorMarker;
52
53    fn from_channel(inner: fidl::Channel) -> Self {
54        Self::new(inner)
55    }
56
57    fn into_channel(self) -> fidl::Channel {
58        self.client.into_channel()
59    }
60
61    fn as_channel(&self) -> &fidl::Channel {
62        self.client.as_channel()
63    }
64}
65
66#[cfg(target_os = "fuchsia")]
67impl ConnectorSynchronousProxy {
68    pub fn new(channel: fidl::Channel) -> Self {
69        let protocol_name = <ConnectorMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME;
70        Self { client: fidl::client::sync::Client::new(channel, protocol_name) }
71    }
72
73    pub fn into_channel(self) -> fidl::Channel {
74        self.client.into_channel()
75    }
76
77    /// Waits until an event arrives and returns it. It is safe for other
78    /// threads to make concurrent requests while waiting for an event.
79    pub fn wait_for_event(
80        &self,
81        deadline: zx::MonotonicInstant,
82    ) -> Result<ConnectorEvent, fidl::Error> {
83        ConnectorEvent::decode(self.client.wait_for_event(deadline)?)
84    }
85
86    /// Connects a [`Watcher`] to the power level of the specified
87    /// [`ClientType`].
88    ///
89    /// A client may call this method and begin using the [`Watcher`] client
90    /// endpoint immediately.
91    ///
92    /// If a power configuration does not exist for the provided `client_type`,
93    /// then the request will fail. On failure, both the `watcher` server
94    /// endpoint as well as the current `Connector` connection will be
95    /// terminated.
96    ///
97    /// + `client_type` specifies to which [`ClientType`] power level that
98    /// `watcher` should be connected. The value is valid iff a power
99    /// configuration exists for the provided `client_type`.
100    ///
101    /// + `watcher` is the server endpoint of a [`Watcher`] channel that will be
102    /// connected to the [`ClientType`] power level.
103    pub fn r#connect(
104        &self,
105        mut client_type: ClientType,
106        mut watcher: fidl::endpoints::ServerEnd<WatcherMarker>,
107    ) -> Result<(), fidl::Error> {
108        self.client.send::<ConnectorConnectRequest>(
109            (client_type, watcher),
110            0x29e603fe743fd08a,
111            fidl::encoding::DynamicFlags::empty(),
112        )
113    }
114}
115
116#[cfg(target_os = "fuchsia")]
117impl From<ConnectorSynchronousProxy> for zx::Handle {
118    fn from(value: ConnectorSynchronousProxy) -> Self {
119        value.into_channel().into()
120    }
121}
122
123#[cfg(target_os = "fuchsia")]
124impl From<fidl::Channel> for ConnectorSynchronousProxy {
125    fn from(value: fidl::Channel) -> Self {
126        Self::new(value)
127    }
128}
129
130#[cfg(target_os = "fuchsia")]
131impl fidl::endpoints::FromClient for ConnectorSynchronousProxy {
132    type Protocol = ConnectorMarker;
133
134    fn from_client(value: fidl::endpoints::ClientEnd<ConnectorMarker>) -> Self {
135        Self::new(value.into_channel())
136    }
137}
138
139#[derive(Debug, Clone)]
140pub struct ConnectorProxy {
141    client: fidl::client::Client<fidl::encoding::DefaultFuchsiaResourceDialect>,
142}
143
144impl fidl::endpoints::Proxy for ConnectorProxy {
145    type Protocol = ConnectorMarker;
146
147    fn from_channel(inner: ::fidl::AsyncChannel) -> Self {
148        Self::new(inner)
149    }
150
151    fn into_channel(self) -> Result<::fidl::AsyncChannel, Self> {
152        self.client.into_channel().map_err(|client| Self { client })
153    }
154
155    fn as_channel(&self) -> &::fidl::AsyncChannel {
156        self.client.as_channel()
157    }
158}
159
160impl ConnectorProxy {
161    /// Create a new Proxy for fuchsia.power.clientlevel/Connector.
162    pub fn new(channel: ::fidl::AsyncChannel) -> Self {
163        let protocol_name = <ConnectorMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME;
164        Self { client: fidl::client::Client::new(channel, protocol_name) }
165    }
166
167    /// Get a Stream of events from the remote end of the protocol.
168    ///
169    /// # Panics
170    ///
171    /// Panics if the event stream was already taken.
172    pub fn take_event_stream(&self) -> ConnectorEventStream {
173        ConnectorEventStream { event_receiver: self.client.take_event_receiver() }
174    }
175
176    /// Connects a [`Watcher`] to the power level of the specified
177    /// [`ClientType`].
178    ///
179    /// A client may call this method and begin using the [`Watcher`] client
180    /// endpoint immediately.
181    ///
182    /// If a power configuration does not exist for the provided `client_type`,
183    /// then the request will fail. On failure, both the `watcher` server
184    /// endpoint as well as the current `Connector` connection will be
185    /// terminated.
186    ///
187    /// + `client_type` specifies to which [`ClientType`] power level that
188    /// `watcher` should be connected. The value is valid iff a power
189    /// configuration exists for the provided `client_type`.
190    ///
191    /// + `watcher` is the server endpoint of a [`Watcher`] channel that will be
192    /// connected to the [`ClientType`] power level.
193    pub fn r#connect(
194        &self,
195        mut client_type: ClientType,
196        mut watcher: fidl::endpoints::ServerEnd<WatcherMarker>,
197    ) -> Result<(), fidl::Error> {
198        ConnectorProxyInterface::r#connect(self, client_type, watcher)
199    }
200}
201
202impl ConnectorProxyInterface for ConnectorProxy {
203    fn r#connect(
204        &self,
205        mut client_type: ClientType,
206        mut watcher: fidl::endpoints::ServerEnd<WatcherMarker>,
207    ) -> Result<(), fidl::Error> {
208        self.client.send::<ConnectorConnectRequest>(
209            (client_type, watcher),
210            0x29e603fe743fd08a,
211            fidl::encoding::DynamicFlags::empty(),
212        )
213    }
214}
215
216pub struct ConnectorEventStream {
217    event_receiver: fidl::client::EventReceiver<fidl::encoding::DefaultFuchsiaResourceDialect>,
218}
219
220impl std::marker::Unpin for ConnectorEventStream {}
221
222impl futures::stream::FusedStream for ConnectorEventStream {
223    fn is_terminated(&self) -> bool {
224        self.event_receiver.is_terminated()
225    }
226}
227
228impl futures::Stream for ConnectorEventStream {
229    type Item = Result<ConnectorEvent, fidl::Error>;
230
231    fn poll_next(
232        mut self: std::pin::Pin<&mut Self>,
233        cx: &mut std::task::Context<'_>,
234    ) -> std::task::Poll<Option<Self::Item>> {
235        match futures::ready!(futures::stream::StreamExt::poll_next_unpin(
236            &mut self.event_receiver,
237            cx
238        )?) {
239            Some(buf) => std::task::Poll::Ready(Some(ConnectorEvent::decode(buf))),
240            None => std::task::Poll::Ready(None),
241        }
242    }
243}
244
245#[derive(Debug)]
246pub enum ConnectorEvent {}
247
248impl ConnectorEvent {
249    /// Decodes a message buffer as a [`ConnectorEvent`].
250    fn decode(
251        mut buf: <fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc,
252    ) -> Result<ConnectorEvent, fidl::Error> {
253        let (bytes, _handles) = buf.split_mut();
254        let (tx_header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
255        debug_assert_eq!(tx_header.tx_id, 0);
256        match tx_header.ordinal {
257            _ => Err(fidl::Error::UnknownOrdinal {
258                ordinal: tx_header.ordinal,
259                protocol_name: <ConnectorMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
260            }),
261        }
262    }
263}
264
265/// A Stream of incoming requests for fuchsia.power.clientlevel/Connector.
266pub struct ConnectorRequestStream {
267    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
268    is_terminated: bool,
269}
270
271impl std::marker::Unpin for ConnectorRequestStream {}
272
273impl futures::stream::FusedStream for ConnectorRequestStream {
274    fn is_terminated(&self) -> bool {
275        self.is_terminated
276    }
277}
278
279impl fidl::endpoints::RequestStream for ConnectorRequestStream {
280    type Protocol = ConnectorMarker;
281    type ControlHandle = ConnectorControlHandle;
282
283    fn from_channel(channel: ::fidl::AsyncChannel) -> Self {
284        Self { inner: std::sync::Arc::new(fidl::ServeInner::new(channel)), is_terminated: false }
285    }
286
287    fn control_handle(&self) -> Self::ControlHandle {
288        ConnectorControlHandle { inner: self.inner.clone() }
289    }
290
291    fn into_inner(
292        self,
293    ) -> (::std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>, bool)
294    {
295        (self.inner, self.is_terminated)
296    }
297
298    fn from_inner(
299        inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
300        is_terminated: bool,
301    ) -> Self {
302        Self { inner, is_terminated }
303    }
304}
305
306impl futures::Stream for ConnectorRequestStream {
307    type Item = Result<ConnectorRequest, fidl::Error>;
308
309    fn poll_next(
310        mut self: std::pin::Pin<&mut Self>,
311        cx: &mut std::task::Context<'_>,
312    ) -> std::task::Poll<Option<Self::Item>> {
313        let this = &mut *self;
314        if this.inner.check_shutdown(cx) {
315            this.is_terminated = true;
316            return std::task::Poll::Ready(None);
317        }
318        if this.is_terminated {
319            panic!("polled ConnectorRequestStream after completion");
320        }
321        fidl::encoding::with_tls_decode_buf::<_, fidl::encoding::DefaultFuchsiaResourceDialect>(
322            |bytes, handles| {
323                match this.inner.channel().read_etc(cx, bytes, handles) {
324                    std::task::Poll::Ready(Ok(())) => {}
325                    std::task::Poll::Pending => return std::task::Poll::Pending,
326                    std::task::Poll::Ready(Err(zx_status::Status::PEER_CLOSED)) => {
327                        this.is_terminated = true;
328                        return std::task::Poll::Ready(None);
329                    }
330                    std::task::Poll::Ready(Err(e)) => {
331                        return std::task::Poll::Ready(Some(Err(fidl::Error::ServerRequestRead(
332                            e.into(),
333                        ))))
334                    }
335                }
336
337                // A message has been received from the channel
338                let (header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
339
340                std::task::Poll::Ready(Some(match header.ordinal {
341                    0x29e603fe743fd08a => {
342                        header.validate_request_tx_id(fidl::MethodType::OneWay)?;
343                        let mut req = fidl::new_empty!(
344                            ConnectorConnectRequest,
345                            fidl::encoding::DefaultFuchsiaResourceDialect
346                        );
347                        fidl::encoding::Decoder::<fidl::encoding::DefaultFuchsiaResourceDialect>::decode_into::<ConnectorConnectRequest>(&header, _body_bytes, handles, &mut req)?;
348                        let control_handle = ConnectorControlHandle { inner: this.inner.clone() };
349                        Ok(ConnectorRequest::Connect {
350                            client_type: req.client_type,
351                            watcher: req.watcher,
352
353                            control_handle,
354                        })
355                    }
356                    _ => Err(fidl::Error::UnknownOrdinal {
357                        ordinal: header.ordinal,
358                        protocol_name:
359                            <ConnectorMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
360                    }),
361                }))
362            },
363        )
364    }
365}
366
367/// Allows a client to connect a [`Watcher`] to the power level of a given
368/// [`ClientType`].
369#[derive(Debug)]
370pub enum ConnectorRequest {
371    /// Connects a [`Watcher`] to the power level of the specified
372    /// [`ClientType`].
373    ///
374    /// A client may call this method and begin using the [`Watcher`] client
375    /// endpoint immediately.
376    ///
377    /// If a power configuration does not exist for the provided `client_type`,
378    /// then the request will fail. On failure, both the `watcher` server
379    /// endpoint as well as the current `Connector` connection will be
380    /// terminated.
381    ///
382    /// + `client_type` specifies to which [`ClientType`] power level that
383    /// `watcher` should be connected. The value is valid iff a power
384    /// configuration exists for the provided `client_type`.
385    ///
386    /// + `watcher` is the server endpoint of a [`Watcher`] channel that will be
387    /// connected to the [`ClientType`] power level.
388    Connect {
389        client_type: ClientType,
390        watcher: fidl::endpoints::ServerEnd<WatcherMarker>,
391        control_handle: ConnectorControlHandle,
392    },
393}
394
395impl ConnectorRequest {
396    #[allow(irrefutable_let_patterns)]
397    pub fn into_connect(
398        self,
399    ) -> Option<(ClientType, fidl::endpoints::ServerEnd<WatcherMarker>, ConnectorControlHandle)>
400    {
401        if let ConnectorRequest::Connect { client_type, watcher, control_handle } = self {
402            Some((client_type, watcher, control_handle))
403        } else {
404            None
405        }
406    }
407
408    /// Name of the method defined in FIDL
409    pub fn method_name(&self) -> &'static str {
410        match *self {
411            ConnectorRequest::Connect { .. } => "connect",
412        }
413    }
414}
415
416#[derive(Debug, Clone)]
417pub struct ConnectorControlHandle {
418    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
419}
420
421impl fidl::endpoints::ControlHandle for ConnectorControlHandle {
422    fn shutdown(&self) {
423        self.inner.shutdown()
424    }
425    fn shutdown_with_epitaph(&self, status: zx_status::Status) {
426        self.inner.shutdown_with_epitaph(status)
427    }
428
429    fn is_closed(&self) -> bool {
430        self.inner.channel().is_closed()
431    }
432    fn on_closed(&self) -> fidl::OnSignalsRef<'_> {
433        self.inner.channel().on_closed()
434    }
435
436    #[cfg(target_os = "fuchsia")]
437    fn signal_peer(
438        &self,
439        clear_mask: zx::Signals,
440        set_mask: zx::Signals,
441    ) -> Result<(), zx_status::Status> {
442        use fidl::Peered;
443        self.inner.channel().signal_peer(clear_mask, set_mask)
444    }
445}
446
447impl ConnectorControlHandle {}
448
449#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
450pub struct WatcherMarker;
451
452impl fidl::endpoints::ProtocolMarker for WatcherMarker {
453    type Proxy = WatcherProxy;
454    type RequestStream = WatcherRequestStream;
455    #[cfg(target_os = "fuchsia")]
456    type SynchronousProxy = WatcherSynchronousProxy;
457
458    const DEBUG_NAME: &'static str = "(anonymous) Watcher";
459}
460
461pub trait WatcherProxyInterface: Send + Sync {
462    type WatchResponseFut: std::future::Future<Output = Result<u64, fidl::Error>> + Send;
463    fn r#watch(&self) -> Self::WatchResponseFut;
464}
465#[derive(Debug)]
466#[cfg(target_os = "fuchsia")]
467pub struct WatcherSynchronousProxy {
468    client: fidl::client::sync::Client,
469}
470
471#[cfg(target_os = "fuchsia")]
472impl fidl::endpoints::SynchronousProxy for WatcherSynchronousProxy {
473    type Proxy = WatcherProxy;
474    type Protocol = WatcherMarker;
475
476    fn from_channel(inner: fidl::Channel) -> Self {
477        Self::new(inner)
478    }
479
480    fn into_channel(self) -> fidl::Channel {
481        self.client.into_channel()
482    }
483
484    fn as_channel(&self) -> &fidl::Channel {
485        self.client.as_channel()
486    }
487}
488
489#[cfg(target_os = "fuchsia")]
490impl WatcherSynchronousProxy {
491    pub fn new(channel: fidl::Channel) -> Self {
492        let protocol_name = <WatcherMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME;
493        Self { client: fidl::client::sync::Client::new(channel, protocol_name) }
494    }
495
496    pub fn into_channel(self) -> fidl::Channel {
497        self.client.into_channel()
498    }
499
500    /// Waits until an event arrives and returns it. It is safe for other
501    /// threads to make concurrent requests while waiting for an event.
502    pub fn wait_for_event(
503        &self,
504        deadline: zx::MonotonicInstant,
505    ) -> Result<WatcherEvent, fidl::Error> {
506        WatcherEvent::decode(self.client.wait_for_event(deadline)?)
507    }
508
509    /// Watches for changes to the power level of the connected [`ClientType`].
510    ///
511    /// The power level for a given [`ClientType`] is determined according to
512    /// the power configuration for that [`ClientType`]. See the
513    /// [README.md](/src/power/power-manager/system_power_mode_config/README.md)
514    /// for more details.
515    ///
516    /// On a given connection, the first call will return immediately with the
517    /// current power level for the connected [`ClientType`]. Subsequent `Watch`
518    /// requests will only return a new `level` if the power level of the
519    /// connected [`ClientType`] has changed. This follows the [hanging
520    /// get](https://fuchsia.dev/fuchsia-src/concepts/api/fidl#hanging-get)
521    /// pattern.
522    ///
523    /// - `level` is an unsigned integer representing the power level of the
524    /// connected [`ClientType`].
525    pub fn r#watch(&self, ___deadline: zx::MonotonicInstant) -> Result<u64, fidl::Error> {
526        let _response =
527            self.client.send_query::<fidl::encoding::EmptyPayload, WatcherWatchResponse>(
528                (),
529                0x29592d2e62f4101a,
530                fidl::encoding::DynamicFlags::empty(),
531                ___deadline,
532            )?;
533        Ok(_response.level)
534    }
535}
536
537#[cfg(target_os = "fuchsia")]
538impl From<WatcherSynchronousProxy> for zx::Handle {
539    fn from(value: WatcherSynchronousProxy) -> Self {
540        value.into_channel().into()
541    }
542}
543
544#[cfg(target_os = "fuchsia")]
545impl From<fidl::Channel> for WatcherSynchronousProxy {
546    fn from(value: fidl::Channel) -> Self {
547        Self::new(value)
548    }
549}
550
551#[cfg(target_os = "fuchsia")]
552impl fidl::endpoints::FromClient for WatcherSynchronousProxy {
553    type Protocol = WatcherMarker;
554
555    fn from_client(value: fidl::endpoints::ClientEnd<WatcherMarker>) -> Self {
556        Self::new(value.into_channel())
557    }
558}
559
560#[derive(Debug, Clone)]
561pub struct WatcherProxy {
562    client: fidl::client::Client<fidl::encoding::DefaultFuchsiaResourceDialect>,
563}
564
565impl fidl::endpoints::Proxy for WatcherProxy {
566    type Protocol = WatcherMarker;
567
568    fn from_channel(inner: ::fidl::AsyncChannel) -> Self {
569        Self::new(inner)
570    }
571
572    fn into_channel(self) -> Result<::fidl::AsyncChannel, Self> {
573        self.client.into_channel().map_err(|client| Self { client })
574    }
575
576    fn as_channel(&self) -> &::fidl::AsyncChannel {
577        self.client.as_channel()
578    }
579}
580
581impl WatcherProxy {
582    /// Create a new Proxy for fuchsia.power.clientlevel/Watcher.
583    pub fn new(channel: ::fidl::AsyncChannel) -> Self {
584        let protocol_name = <WatcherMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME;
585        Self { client: fidl::client::Client::new(channel, protocol_name) }
586    }
587
588    /// Get a Stream of events from the remote end of the protocol.
589    ///
590    /// # Panics
591    ///
592    /// Panics if the event stream was already taken.
593    pub fn take_event_stream(&self) -> WatcherEventStream {
594        WatcherEventStream { event_receiver: self.client.take_event_receiver() }
595    }
596
597    /// Watches for changes to the power level of the connected [`ClientType`].
598    ///
599    /// The power level for a given [`ClientType`] is determined according to
600    /// the power configuration for that [`ClientType`]. See the
601    /// [README.md](/src/power/power-manager/system_power_mode_config/README.md)
602    /// for more details.
603    ///
604    /// On a given connection, the first call will return immediately with the
605    /// current power level for the connected [`ClientType`]. Subsequent `Watch`
606    /// requests will only return a new `level` if the power level of the
607    /// connected [`ClientType`] has changed. This follows the [hanging
608    /// get](https://fuchsia.dev/fuchsia-src/concepts/api/fidl#hanging-get)
609    /// pattern.
610    ///
611    /// - `level` is an unsigned integer representing the power level of the
612    /// connected [`ClientType`].
613    pub fn r#watch(
614        &self,
615    ) -> fidl::client::QueryResponseFut<u64, fidl::encoding::DefaultFuchsiaResourceDialect> {
616        WatcherProxyInterface::r#watch(self)
617    }
618}
619
620impl WatcherProxyInterface for WatcherProxy {
621    type WatchResponseFut =
622        fidl::client::QueryResponseFut<u64, fidl::encoding::DefaultFuchsiaResourceDialect>;
623    fn r#watch(&self) -> Self::WatchResponseFut {
624        fn _decode(
625            mut _buf: Result<<fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc, fidl::Error>,
626        ) -> Result<u64, fidl::Error> {
627            let _response = fidl::client::decode_transaction_body::<
628                WatcherWatchResponse,
629                fidl::encoding::DefaultFuchsiaResourceDialect,
630                0x29592d2e62f4101a,
631            >(_buf?)?;
632            Ok(_response.level)
633        }
634        self.client.send_query_and_decode::<fidl::encoding::EmptyPayload, u64>(
635            (),
636            0x29592d2e62f4101a,
637            fidl::encoding::DynamicFlags::empty(),
638            _decode,
639        )
640    }
641}
642
643pub struct WatcherEventStream {
644    event_receiver: fidl::client::EventReceiver<fidl::encoding::DefaultFuchsiaResourceDialect>,
645}
646
647impl std::marker::Unpin for WatcherEventStream {}
648
649impl futures::stream::FusedStream for WatcherEventStream {
650    fn is_terminated(&self) -> bool {
651        self.event_receiver.is_terminated()
652    }
653}
654
655impl futures::Stream for WatcherEventStream {
656    type Item = Result<WatcherEvent, fidl::Error>;
657
658    fn poll_next(
659        mut self: std::pin::Pin<&mut Self>,
660        cx: &mut std::task::Context<'_>,
661    ) -> std::task::Poll<Option<Self::Item>> {
662        match futures::ready!(futures::stream::StreamExt::poll_next_unpin(
663            &mut self.event_receiver,
664            cx
665        )?) {
666            Some(buf) => std::task::Poll::Ready(Some(WatcherEvent::decode(buf))),
667            None => std::task::Poll::Ready(None),
668        }
669    }
670}
671
672#[derive(Debug)]
673pub enum WatcherEvent {}
674
675impl WatcherEvent {
676    /// Decodes a message buffer as a [`WatcherEvent`].
677    fn decode(
678        mut buf: <fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc,
679    ) -> Result<WatcherEvent, fidl::Error> {
680        let (bytes, _handles) = buf.split_mut();
681        let (tx_header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
682        debug_assert_eq!(tx_header.tx_id, 0);
683        match tx_header.ordinal {
684            _ => Err(fidl::Error::UnknownOrdinal {
685                ordinal: tx_header.ordinal,
686                protocol_name: <WatcherMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
687            }),
688        }
689    }
690}
691
692/// A Stream of incoming requests for fuchsia.power.clientlevel/Watcher.
693pub struct WatcherRequestStream {
694    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
695    is_terminated: bool,
696}
697
698impl std::marker::Unpin for WatcherRequestStream {}
699
700impl futures::stream::FusedStream for WatcherRequestStream {
701    fn is_terminated(&self) -> bool {
702        self.is_terminated
703    }
704}
705
706impl fidl::endpoints::RequestStream for WatcherRequestStream {
707    type Protocol = WatcherMarker;
708    type ControlHandle = WatcherControlHandle;
709
710    fn from_channel(channel: ::fidl::AsyncChannel) -> Self {
711        Self { inner: std::sync::Arc::new(fidl::ServeInner::new(channel)), is_terminated: false }
712    }
713
714    fn control_handle(&self) -> Self::ControlHandle {
715        WatcherControlHandle { inner: self.inner.clone() }
716    }
717
718    fn into_inner(
719        self,
720    ) -> (::std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>, bool)
721    {
722        (self.inner, self.is_terminated)
723    }
724
725    fn from_inner(
726        inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
727        is_terminated: bool,
728    ) -> Self {
729        Self { inner, is_terminated }
730    }
731}
732
733impl futures::Stream for WatcherRequestStream {
734    type Item = Result<WatcherRequest, fidl::Error>;
735
736    fn poll_next(
737        mut self: std::pin::Pin<&mut Self>,
738        cx: &mut std::task::Context<'_>,
739    ) -> std::task::Poll<Option<Self::Item>> {
740        let this = &mut *self;
741        if this.inner.check_shutdown(cx) {
742            this.is_terminated = true;
743            return std::task::Poll::Ready(None);
744        }
745        if this.is_terminated {
746            panic!("polled WatcherRequestStream after completion");
747        }
748        fidl::encoding::with_tls_decode_buf::<_, fidl::encoding::DefaultFuchsiaResourceDialect>(
749            |bytes, handles| {
750                match this.inner.channel().read_etc(cx, bytes, handles) {
751                    std::task::Poll::Ready(Ok(())) => {}
752                    std::task::Poll::Pending => return std::task::Poll::Pending,
753                    std::task::Poll::Ready(Err(zx_status::Status::PEER_CLOSED)) => {
754                        this.is_terminated = true;
755                        return std::task::Poll::Ready(None);
756                    }
757                    std::task::Poll::Ready(Err(e)) => {
758                        return std::task::Poll::Ready(Some(Err(fidl::Error::ServerRequestRead(
759                            e.into(),
760                        ))))
761                    }
762                }
763
764                // A message has been received from the channel
765                let (header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
766
767                std::task::Poll::Ready(Some(match header.ordinal {
768                    0x29592d2e62f4101a => {
769                        header.validate_request_tx_id(fidl::MethodType::TwoWay)?;
770                        let mut req = fidl::new_empty!(
771                            fidl::encoding::EmptyPayload,
772                            fidl::encoding::DefaultFuchsiaResourceDialect
773                        );
774                        fidl::encoding::Decoder::<fidl::encoding::DefaultFuchsiaResourceDialect>::decode_into::<fidl::encoding::EmptyPayload>(&header, _body_bytes, handles, &mut req)?;
775                        let control_handle = WatcherControlHandle { inner: this.inner.clone() };
776                        Ok(WatcherRequest::Watch {
777                            responder: WatcherWatchResponder {
778                                control_handle: std::mem::ManuallyDrop::new(control_handle),
779                                tx_id: header.tx_id,
780                            },
781                        })
782                    }
783                    _ => Err(fidl::Error::UnknownOrdinal {
784                        ordinal: header.ordinal,
785                        protocol_name:
786                            <WatcherMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
787                    }),
788                }))
789            },
790        )
791    }
792}
793
794/// Allows a client to watch for changes to the power level of a given
795/// [`ClientType`].
796///
797/// This protocol cannot be connected to the service directly. Instead, the
798/// server endpoint of a `Watcher` channel must first be connected to the power
799/// level of the desired [`ClientType`] using the [`Connector.Connect`] method.
800/// The client endpoint of a `Watcher` channel is only useful after it has been
801/// connected in this way.
802#[derive(Debug)]
803pub enum WatcherRequest {
804    /// Watches for changes to the power level of the connected [`ClientType`].
805    ///
806    /// The power level for a given [`ClientType`] is determined according to
807    /// the power configuration for that [`ClientType`]. See the
808    /// [README.md](/src/power/power-manager/system_power_mode_config/README.md)
809    /// for more details.
810    ///
811    /// On a given connection, the first call will return immediately with the
812    /// current power level for the connected [`ClientType`]. Subsequent `Watch`
813    /// requests will only return a new `level` if the power level of the
814    /// connected [`ClientType`] has changed. This follows the [hanging
815    /// get](https://fuchsia.dev/fuchsia-src/concepts/api/fidl#hanging-get)
816    /// pattern.
817    ///
818    /// - `level` is an unsigned integer representing the power level of the
819    /// connected [`ClientType`].
820    Watch { responder: WatcherWatchResponder },
821}
822
823impl WatcherRequest {
824    #[allow(irrefutable_let_patterns)]
825    pub fn into_watch(self) -> Option<(WatcherWatchResponder)> {
826        if let WatcherRequest::Watch { responder } = self {
827            Some((responder))
828        } else {
829            None
830        }
831    }
832
833    /// Name of the method defined in FIDL
834    pub fn method_name(&self) -> &'static str {
835        match *self {
836            WatcherRequest::Watch { .. } => "watch",
837        }
838    }
839}
840
841#[derive(Debug, Clone)]
842pub struct WatcherControlHandle {
843    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
844}
845
846impl fidl::endpoints::ControlHandle for WatcherControlHandle {
847    fn shutdown(&self) {
848        self.inner.shutdown()
849    }
850    fn shutdown_with_epitaph(&self, status: zx_status::Status) {
851        self.inner.shutdown_with_epitaph(status)
852    }
853
854    fn is_closed(&self) -> bool {
855        self.inner.channel().is_closed()
856    }
857    fn on_closed(&self) -> fidl::OnSignalsRef<'_> {
858        self.inner.channel().on_closed()
859    }
860
861    #[cfg(target_os = "fuchsia")]
862    fn signal_peer(
863        &self,
864        clear_mask: zx::Signals,
865        set_mask: zx::Signals,
866    ) -> Result<(), zx_status::Status> {
867        use fidl::Peered;
868        self.inner.channel().signal_peer(clear_mask, set_mask)
869    }
870}
871
872impl WatcherControlHandle {}
873
874#[must_use = "FIDL methods require a response to be sent"]
875#[derive(Debug)]
876pub struct WatcherWatchResponder {
877    control_handle: std::mem::ManuallyDrop<WatcherControlHandle>,
878    tx_id: u32,
879}
880
881/// Set the the channel to be shutdown (see [`WatcherControlHandle::shutdown`])
882/// if the responder is dropped without sending a response, so that the client
883/// doesn't hang. To prevent this behavior, call `drop_without_shutdown`.
884impl std::ops::Drop for WatcherWatchResponder {
885    fn drop(&mut self) {
886        self.control_handle.shutdown();
887        // Safety: drops once, never accessed again
888        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
889    }
890}
891
892impl fidl::endpoints::Responder for WatcherWatchResponder {
893    type ControlHandle = WatcherControlHandle;
894
895    fn control_handle(&self) -> &WatcherControlHandle {
896        &self.control_handle
897    }
898
899    fn drop_without_shutdown(mut self) {
900        // Safety: drops once, never accessed again due to mem::forget
901        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
902        // Prevent Drop from running (which would shut down the channel)
903        std::mem::forget(self);
904    }
905}
906
907impl WatcherWatchResponder {
908    /// Sends a response to the FIDL transaction.
909    ///
910    /// Sets the channel to shutdown if an error occurs.
911    pub fn send(self, mut level: u64) -> Result<(), fidl::Error> {
912        let _result = self.send_raw(level);
913        if _result.is_err() {
914            self.control_handle.shutdown();
915        }
916        self.drop_without_shutdown();
917        _result
918    }
919
920    /// Similar to "send" but does not shutdown the channel if an error occurs.
921    pub fn send_no_shutdown_on_err(self, mut level: u64) -> Result<(), fidl::Error> {
922        let _result = self.send_raw(level);
923        self.drop_without_shutdown();
924        _result
925    }
926
927    fn send_raw(&self, mut level: u64) -> Result<(), fidl::Error> {
928        self.control_handle.inner.send::<WatcherWatchResponse>(
929            (level,),
930            self.tx_id,
931            0x29592d2e62f4101a,
932            fidl::encoding::DynamicFlags::empty(),
933        )
934    }
935}
936
937mod internal {
938    use super::*;
939
940    impl fidl::encoding::ResourceTypeMarker for ConnectorConnectRequest {
941        type Borrowed<'a> = &'a mut Self;
942        fn take_or_borrow<'a>(
943            value: &'a mut <Self as fidl::encoding::TypeMarker>::Owned,
944        ) -> Self::Borrowed<'a> {
945            value
946        }
947    }
948
949    unsafe impl fidl::encoding::TypeMarker for ConnectorConnectRequest {
950        type Owned = Self;
951
952        #[inline(always)]
953        fn inline_align(_context: fidl::encoding::Context) -> usize {
954            4
955        }
956
957        #[inline(always)]
958        fn inline_size(_context: fidl::encoding::Context) -> usize {
959            8
960        }
961    }
962
963    unsafe impl
964        fidl::encoding::Encode<
965            ConnectorConnectRequest,
966            fidl::encoding::DefaultFuchsiaResourceDialect,
967        > for &mut ConnectorConnectRequest
968    {
969        #[inline]
970        unsafe fn encode(
971            self,
972            encoder: &mut fidl::encoding::Encoder<
973                '_,
974                fidl::encoding::DefaultFuchsiaResourceDialect,
975            >,
976            offset: usize,
977            _depth: fidl::encoding::Depth,
978        ) -> fidl::Result<()> {
979            encoder.debug_check_bounds::<ConnectorConnectRequest>(offset);
980            // Delegate to tuple encoding.
981            fidl::encoding::Encode::<ConnectorConnectRequest, fidl::encoding::DefaultFuchsiaResourceDialect>::encode(
982                (
983                    <ClientType as fidl::encoding::ValueTypeMarker>::borrow(&self.client_type),
984                    <fidl::encoding::Endpoint<fidl::endpoints::ServerEnd<WatcherMarker>> as fidl::encoding::ResourceTypeMarker>::take_or_borrow(&mut self.watcher),
985                ),
986                encoder, offset, _depth
987            )
988        }
989    }
990    unsafe impl<
991            T0: fidl::encoding::Encode<ClientType, fidl::encoding::DefaultFuchsiaResourceDialect>,
992            T1: fidl::encoding::Encode<
993                fidl::encoding::Endpoint<fidl::endpoints::ServerEnd<WatcherMarker>>,
994                fidl::encoding::DefaultFuchsiaResourceDialect,
995            >,
996        >
997        fidl::encoding::Encode<
998            ConnectorConnectRequest,
999            fidl::encoding::DefaultFuchsiaResourceDialect,
1000        > for (T0, T1)
1001    {
1002        #[inline]
1003        unsafe fn encode(
1004            self,
1005            encoder: &mut fidl::encoding::Encoder<
1006                '_,
1007                fidl::encoding::DefaultFuchsiaResourceDialect,
1008            >,
1009            offset: usize,
1010            depth: fidl::encoding::Depth,
1011        ) -> fidl::Result<()> {
1012            encoder.debug_check_bounds::<ConnectorConnectRequest>(offset);
1013            // Zero out padding regions. There's no need to apply masks
1014            // because the unmasked parts will be overwritten by fields.
1015            // Write the fields.
1016            self.0.encode(encoder, offset + 0, depth)?;
1017            self.1.encode(encoder, offset + 4, depth)?;
1018            Ok(())
1019        }
1020    }
1021
1022    impl fidl::encoding::Decode<Self, fidl::encoding::DefaultFuchsiaResourceDialect>
1023        for ConnectorConnectRequest
1024    {
1025        #[inline(always)]
1026        fn new_empty() -> Self {
1027            Self {
1028                client_type: fidl::new_empty!(
1029                    ClientType,
1030                    fidl::encoding::DefaultFuchsiaResourceDialect
1031                ),
1032                watcher: fidl::new_empty!(
1033                    fidl::encoding::Endpoint<fidl::endpoints::ServerEnd<WatcherMarker>>,
1034                    fidl::encoding::DefaultFuchsiaResourceDialect
1035                ),
1036            }
1037        }
1038
1039        #[inline]
1040        unsafe fn decode(
1041            &mut self,
1042            decoder: &mut fidl::encoding::Decoder<
1043                '_,
1044                fidl::encoding::DefaultFuchsiaResourceDialect,
1045            >,
1046            offset: usize,
1047            _depth: fidl::encoding::Depth,
1048        ) -> fidl::Result<()> {
1049            decoder.debug_check_bounds::<Self>(offset);
1050            // Verify that padding bytes are zero.
1051            fidl::decode!(
1052                ClientType,
1053                fidl::encoding::DefaultFuchsiaResourceDialect,
1054                &mut self.client_type,
1055                decoder,
1056                offset + 0,
1057                _depth
1058            )?;
1059            fidl::decode!(
1060                fidl::encoding::Endpoint<fidl::endpoints::ServerEnd<WatcherMarker>>,
1061                fidl::encoding::DefaultFuchsiaResourceDialect,
1062                &mut self.watcher,
1063                decoder,
1064                offset + 4,
1065                _depth
1066            )?;
1067            Ok(())
1068        }
1069    }
1070}