Skip to main content

fidl_fuchsia_hardware_usb_policy/
fidl_fuchsia_hardware_usb_policy.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_hardware_usb_policy__common::*;
11use futures::future::{self, MaybeDone, TryFutureExt};
12use zx_status;
13
14#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
15pub struct ControllerMarker;
16
17impl fidl::endpoints::ProtocolMarker for ControllerMarker {
18    type Proxy = ControllerProxy;
19    type RequestStream = ControllerRequestStream;
20    #[cfg(target_os = "fuchsia")]
21    type SynchronousProxy = ControllerSynchronousProxy;
22
23    const DEBUG_NAME: &'static str = "(anonymous) Controller";
24}
25
26pub trait ControllerProxyInterface: Send + Sync {
27    type WatchDeviceStateResponseFut: std::future::Future<Output = Result<DeviceStateWatcherWatchDeviceStateResult, fidl::Error>>
28        + Send;
29    fn r#watch_device_state(&self) -> Self::WatchDeviceStateResponseFut;
30}
31#[derive(Debug)]
32#[cfg(target_os = "fuchsia")]
33pub struct ControllerSynchronousProxy {
34    client: fidl::client::sync::Client,
35}
36
37#[cfg(target_os = "fuchsia")]
38impl fidl::endpoints::SynchronousProxy for ControllerSynchronousProxy {
39    type Proxy = ControllerProxy;
40    type Protocol = ControllerMarker;
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 ControllerSynchronousProxy {
57    pub fn new(channel: fidl::Channel) -> Self {
58        Self { client: fidl::client::sync::Client::new(channel) }
59    }
60
61    pub fn into_channel(self) -> fidl::Channel {
62        self.client.into_channel()
63    }
64
65    /// Waits until an event arrives and returns it. It is safe for other
66    /// threads to make concurrent requests while waiting for an event.
67    pub fn wait_for_event(
68        &self,
69        deadline: zx::MonotonicInstant,
70    ) -> Result<ControllerEvent, fidl::Error> {
71        ControllerEvent::decode(self.client.wait_for_event::<ControllerMarker>(deadline)?)
72    }
73
74    /// Notify a client of an updated device state value via a hanging get.
75    /// The first time this is called, it will return right away with the
76    /// current state. Subsequent calls will hang until there is a change
77    /// to report.
78    /// Returns a table containing the updated device state.
79    pub fn r#watch_device_state(
80        &self,
81        ___deadline: zx::MonotonicInstant,
82    ) -> Result<DeviceStateWatcherWatchDeviceStateResult, fidl::Error> {
83        let _response = self.client.send_query::<
84            fidl::encoding::EmptyPayload,
85            fidl::encoding::FlexibleResultType<DeviceStateUpdate, i32>,
86            ControllerMarker,
87        >(
88            (),
89            0x44628a2275753738,
90            fidl::encoding::DynamicFlags::FLEXIBLE,
91            ___deadline,
92        )?
93        .into_result::<ControllerMarker>("watch_device_state")?;
94        Ok(_response.map(|x| x))
95    }
96}
97
98#[cfg(target_os = "fuchsia")]
99impl From<ControllerSynchronousProxy> for zx::NullableHandle {
100    fn from(value: ControllerSynchronousProxy) -> Self {
101        value.into_channel().into()
102    }
103}
104
105#[cfg(target_os = "fuchsia")]
106impl From<fidl::Channel> for ControllerSynchronousProxy {
107    fn from(value: fidl::Channel) -> Self {
108        Self::new(value)
109    }
110}
111
112#[cfg(target_os = "fuchsia")]
113impl fidl::endpoints::FromClient for ControllerSynchronousProxy {
114    type Protocol = ControllerMarker;
115
116    fn from_client(value: fidl::endpoints::ClientEnd<ControllerMarker>) -> Self {
117        Self::new(value.into_channel())
118    }
119}
120
121#[derive(Debug, Clone)]
122pub struct ControllerProxy {
123    client: fidl::client::Client<fidl::encoding::DefaultFuchsiaResourceDialect>,
124}
125
126impl fidl::endpoints::Proxy for ControllerProxy {
127    type Protocol = ControllerMarker;
128
129    fn from_channel(inner: ::fidl::AsyncChannel) -> Self {
130        Self::new(inner)
131    }
132
133    fn into_channel(self) -> Result<::fidl::AsyncChannel, Self> {
134        self.client.into_channel().map_err(|client| Self { client })
135    }
136
137    fn as_channel(&self) -> &::fidl::AsyncChannel {
138        self.client.as_channel()
139    }
140}
141
142impl ControllerProxy {
143    /// Create a new Proxy for fuchsia.hardware.usb.policy/Controller.
144    pub fn new(channel: ::fidl::AsyncChannel) -> Self {
145        let protocol_name = <ControllerMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME;
146        Self { client: fidl::client::Client::new(channel, protocol_name) }
147    }
148
149    /// Get a Stream of events from the remote end of the protocol.
150    ///
151    /// # Panics
152    ///
153    /// Panics if the event stream was already taken.
154    pub fn take_event_stream(&self) -> ControllerEventStream {
155        ControllerEventStream { event_receiver: self.client.take_event_receiver() }
156    }
157
158    /// Notify a client of an updated device state value via a hanging get.
159    /// The first time this is called, it will return right away with the
160    /// current state. Subsequent calls will hang until there is a change
161    /// to report.
162    /// Returns a table containing the updated device state.
163    pub fn r#watch_device_state(
164        &self,
165    ) -> fidl::client::QueryResponseFut<
166        DeviceStateWatcherWatchDeviceStateResult,
167        fidl::encoding::DefaultFuchsiaResourceDialect,
168    > {
169        ControllerProxyInterface::r#watch_device_state(self)
170    }
171}
172
173impl ControllerProxyInterface for ControllerProxy {
174    type WatchDeviceStateResponseFut = fidl::client::QueryResponseFut<
175        DeviceStateWatcherWatchDeviceStateResult,
176        fidl::encoding::DefaultFuchsiaResourceDialect,
177    >;
178    fn r#watch_device_state(&self) -> Self::WatchDeviceStateResponseFut {
179        fn _decode(
180            mut _buf: Result<<fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc, fidl::Error>,
181        ) -> Result<DeviceStateWatcherWatchDeviceStateResult, fidl::Error> {
182            let _response = fidl::client::decode_transaction_body::<
183                fidl::encoding::FlexibleResultType<DeviceStateUpdate, i32>,
184                fidl::encoding::DefaultFuchsiaResourceDialect,
185                0x44628a2275753738,
186            >(_buf?)?
187            .into_result::<ControllerMarker>("watch_device_state")?;
188            Ok(_response.map(|x| x))
189        }
190        self.client.send_query_and_decode::<
191            fidl::encoding::EmptyPayload,
192            DeviceStateWatcherWatchDeviceStateResult,
193        >(
194            (),
195            0x44628a2275753738,
196            fidl::encoding::DynamicFlags::FLEXIBLE,
197            _decode,
198        )
199    }
200}
201
202pub struct ControllerEventStream {
203    event_receiver: fidl::client::EventReceiver<fidl::encoding::DefaultFuchsiaResourceDialect>,
204}
205
206impl std::marker::Unpin for ControllerEventStream {}
207
208impl futures::stream::FusedStream for ControllerEventStream {
209    fn is_terminated(&self) -> bool {
210        self.event_receiver.is_terminated()
211    }
212}
213
214impl futures::Stream for ControllerEventStream {
215    type Item = Result<ControllerEvent, fidl::Error>;
216
217    fn poll_next(
218        mut self: std::pin::Pin<&mut Self>,
219        cx: &mut std::task::Context<'_>,
220    ) -> std::task::Poll<Option<Self::Item>> {
221        match futures::ready!(futures::stream::StreamExt::poll_next_unpin(
222            &mut self.event_receiver,
223            cx
224        )?) {
225            Some(buf) => std::task::Poll::Ready(Some(ControllerEvent::decode(buf))),
226            None => std::task::Poll::Ready(None),
227        }
228    }
229}
230
231#[derive(Debug)]
232pub enum ControllerEvent {
233    #[non_exhaustive]
234    _UnknownEvent {
235        /// Ordinal of the event that was sent.
236        ordinal: u64,
237    },
238}
239
240impl ControllerEvent {
241    /// Decodes a message buffer as a [`ControllerEvent`].
242    fn decode(
243        mut buf: <fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc,
244    ) -> Result<ControllerEvent, fidl::Error> {
245        let (bytes, _handles) = buf.split_mut();
246        let (tx_header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
247        debug_assert_eq!(tx_header.tx_id, 0);
248        match tx_header.ordinal {
249            _ if tx_header.dynamic_flags().contains(fidl::encoding::DynamicFlags::FLEXIBLE) => {
250                Ok(ControllerEvent::_UnknownEvent { ordinal: tx_header.ordinal })
251            }
252            _ => Err(fidl::Error::UnknownOrdinal {
253                ordinal: tx_header.ordinal,
254                protocol_name: <ControllerMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
255            }),
256        }
257    }
258}
259
260/// A Stream of incoming requests for fuchsia.hardware.usb.policy/Controller.
261pub struct ControllerRequestStream {
262    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
263    is_terminated: bool,
264}
265
266impl std::marker::Unpin for ControllerRequestStream {}
267
268impl futures::stream::FusedStream for ControllerRequestStream {
269    fn is_terminated(&self) -> bool {
270        self.is_terminated
271    }
272}
273
274impl fidl::endpoints::RequestStream for ControllerRequestStream {
275    type Protocol = ControllerMarker;
276    type ControlHandle = ControllerControlHandle;
277
278    fn from_channel(channel: ::fidl::AsyncChannel) -> Self {
279        Self { inner: std::sync::Arc::new(fidl::ServeInner::new(channel)), is_terminated: false }
280    }
281
282    fn control_handle(&self) -> Self::ControlHandle {
283        ControllerControlHandle { inner: self.inner.clone() }
284    }
285
286    fn into_inner(
287        self,
288    ) -> (::std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>, bool)
289    {
290        (self.inner, self.is_terminated)
291    }
292
293    fn from_inner(
294        inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
295        is_terminated: bool,
296    ) -> Self {
297        Self { inner, is_terminated }
298    }
299}
300
301impl futures::Stream for ControllerRequestStream {
302    type Item = Result<ControllerRequest, fidl::Error>;
303
304    fn poll_next(
305        mut self: std::pin::Pin<&mut Self>,
306        cx: &mut std::task::Context<'_>,
307    ) -> std::task::Poll<Option<Self::Item>> {
308        let this = &mut *self;
309        if this.inner.check_shutdown(cx) {
310            this.is_terminated = true;
311            return std::task::Poll::Ready(None);
312        }
313        if this.is_terminated {
314            panic!("polled ControllerRequestStream after completion");
315        }
316        fidl::encoding::with_tls_decode_buf::<_, fidl::encoding::DefaultFuchsiaResourceDialect>(
317            |bytes, handles| {
318                match this.inner.channel().read_etc(cx, bytes, handles) {
319                    std::task::Poll::Ready(Ok(())) => {}
320                    std::task::Poll::Pending => return std::task::Poll::Pending,
321                    std::task::Poll::Ready(Err(zx_status::Status::PEER_CLOSED)) => {
322                        this.is_terminated = true;
323                        return std::task::Poll::Ready(None);
324                    }
325                    std::task::Poll::Ready(Err(e)) => {
326                        return std::task::Poll::Ready(Some(Err(fidl::Error::ServerRequestRead(
327                            e.into(),
328                        ))));
329                    }
330                }
331
332                // A message has been received from the channel
333                let (header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
334
335                std::task::Poll::Ready(Some(match header.ordinal {
336                    0x44628a2275753738 => {
337                        header.validate_request_tx_id(fidl::MethodType::TwoWay)?;
338                        let mut req = fidl::new_empty!(
339                            fidl::encoding::EmptyPayload,
340                            fidl::encoding::DefaultFuchsiaResourceDialect
341                        );
342                        fidl::encoding::Decoder::<fidl::encoding::DefaultFuchsiaResourceDialect>::decode_into::<fidl::encoding::EmptyPayload>(&header, _body_bytes, handles, &mut req)?;
343                        let control_handle = ControllerControlHandle { inner: this.inner.clone() };
344                        Ok(ControllerRequest::WatchDeviceState {
345                            responder: ControllerWatchDeviceStateResponder {
346                                control_handle: std::mem::ManuallyDrop::new(control_handle),
347                                tx_id: header.tx_id,
348                            },
349                        })
350                    }
351                    _ if header.tx_id == 0
352                        && header
353                            .dynamic_flags()
354                            .contains(fidl::encoding::DynamicFlags::FLEXIBLE) =>
355                    {
356                        Ok(ControllerRequest::_UnknownMethod {
357                            ordinal: header.ordinal,
358                            control_handle: ControllerControlHandle { inner: this.inner.clone() },
359                            method_type: fidl::MethodType::OneWay,
360                        })
361                    }
362                    _ if header
363                        .dynamic_flags()
364                        .contains(fidl::encoding::DynamicFlags::FLEXIBLE) =>
365                    {
366                        this.inner.send_framework_err(
367                            fidl::encoding::FrameworkErr::UnknownMethod,
368                            header.tx_id,
369                            header.ordinal,
370                            header.dynamic_flags(),
371                            (bytes, handles),
372                        )?;
373                        Ok(ControllerRequest::_UnknownMethod {
374                            ordinal: header.ordinal,
375                            control_handle: ControllerControlHandle { inner: this.inner.clone() },
376                            method_type: fidl::MethodType::TwoWay,
377                        })
378                    }
379                    _ => Err(fidl::Error::UnknownOrdinal {
380                        ordinal: header.ordinal,
381                        protocol_name:
382                            <ControllerMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
383                    }),
384                }))
385            },
386        )
387    }
388}
389
390/// Protocol for communicating with a low-level USB hardware controller.
391///
392/// This interface allows the USB policy component to act as a client and monitor
393/// the hardware's state.
394#[derive(Debug)]
395pub enum ControllerRequest {
396    /// Notify a client of an updated device state value via a hanging get.
397    /// The first time this is called, it will return right away with the
398    /// current state. Subsequent calls will hang until there is a change
399    /// to report.
400    /// Returns a table containing the updated device state.
401    WatchDeviceState { responder: ControllerWatchDeviceStateResponder },
402    /// An interaction was received which does not match any known method.
403    #[non_exhaustive]
404    _UnknownMethod {
405        /// Ordinal of the method that was called.
406        ordinal: u64,
407        control_handle: ControllerControlHandle,
408        method_type: fidl::MethodType,
409    },
410}
411
412impl ControllerRequest {
413    #[allow(irrefutable_let_patterns)]
414    pub fn into_watch_device_state(self) -> Option<(ControllerWatchDeviceStateResponder)> {
415        if let ControllerRequest::WatchDeviceState { responder } = self {
416            Some((responder))
417        } else {
418            None
419        }
420    }
421
422    /// Name of the method defined in FIDL
423    pub fn method_name(&self) -> &'static str {
424        match *self {
425            ControllerRequest::WatchDeviceState { .. } => "watch_device_state",
426            ControllerRequest::_UnknownMethod { method_type: fidl::MethodType::OneWay, .. } => {
427                "unknown one-way method"
428            }
429            ControllerRequest::_UnknownMethod { method_type: fidl::MethodType::TwoWay, .. } => {
430                "unknown two-way method"
431            }
432        }
433    }
434}
435
436#[derive(Debug, Clone)]
437pub struct ControllerControlHandle {
438    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
439}
440
441impl fidl::endpoints::ControlHandle for ControllerControlHandle {
442    fn shutdown(&self) {
443        self.inner.shutdown()
444    }
445
446    fn shutdown_with_epitaph(&self, status: zx_status::Status) {
447        self.inner.shutdown_with_epitaph(status)
448    }
449
450    fn is_closed(&self) -> bool {
451        self.inner.channel().is_closed()
452    }
453    fn on_closed(&self) -> fidl::OnSignalsRef<'_> {
454        self.inner.channel().on_closed()
455    }
456
457    #[cfg(target_os = "fuchsia")]
458    fn signal_peer(
459        &self,
460        clear_mask: zx::Signals,
461        set_mask: zx::Signals,
462    ) -> Result<(), zx_status::Status> {
463        use fidl::Peered;
464        self.inner.channel().signal_peer(clear_mask, set_mask)
465    }
466}
467
468impl ControllerControlHandle {}
469
470#[must_use = "FIDL methods require a response to be sent"]
471#[derive(Debug)]
472pub struct ControllerWatchDeviceStateResponder {
473    control_handle: std::mem::ManuallyDrop<ControllerControlHandle>,
474    tx_id: u32,
475}
476
477/// Set the the channel to be shutdown (see [`ControllerControlHandle::shutdown`])
478/// if the responder is dropped without sending a response, so that the client
479/// doesn't hang. To prevent this behavior, call `drop_without_shutdown`.
480impl std::ops::Drop for ControllerWatchDeviceStateResponder {
481    fn drop(&mut self) {
482        self.control_handle.shutdown();
483        // Safety: drops once, never accessed again
484        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
485    }
486}
487
488impl fidl::endpoints::Responder for ControllerWatchDeviceStateResponder {
489    type ControlHandle = ControllerControlHandle;
490
491    fn control_handle(&self) -> &ControllerControlHandle {
492        &self.control_handle
493    }
494
495    fn drop_without_shutdown(mut self) {
496        // Safety: drops once, never accessed again due to mem::forget
497        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
498        // Prevent Drop from running (which would shut down the channel)
499        std::mem::forget(self);
500    }
501}
502
503impl ControllerWatchDeviceStateResponder {
504    /// Sends a response to the FIDL transaction.
505    ///
506    /// Sets the channel to shutdown if an error occurs.
507    pub fn send(self, mut result: Result<&DeviceStateUpdate, i32>) -> Result<(), fidl::Error> {
508        let _result = self.send_raw(result);
509        if _result.is_err() {
510            self.control_handle.shutdown();
511        }
512        self.drop_without_shutdown();
513        _result
514    }
515
516    /// Similar to "send" but does not shutdown the channel if an error occurs.
517    pub fn send_no_shutdown_on_err(
518        self,
519        mut result: Result<&DeviceStateUpdate, i32>,
520    ) -> Result<(), fidl::Error> {
521        let _result = self.send_raw(result);
522        self.drop_without_shutdown();
523        _result
524    }
525
526    fn send_raw(&self, mut result: Result<&DeviceStateUpdate, i32>) -> Result<(), fidl::Error> {
527        self.control_handle
528            .inner
529            .send::<fidl::encoding::FlexibleResultType<DeviceStateUpdate, i32>>(
530                fidl::encoding::FlexibleResult::new(result),
531                self.tx_id,
532                0x44628a2275753738,
533                fidl::encoding::DynamicFlags::FLEXIBLE,
534            )
535    }
536}
537
538#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
539pub struct DeviceStateWatcherMarker;
540
541impl fidl::endpoints::ProtocolMarker for DeviceStateWatcherMarker {
542    type Proxy = DeviceStateWatcherProxy;
543    type RequestStream = DeviceStateWatcherRequestStream;
544    #[cfg(target_os = "fuchsia")]
545    type SynchronousProxy = DeviceStateWatcherSynchronousProxy;
546
547    const DEBUG_NAME: &'static str = "(anonymous) DeviceStateWatcher";
548}
549pub type DeviceStateWatcherWatchDeviceStateResult = Result<DeviceStateUpdate, i32>;
550
551pub trait DeviceStateWatcherProxyInterface: Send + Sync {
552    type WatchDeviceStateResponseFut: std::future::Future<Output = Result<DeviceStateWatcherWatchDeviceStateResult, fidl::Error>>
553        + Send;
554    fn r#watch_device_state(&self) -> Self::WatchDeviceStateResponseFut;
555}
556#[derive(Debug)]
557#[cfg(target_os = "fuchsia")]
558pub struct DeviceStateWatcherSynchronousProxy {
559    client: fidl::client::sync::Client,
560}
561
562#[cfg(target_os = "fuchsia")]
563impl fidl::endpoints::SynchronousProxy for DeviceStateWatcherSynchronousProxy {
564    type Proxy = DeviceStateWatcherProxy;
565    type Protocol = DeviceStateWatcherMarker;
566
567    fn from_channel(inner: fidl::Channel) -> Self {
568        Self::new(inner)
569    }
570
571    fn into_channel(self) -> fidl::Channel {
572        self.client.into_channel()
573    }
574
575    fn as_channel(&self) -> &fidl::Channel {
576        self.client.as_channel()
577    }
578}
579
580#[cfg(target_os = "fuchsia")]
581impl DeviceStateWatcherSynchronousProxy {
582    pub fn new(channel: fidl::Channel) -> Self {
583        Self { client: fidl::client::sync::Client::new(channel) }
584    }
585
586    pub fn into_channel(self) -> fidl::Channel {
587        self.client.into_channel()
588    }
589
590    /// Waits until an event arrives and returns it. It is safe for other
591    /// threads to make concurrent requests while waiting for an event.
592    pub fn wait_for_event(
593        &self,
594        deadline: zx::MonotonicInstant,
595    ) -> Result<DeviceStateWatcherEvent, fidl::Error> {
596        DeviceStateWatcherEvent::decode(
597            self.client.wait_for_event::<DeviceStateWatcherMarker>(deadline)?,
598        )
599    }
600
601    /// Notify a client of an updated device state value via a hanging get.
602    /// The first time this is called, it will return right away with the
603    /// current state. Subsequent calls will hang until there is a change
604    /// to report.
605    /// Returns a table containing the updated device state.
606    pub fn r#watch_device_state(
607        &self,
608        ___deadline: zx::MonotonicInstant,
609    ) -> Result<DeviceStateWatcherWatchDeviceStateResult, fidl::Error> {
610        let _response = self.client.send_query::<
611            fidl::encoding::EmptyPayload,
612            fidl::encoding::FlexibleResultType<DeviceStateUpdate, i32>,
613            DeviceStateWatcherMarker,
614        >(
615            (),
616            0x44628a2275753738,
617            fidl::encoding::DynamicFlags::FLEXIBLE,
618            ___deadline,
619        )?
620        .into_result::<DeviceStateWatcherMarker>("watch_device_state")?;
621        Ok(_response.map(|x| x))
622    }
623}
624
625#[cfg(target_os = "fuchsia")]
626impl From<DeviceStateWatcherSynchronousProxy> for zx::NullableHandle {
627    fn from(value: DeviceStateWatcherSynchronousProxy) -> Self {
628        value.into_channel().into()
629    }
630}
631
632#[cfg(target_os = "fuchsia")]
633impl From<fidl::Channel> for DeviceStateWatcherSynchronousProxy {
634    fn from(value: fidl::Channel) -> Self {
635        Self::new(value)
636    }
637}
638
639#[cfg(target_os = "fuchsia")]
640impl fidl::endpoints::FromClient for DeviceStateWatcherSynchronousProxy {
641    type Protocol = DeviceStateWatcherMarker;
642
643    fn from_client(value: fidl::endpoints::ClientEnd<DeviceStateWatcherMarker>) -> Self {
644        Self::new(value.into_channel())
645    }
646}
647
648#[derive(Debug, Clone)]
649pub struct DeviceStateWatcherProxy {
650    client: fidl::client::Client<fidl::encoding::DefaultFuchsiaResourceDialect>,
651}
652
653impl fidl::endpoints::Proxy for DeviceStateWatcherProxy {
654    type Protocol = DeviceStateWatcherMarker;
655
656    fn from_channel(inner: ::fidl::AsyncChannel) -> Self {
657        Self::new(inner)
658    }
659
660    fn into_channel(self) -> Result<::fidl::AsyncChannel, Self> {
661        self.client.into_channel().map_err(|client| Self { client })
662    }
663
664    fn as_channel(&self) -> &::fidl::AsyncChannel {
665        self.client.as_channel()
666    }
667}
668
669impl DeviceStateWatcherProxy {
670    /// Create a new Proxy for fuchsia.hardware.usb.policy/DeviceStateWatcher.
671    pub fn new(channel: ::fidl::AsyncChannel) -> Self {
672        let protocol_name =
673            <DeviceStateWatcherMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME;
674        Self { client: fidl::client::Client::new(channel, protocol_name) }
675    }
676
677    /// Get a Stream of events from the remote end of the protocol.
678    ///
679    /// # Panics
680    ///
681    /// Panics if the event stream was already taken.
682    pub fn take_event_stream(&self) -> DeviceStateWatcherEventStream {
683        DeviceStateWatcherEventStream { event_receiver: self.client.take_event_receiver() }
684    }
685
686    /// Notify a client of an updated device state value via a hanging get.
687    /// The first time this is called, it will return right away with the
688    /// current state. Subsequent calls will hang until there is a change
689    /// to report.
690    /// Returns a table containing the updated device state.
691    pub fn r#watch_device_state(
692        &self,
693    ) -> fidl::client::QueryResponseFut<
694        DeviceStateWatcherWatchDeviceStateResult,
695        fidl::encoding::DefaultFuchsiaResourceDialect,
696    > {
697        DeviceStateWatcherProxyInterface::r#watch_device_state(self)
698    }
699}
700
701impl DeviceStateWatcherProxyInterface for DeviceStateWatcherProxy {
702    type WatchDeviceStateResponseFut = fidl::client::QueryResponseFut<
703        DeviceStateWatcherWatchDeviceStateResult,
704        fidl::encoding::DefaultFuchsiaResourceDialect,
705    >;
706    fn r#watch_device_state(&self) -> Self::WatchDeviceStateResponseFut {
707        fn _decode(
708            mut _buf: Result<<fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc, fidl::Error>,
709        ) -> Result<DeviceStateWatcherWatchDeviceStateResult, fidl::Error> {
710            let _response = fidl::client::decode_transaction_body::<
711                fidl::encoding::FlexibleResultType<DeviceStateUpdate, i32>,
712                fidl::encoding::DefaultFuchsiaResourceDialect,
713                0x44628a2275753738,
714            >(_buf?)?
715            .into_result::<DeviceStateWatcherMarker>("watch_device_state")?;
716            Ok(_response.map(|x| x))
717        }
718        self.client.send_query_and_decode::<
719            fidl::encoding::EmptyPayload,
720            DeviceStateWatcherWatchDeviceStateResult,
721        >(
722            (),
723            0x44628a2275753738,
724            fidl::encoding::DynamicFlags::FLEXIBLE,
725            _decode,
726        )
727    }
728}
729
730pub struct DeviceStateWatcherEventStream {
731    event_receiver: fidl::client::EventReceiver<fidl::encoding::DefaultFuchsiaResourceDialect>,
732}
733
734impl std::marker::Unpin for DeviceStateWatcherEventStream {}
735
736impl futures::stream::FusedStream for DeviceStateWatcherEventStream {
737    fn is_terminated(&self) -> bool {
738        self.event_receiver.is_terminated()
739    }
740}
741
742impl futures::Stream for DeviceStateWatcherEventStream {
743    type Item = Result<DeviceStateWatcherEvent, fidl::Error>;
744
745    fn poll_next(
746        mut self: std::pin::Pin<&mut Self>,
747        cx: &mut std::task::Context<'_>,
748    ) -> std::task::Poll<Option<Self::Item>> {
749        match futures::ready!(futures::stream::StreamExt::poll_next_unpin(
750            &mut self.event_receiver,
751            cx
752        )?) {
753            Some(buf) => std::task::Poll::Ready(Some(DeviceStateWatcherEvent::decode(buf))),
754            None => std::task::Poll::Ready(None),
755        }
756    }
757}
758
759#[derive(Debug)]
760pub enum DeviceStateWatcherEvent {
761    #[non_exhaustive]
762    _UnknownEvent {
763        /// Ordinal of the event that was sent.
764        ordinal: u64,
765    },
766}
767
768impl DeviceStateWatcherEvent {
769    /// Decodes a message buffer as a [`DeviceStateWatcherEvent`].
770    fn decode(
771        mut buf: <fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc,
772    ) -> Result<DeviceStateWatcherEvent, fidl::Error> {
773        let (bytes, _handles) = buf.split_mut();
774        let (tx_header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
775        debug_assert_eq!(tx_header.tx_id, 0);
776        match tx_header.ordinal {
777            _ if tx_header.dynamic_flags().contains(fidl::encoding::DynamicFlags::FLEXIBLE) => {
778                Ok(DeviceStateWatcherEvent::_UnknownEvent { ordinal: tx_header.ordinal })
779            }
780            _ => Err(fidl::Error::UnknownOrdinal {
781                ordinal: tx_header.ordinal,
782                protocol_name:
783                    <DeviceStateWatcherMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
784            }),
785        }
786    }
787}
788
789/// A Stream of incoming requests for fuchsia.hardware.usb.policy/DeviceStateWatcher.
790pub struct DeviceStateWatcherRequestStream {
791    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
792    is_terminated: bool,
793}
794
795impl std::marker::Unpin for DeviceStateWatcherRequestStream {}
796
797impl futures::stream::FusedStream for DeviceStateWatcherRequestStream {
798    fn is_terminated(&self) -> bool {
799        self.is_terminated
800    }
801}
802
803impl fidl::endpoints::RequestStream for DeviceStateWatcherRequestStream {
804    type Protocol = DeviceStateWatcherMarker;
805    type ControlHandle = DeviceStateWatcherControlHandle;
806
807    fn from_channel(channel: ::fidl::AsyncChannel) -> Self {
808        Self { inner: std::sync::Arc::new(fidl::ServeInner::new(channel)), is_terminated: false }
809    }
810
811    fn control_handle(&self) -> Self::ControlHandle {
812        DeviceStateWatcherControlHandle { inner: self.inner.clone() }
813    }
814
815    fn into_inner(
816        self,
817    ) -> (::std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>, bool)
818    {
819        (self.inner, self.is_terminated)
820    }
821
822    fn from_inner(
823        inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
824        is_terminated: bool,
825    ) -> Self {
826        Self { inner, is_terminated }
827    }
828}
829
830impl futures::Stream for DeviceStateWatcherRequestStream {
831    type Item = Result<DeviceStateWatcherRequest, fidl::Error>;
832
833    fn poll_next(
834        mut self: std::pin::Pin<&mut Self>,
835        cx: &mut std::task::Context<'_>,
836    ) -> std::task::Poll<Option<Self::Item>> {
837        let this = &mut *self;
838        if this.inner.check_shutdown(cx) {
839            this.is_terminated = true;
840            return std::task::Poll::Ready(None);
841        }
842        if this.is_terminated {
843            panic!("polled DeviceStateWatcherRequestStream after completion");
844        }
845        fidl::encoding::with_tls_decode_buf::<_, fidl::encoding::DefaultFuchsiaResourceDialect>(
846            |bytes, handles| {
847                match this.inner.channel().read_etc(cx, bytes, handles) {
848                    std::task::Poll::Ready(Ok(())) => {}
849                    std::task::Poll::Pending => return std::task::Poll::Pending,
850                    std::task::Poll::Ready(Err(zx_status::Status::PEER_CLOSED)) => {
851                        this.is_terminated = true;
852                        return std::task::Poll::Ready(None);
853                    }
854                    std::task::Poll::Ready(Err(e)) => {
855                        return std::task::Poll::Ready(Some(Err(fidl::Error::ServerRequestRead(
856                            e.into(),
857                        ))));
858                    }
859                }
860
861                // A message has been received from the channel
862                let (header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
863
864                std::task::Poll::Ready(Some(match header.ordinal {
865                0x44628a2275753738 => {
866                    header.validate_request_tx_id(fidl::MethodType::TwoWay)?;
867                    let mut req = fidl::new_empty!(fidl::encoding::EmptyPayload, fidl::encoding::DefaultFuchsiaResourceDialect);
868                    fidl::encoding::Decoder::<fidl::encoding::DefaultFuchsiaResourceDialect>::decode_into::<fidl::encoding::EmptyPayload>(&header, _body_bytes, handles, &mut req)?;
869                    let control_handle = DeviceStateWatcherControlHandle {
870                        inner: this.inner.clone(),
871                    };
872                    Ok(DeviceStateWatcherRequest::WatchDeviceState {
873                        responder: DeviceStateWatcherWatchDeviceStateResponder {
874                            control_handle: std::mem::ManuallyDrop::new(control_handle),
875                            tx_id: header.tx_id,
876                        },
877                    })
878                }
879                _ if header.tx_id == 0 && header.dynamic_flags().contains(fidl::encoding::DynamicFlags::FLEXIBLE) => {
880                    Ok(DeviceStateWatcherRequest::_UnknownMethod {
881                        ordinal: header.ordinal,
882                        control_handle: DeviceStateWatcherControlHandle { inner: this.inner.clone() },
883                        method_type: fidl::MethodType::OneWay,
884                    })
885                }
886                _ if header.dynamic_flags().contains(fidl::encoding::DynamicFlags::FLEXIBLE) => {
887                    this.inner.send_framework_err(
888                        fidl::encoding::FrameworkErr::UnknownMethod,
889                        header.tx_id,
890                        header.ordinal,
891                        header.dynamic_flags(),
892                        (bytes, handles),
893                    )?;
894                    Ok(DeviceStateWatcherRequest::_UnknownMethod {
895                        ordinal: header.ordinal,
896                        control_handle: DeviceStateWatcherControlHandle { inner: this.inner.clone() },
897                        method_type: fidl::MethodType::TwoWay,
898                    })
899                }
900                _ => Err(fidl::Error::UnknownOrdinal {
901                    ordinal: header.ordinal,
902                    protocol_name: <DeviceStateWatcherMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
903                }),
904            }))
905            },
906        )
907    }
908}
909
910/// An interface to watch for updates to the USB device state.
911#[derive(Debug)]
912pub enum DeviceStateWatcherRequest {
913    /// Notify a client of an updated device state value via a hanging get.
914    /// The first time this is called, it will return right away with the
915    /// current state. Subsequent calls will hang until there is a change
916    /// to report.
917    /// Returns a table containing the updated device state.
918    WatchDeviceState { responder: DeviceStateWatcherWatchDeviceStateResponder },
919    /// An interaction was received which does not match any known method.
920    #[non_exhaustive]
921    _UnknownMethod {
922        /// Ordinal of the method that was called.
923        ordinal: u64,
924        control_handle: DeviceStateWatcherControlHandle,
925        method_type: fidl::MethodType,
926    },
927}
928
929impl DeviceStateWatcherRequest {
930    #[allow(irrefutable_let_patterns)]
931    pub fn into_watch_device_state(self) -> Option<(DeviceStateWatcherWatchDeviceStateResponder)> {
932        if let DeviceStateWatcherRequest::WatchDeviceState { responder } = self {
933            Some((responder))
934        } else {
935            None
936        }
937    }
938
939    /// Name of the method defined in FIDL
940    pub fn method_name(&self) -> &'static str {
941        match *self {
942            DeviceStateWatcherRequest::WatchDeviceState { .. } => "watch_device_state",
943            DeviceStateWatcherRequest::_UnknownMethod {
944                method_type: fidl::MethodType::OneWay,
945                ..
946            } => "unknown one-way method",
947            DeviceStateWatcherRequest::_UnknownMethod {
948                method_type: fidl::MethodType::TwoWay,
949                ..
950            } => "unknown two-way method",
951        }
952    }
953}
954
955#[derive(Debug, Clone)]
956pub struct DeviceStateWatcherControlHandle {
957    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
958}
959
960impl fidl::endpoints::ControlHandle for DeviceStateWatcherControlHandle {
961    fn shutdown(&self) {
962        self.inner.shutdown()
963    }
964
965    fn shutdown_with_epitaph(&self, status: zx_status::Status) {
966        self.inner.shutdown_with_epitaph(status)
967    }
968
969    fn is_closed(&self) -> bool {
970        self.inner.channel().is_closed()
971    }
972    fn on_closed(&self) -> fidl::OnSignalsRef<'_> {
973        self.inner.channel().on_closed()
974    }
975
976    #[cfg(target_os = "fuchsia")]
977    fn signal_peer(
978        &self,
979        clear_mask: zx::Signals,
980        set_mask: zx::Signals,
981    ) -> Result<(), zx_status::Status> {
982        use fidl::Peered;
983        self.inner.channel().signal_peer(clear_mask, set_mask)
984    }
985}
986
987impl DeviceStateWatcherControlHandle {}
988
989#[must_use = "FIDL methods require a response to be sent"]
990#[derive(Debug)]
991pub struct DeviceStateWatcherWatchDeviceStateResponder {
992    control_handle: std::mem::ManuallyDrop<DeviceStateWatcherControlHandle>,
993    tx_id: u32,
994}
995
996/// Set the the channel to be shutdown (see [`DeviceStateWatcherControlHandle::shutdown`])
997/// if the responder is dropped without sending a response, so that the client
998/// doesn't hang. To prevent this behavior, call `drop_without_shutdown`.
999impl std::ops::Drop for DeviceStateWatcherWatchDeviceStateResponder {
1000    fn drop(&mut self) {
1001        self.control_handle.shutdown();
1002        // Safety: drops once, never accessed again
1003        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
1004    }
1005}
1006
1007impl fidl::endpoints::Responder for DeviceStateWatcherWatchDeviceStateResponder {
1008    type ControlHandle = DeviceStateWatcherControlHandle;
1009
1010    fn control_handle(&self) -> &DeviceStateWatcherControlHandle {
1011        &self.control_handle
1012    }
1013
1014    fn drop_without_shutdown(mut self) {
1015        // Safety: drops once, never accessed again due to mem::forget
1016        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
1017        // Prevent Drop from running (which would shut down the channel)
1018        std::mem::forget(self);
1019    }
1020}
1021
1022impl DeviceStateWatcherWatchDeviceStateResponder {
1023    /// Sends a response to the FIDL transaction.
1024    ///
1025    /// Sets the channel to shutdown if an error occurs.
1026    pub fn send(self, mut result: Result<&DeviceStateUpdate, i32>) -> Result<(), fidl::Error> {
1027        let _result = self.send_raw(result);
1028        if _result.is_err() {
1029            self.control_handle.shutdown();
1030        }
1031        self.drop_without_shutdown();
1032        _result
1033    }
1034
1035    /// Similar to "send" but does not shutdown the channel if an error occurs.
1036    pub fn send_no_shutdown_on_err(
1037        self,
1038        mut result: Result<&DeviceStateUpdate, i32>,
1039    ) -> Result<(), fidl::Error> {
1040        let _result = self.send_raw(result);
1041        self.drop_without_shutdown();
1042        _result
1043    }
1044
1045    fn send_raw(&self, mut result: Result<&DeviceStateUpdate, i32>) -> Result<(), fidl::Error> {
1046        self.control_handle
1047            .inner
1048            .send::<fidl::encoding::FlexibleResultType<DeviceStateUpdate, i32>>(
1049                fidl::encoding::FlexibleResult::new(result),
1050                self.tx_id,
1051                0x44628a2275753738,
1052                fidl::encoding::DynamicFlags::FLEXIBLE,
1053            )
1054    }
1055}
1056
1057#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
1058pub struct ServiceMarker;
1059
1060#[cfg(target_os = "fuchsia")]
1061impl fidl::endpoints::ServiceMarker for ServiceMarker {
1062    type Proxy = ServiceProxy;
1063    type Request = ServiceRequest;
1064    const SERVICE_NAME: &'static str = "fuchsia.hardware.usb.policy.Service";
1065}
1066
1067/// A request for one of the member protocols of Service.
1068///
1069/// A service definition for hardware USB policy, exposing the controller.
1070#[cfg(target_os = "fuchsia")]
1071pub enum ServiceRequest {
1072    /// A client end to connect to the Controller protocol.
1073    Controller(ControllerRequestStream),
1074}
1075
1076#[cfg(target_os = "fuchsia")]
1077impl fidl::endpoints::ServiceRequest for ServiceRequest {
1078    type Service = ServiceMarker;
1079
1080    fn dispatch(name: &str, _channel: fidl::AsyncChannel) -> Self {
1081        match name {
1082            "controller" => Self::Controller(
1083                <ControllerRequestStream as fidl::endpoints::RequestStream>::from_channel(_channel),
1084            ),
1085            _ => panic!("no such member protocol name for service Service"),
1086        }
1087    }
1088
1089    fn member_names() -> &'static [&'static str] {
1090        &["controller"]
1091    }
1092}
1093/// A service definition for hardware USB policy, exposing the controller.
1094#[cfg(target_os = "fuchsia")]
1095pub struct ServiceProxy(#[allow(dead_code)] Box<dyn fidl::endpoints::MemberOpener>);
1096
1097#[cfg(target_os = "fuchsia")]
1098impl fidl::endpoints::ServiceProxy for ServiceProxy {
1099    type Service = ServiceMarker;
1100
1101    fn from_member_opener(opener: Box<dyn fidl::endpoints::MemberOpener>) -> Self {
1102        Self(opener)
1103    }
1104}
1105
1106#[cfg(target_os = "fuchsia")]
1107impl ServiceProxy {
1108    /// A client end to connect to the Controller protocol.
1109    pub fn connect_to_controller(&self) -> Result<ControllerProxy, fidl::Error> {
1110        let (proxy, server_end) = fidl::endpoints::create_proxy::<ControllerMarker>();
1111        self.connect_channel_to_controller(server_end)?;
1112        Ok(proxy)
1113    }
1114
1115    /// Like `connect_to_controller`, but returns a sync proxy.
1116    /// See [`Self::connect_to_controller`] for more details.
1117    pub fn connect_to_controller_sync(&self) -> Result<ControllerSynchronousProxy, fidl::Error> {
1118        let (proxy, server_end) = fidl::endpoints::create_sync_proxy::<ControllerMarker>();
1119        self.connect_channel_to_controller(server_end)?;
1120        Ok(proxy)
1121    }
1122
1123    /// Like `connect_to_controller`, but accepts a server end.
1124    /// See [`Self::connect_to_controller`] for more details.
1125    pub fn connect_channel_to_controller(
1126        &self,
1127        server_end: fidl::endpoints::ServerEnd<ControllerMarker>,
1128    ) -> Result<(), fidl::Error> {
1129        self.0.open_member("controller", server_end.into_channel())
1130    }
1131
1132    pub fn instance_name(&self) -> &str {
1133        self.0.instance_name()
1134    }
1135}
1136
1137mod internal {
1138    use super::*;
1139}