Skip to main content

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