Skip to main content

fidl_fuchsia_hardware_usb_peripheral/
fidl_fuchsia_hardware_usb_peripheral.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_peripheral_common::*;
11use futures::future::{self, MaybeDone, TryFutureExt};
12use zx_status;
13
14#[derive(Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
15pub struct DeviceSetStateChangeListenerRequest {
16    pub listener: fidl::endpoints::ClientEnd<EventsMarker>,
17}
18
19impl fidl::Standalone<fidl::encoding::DefaultFuchsiaResourceDialect>
20    for DeviceSetStateChangeListenerRequest
21{
22}
23
24#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
25pub struct DeviceMarker;
26
27impl fidl::endpoints::ProtocolMarker for DeviceMarker {
28    type Proxy = DeviceProxy;
29    type RequestStream = DeviceRequestStream;
30    #[cfg(target_os = "fuchsia")]
31    type SynchronousProxy = DeviceSynchronousProxy;
32
33    const DEBUG_NAME: &'static str = "(anonymous) Device";
34}
35pub type DeviceGetConfigurationResult =
36    Result<(DeviceDescriptor, Vec<Vec<FunctionDescriptor>>), i32>;
37pub type DeviceSetConfigurationResult = Result<(), i32>;
38
39pub trait DeviceProxyInterface: Send + Sync {
40    type GetConfigurationResponseFut: std::future::Future<Output = Result<DeviceGetConfigurationResult, fidl::Error>>
41        + Send;
42    fn r#get_configuration(&self) -> Self::GetConfigurationResponseFut;
43    type SetConfigurationResponseFut: std::future::Future<Output = Result<DeviceSetConfigurationResult, fidl::Error>>
44        + Send;
45    fn r#set_configuration(
46        &self,
47        device_desc: &DeviceDescriptor,
48        config_descriptors: &[Vec<FunctionDescriptor>],
49    ) -> Self::SetConfigurationResponseFut;
50    type ClearFunctionsResponseFut: std::future::Future<Output = Result<(), fidl::Error>> + Send;
51    fn r#clear_functions(&self) -> Self::ClearFunctionsResponseFut;
52    fn r#set_state_change_listener(
53        &self,
54        listener: fidl::endpoints::ClientEnd<EventsMarker>,
55    ) -> Result<(), fidl::Error>;
56}
57#[derive(Debug)]
58#[cfg(target_os = "fuchsia")]
59pub struct DeviceSynchronousProxy {
60    client: fidl::client::sync::Client,
61}
62
63#[cfg(target_os = "fuchsia")]
64impl fidl::endpoints::SynchronousProxy for DeviceSynchronousProxy {
65    type Proxy = DeviceProxy;
66    type Protocol = DeviceMarker;
67
68    fn from_channel(inner: fidl::Channel) -> Self {
69        Self::new(inner)
70    }
71
72    fn into_channel(self) -> fidl::Channel {
73        self.client.into_channel()
74    }
75
76    fn as_channel(&self) -> &fidl::Channel {
77        self.client.as_channel()
78    }
79}
80
81#[cfg(target_os = "fuchsia")]
82impl DeviceSynchronousProxy {
83    pub fn new(channel: fidl::Channel) -> Self {
84        Self { client: fidl::client::sync::Client::new(channel) }
85    }
86
87    pub fn into_channel(self) -> fidl::Channel {
88        self.client.into_channel()
89    }
90
91    /// Waits until an event arrives and returns it. It is safe for other
92    /// threads to make concurrent requests while waiting for an event.
93    pub fn wait_for_event(
94        &self,
95        deadline: zx::MonotonicInstant,
96    ) -> Result<DeviceEvent, fidl::Error> {
97        DeviceEvent::decode(self.client.wait_for_event::<DeviceMarker>(deadline)?)
98    }
99
100    /// Retrieves the current device descriptor and active configuration descriptors.
101    ///
102    /// Returns the active USB device descriptor and all associated configuration
103    /// descriptors registered with the peripheral device manager.
104    ///
105    /// * error:
106    ///   * `ZX_ERR_BAD_STATE`: The peripheral device has not been configured.
107    pub fn r#get_configuration(
108        &self,
109        ___deadline: zx::MonotonicInstant,
110    ) -> Result<DeviceGetConfigurationResult, fidl::Error> {
111        let _response = self.client.send_query::<
112            fidl::encoding::EmptyPayload,
113            fidl::encoding::FlexibleResultType<DeviceGetConfigurationResponse, i32>,
114            DeviceMarker,
115        >(
116            (),
117            0x19fe4f37c3b52e3a,
118            fidl::encoding::DynamicFlags::FLEXIBLE,
119            ___deadline,
120        )?
121        .into_result::<DeviceMarker>("get_configuration")?;
122        Ok(_response.map(|x| (x.device_desc, x.config_descriptors)))
123    }
124
125    /// Sets the device's descriptors, adds the functions and creates the child devices for the
126    /// configuration's interfaces.
127    /// At least one function descriptor must be provided.
128    pub fn r#set_configuration(
129        &self,
130        mut device_desc: &DeviceDescriptor,
131        mut config_descriptors: &[Vec<FunctionDescriptor>],
132        ___deadline: zx::MonotonicInstant,
133    ) -> Result<DeviceSetConfigurationResult, fidl::Error> {
134        let _response = self.client.send_query::<
135            DeviceSetConfigurationRequest,
136            fidl::encoding::FlexibleResultType<fidl::encoding::EmptyStruct, i32>,
137            DeviceMarker,
138        >(
139            (device_desc, config_descriptors,),
140            0x464bafee91a3d6de,
141            fidl::encoding::DynamicFlags::FLEXIBLE,
142            ___deadline,
143        )?
144        .into_result::<DeviceMarker>("set_configuration")?;
145        Ok(_response.map(|x| x))
146    }
147
148    /// Tells the device to remove the child devices for the configuration's interfaces
149    /// and reset the list of functions to empty.
150    /// The caller should wait for the `FunctionsCleared` event.
151    pub fn r#clear_functions(&self, ___deadline: zx::MonotonicInstant) -> Result<(), fidl::Error> {
152        let _response = self.client.send_query::<
153            fidl::encoding::EmptyPayload,
154            fidl::encoding::FlexibleType<fidl::encoding::EmptyStruct>,
155            DeviceMarker,
156        >(
157            (),
158            0x67d9d8086dfab0cb,
159            fidl::encoding::DynamicFlags::FLEXIBLE,
160            ___deadline,
161        )?
162        .into_result::<DeviceMarker>("clear_functions")?;
163        Ok(_response)
164    }
165
166    /// Adds a state change listener that is invoked when a state change completes.
167    pub fn r#set_state_change_listener(
168        &self,
169        mut listener: fidl::endpoints::ClientEnd<EventsMarker>,
170    ) -> Result<(), fidl::Error> {
171        self.client.send::<DeviceSetStateChangeListenerRequest>(
172            (listener,),
173            0x5575723c4674d1d9,
174            fidl::encoding::DynamicFlags::FLEXIBLE,
175        )
176    }
177}
178
179#[cfg(target_os = "fuchsia")]
180impl From<DeviceSynchronousProxy> for zx::NullableHandle {
181    fn from(value: DeviceSynchronousProxy) -> Self {
182        value.into_channel().into()
183    }
184}
185
186#[cfg(target_os = "fuchsia")]
187impl From<fidl::Channel> for DeviceSynchronousProxy {
188    fn from(value: fidl::Channel) -> Self {
189        Self::new(value)
190    }
191}
192
193#[cfg(target_os = "fuchsia")]
194impl fidl::endpoints::FromClient for DeviceSynchronousProxy {
195    type Protocol = DeviceMarker;
196
197    fn from_client(value: fidl::endpoints::ClientEnd<DeviceMarker>) -> Self {
198        Self::new(value.into_channel())
199    }
200}
201
202#[derive(Debug, Clone)]
203pub struct DeviceProxy {
204    client: fidl::client::Client<fidl::encoding::DefaultFuchsiaResourceDialect>,
205}
206
207impl fidl::endpoints::Proxy for DeviceProxy {
208    type Protocol = DeviceMarker;
209
210    fn from_channel(inner: ::fidl::AsyncChannel) -> Self {
211        Self::new(inner)
212    }
213
214    fn into_channel(self) -> Result<::fidl::AsyncChannel, Self> {
215        self.client.into_channel().map_err(|client| Self { client })
216    }
217
218    fn as_channel(&self) -> &::fidl::AsyncChannel {
219        self.client.as_channel()
220    }
221}
222
223impl DeviceProxy {
224    /// Create a new Proxy for fuchsia.hardware.usb.peripheral/Device.
225    pub fn new(channel: ::fidl::AsyncChannel) -> Self {
226        let protocol_name = <DeviceMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME;
227        Self { client: fidl::client::Client::new(channel, protocol_name) }
228    }
229
230    /// Get a Stream of events from the remote end of the protocol.
231    ///
232    /// # Panics
233    ///
234    /// Panics if the event stream was already taken.
235    pub fn take_event_stream(&self) -> DeviceEventStream {
236        DeviceEventStream { event_receiver: self.client.take_event_receiver() }
237    }
238
239    /// Retrieves the current device descriptor and active configuration descriptors.
240    ///
241    /// Returns the active USB device descriptor and all associated configuration
242    /// descriptors registered with the peripheral device manager.
243    ///
244    /// * error:
245    ///   * `ZX_ERR_BAD_STATE`: The peripheral device has not been configured.
246    pub fn r#get_configuration(
247        &self,
248    ) -> fidl::client::QueryResponseFut<
249        DeviceGetConfigurationResult,
250        fidl::encoding::DefaultFuchsiaResourceDialect,
251    > {
252        DeviceProxyInterface::r#get_configuration(self)
253    }
254
255    /// Sets the device's descriptors, adds the functions and creates the child devices for the
256    /// configuration's interfaces.
257    /// At least one function descriptor must be provided.
258    pub fn r#set_configuration(
259        &self,
260        mut device_desc: &DeviceDescriptor,
261        mut config_descriptors: &[Vec<FunctionDescriptor>],
262    ) -> fidl::client::QueryResponseFut<
263        DeviceSetConfigurationResult,
264        fidl::encoding::DefaultFuchsiaResourceDialect,
265    > {
266        DeviceProxyInterface::r#set_configuration(self, device_desc, config_descriptors)
267    }
268
269    /// Tells the device to remove the child devices for the configuration's interfaces
270    /// and reset the list of functions to empty.
271    /// The caller should wait for the `FunctionsCleared` event.
272    pub fn r#clear_functions(
273        &self,
274    ) -> fidl::client::QueryResponseFut<(), fidl::encoding::DefaultFuchsiaResourceDialect> {
275        DeviceProxyInterface::r#clear_functions(self)
276    }
277
278    /// Adds a state change listener that is invoked when a state change completes.
279    pub fn r#set_state_change_listener(
280        &self,
281        mut listener: fidl::endpoints::ClientEnd<EventsMarker>,
282    ) -> Result<(), fidl::Error> {
283        DeviceProxyInterface::r#set_state_change_listener(self, listener)
284    }
285}
286
287impl DeviceProxyInterface for DeviceProxy {
288    type GetConfigurationResponseFut = fidl::client::QueryResponseFut<
289        DeviceGetConfigurationResult,
290        fidl::encoding::DefaultFuchsiaResourceDialect,
291    >;
292    fn r#get_configuration(&self) -> Self::GetConfigurationResponseFut {
293        fn _decode(
294            mut _buf: Result<<fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc, fidl::Error>,
295        ) -> Result<DeviceGetConfigurationResult, fidl::Error> {
296            let _response = fidl::client::decode_transaction_body::<
297                fidl::encoding::FlexibleResultType<DeviceGetConfigurationResponse, i32>,
298                fidl::encoding::DefaultFuchsiaResourceDialect,
299                0x19fe4f37c3b52e3a,
300            >(_buf?)?
301            .into_result::<DeviceMarker>("get_configuration")?;
302            Ok(_response.map(|x| (x.device_desc, x.config_descriptors)))
303        }
304        self.client
305            .send_query_and_decode::<fidl::encoding::EmptyPayload, DeviceGetConfigurationResult>(
306                (),
307                0x19fe4f37c3b52e3a,
308                fidl::encoding::DynamicFlags::FLEXIBLE,
309                _decode,
310            )
311    }
312
313    type SetConfigurationResponseFut = fidl::client::QueryResponseFut<
314        DeviceSetConfigurationResult,
315        fidl::encoding::DefaultFuchsiaResourceDialect,
316    >;
317    fn r#set_configuration(
318        &self,
319        mut device_desc: &DeviceDescriptor,
320        mut config_descriptors: &[Vec<FunctionDescriptor>],
321    ) -> Self::SetConfigurationResponseFut {
322        fn _decode(
323            mut _buf: Result<<fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc, fidl::Error>,
324        ) -> Result<DeviceSetConfigurationResult, fidl::Error> {
325            let _response = fidl::client::decode_transaction_body::<
326                fidl::encoding::FlexibleResultType<fidl::encoding::EmptyStruct, i32>,
327                fidl::encoding::DefaultFuchsiaResourceDialect,
328                0x464bafee91a3d6de,
329            >(_buf?)?
330            .into_result::<DeviceMarker>("set_configuration")?;
331            Ok(_response.map(|x| x))
332        }
333        self.client
334            .send_query_and_decode::<DeviceSetConfigurationRequest, DeviceSetConfigurationResult>(
335                (device_desc, config_descriptors),
336                0x464bafee91a3d6de,
337                fidl::encoding::DynamicFlags::FLEXIBLE,
338                _decode,
339            )
340    }
341
342    type ClearFunctionsResponseFut =
343        fidl::client::QueryResponseFut<(), fidl::encoding::DefaultFuchsiaResourceDialect>;
344    fn r#clear_functions(&self) -> Self::ClearFunctionsResponseFut {
345        fn _decode(
346            mut _buf: Result<<fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc, fidl::Error>,
347        ) -> Result<(), fidl::Error> {
348            let _response = fidl::client::decode_transaction_body::<
349                fidl::encoding::FlexibleType<fidl::encoding::EmptyStruct>,
350                fidl::encoding::DefaultFuchsiaResourceDialect,
351                0x67d9d8086dfab0cb,
352            >(_buf?)?
353            .into_result::<DeviceMarker>("clear_functions")?;
354            Ok(_response)
355        }
356        self.client.send_query_and_decode::<fidl::encoding::EmptyPayload, ()>(
357            (),
358            0x67d9d8086dfab0cb,
359            fidl::encoding::DynamicFlags::FLEXIBLE,
360            _decode,
361        )
362    }
363
364    fn r#set_state_change_listener(
365        &self,
366        mut listener: fidl::endpoints::ClientEnd<EventsMarker>,
367    ) -> Result<(), fidl::Error> {
368        self.client.send::<DeviceSetStateChangeListenerRequest>(
369            (listener,),
370            0x5575723c4674d1d9,
371            fidl::encoding::DynamicFlags::FLEXIBLE,
372        )
373    }
374}
375
376pub struct DeviceEventStream {
377    event_receiver: fidl::client::EventReceiver<fidl::encoding::DefaultFuchsiaResourceDialect>,
378}
379
380impl std::marker::Unpin for DeviceEventStream {}
381
382impl futures::stream::FusedStream for DeviceEventStream {
383    fn is_terminated(&self) -> bool {
384        self.event_receiver.is_terminated()
385    }
386}
387
388impl futures::Stream for DeviceEventStream {
389    type Item = Result<DeviceEvent, fidl::Error>;
390
391    fn poll_next(
392        mut self: std::pin::Pin<&mut Self>,
393        cx: &mut std::task::Context<'_>,
394    ) -> std::task::Poll<Option<Self::Item>> {
395        match futures::ready!(futures::stream::StreamExt::poll_next_unpin(
396            &mut self.event_receiver,
397            cx
398        )?) {
399            Some(buf) => std::task::Poll::Ready(Some(DeviceEvent::decode(buf))),
400            None => std::task::Poll::Ready(None),
401        }
402    }
403}
404
405#[derive(Debug)]
406pub enum DeviceEvent {
407    #[non_exhaustive]
408    _UnknownEvent {
409        /// Ordinal of the event that was sent.
410        ordinal: u64,
411    },
412}
413
414impl DeviceEvent {
415    /// Decodes a message buffer as a [`DeviceEvent`].
416    fn decode(
417        mut buf: <fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc,
418    ) -> Result<DeviceEvent, fidl::Error> {
419        let (bytes, _handles) = buf.split_mut();
420        let (tx_header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
421        debug_assert_eq!(tx_header.tx_id, 0);
422        match tx_header.ordinal {
423            _ if tx_header.dynamic_flags().contains(fidl::encoding::DynamicFlags::FLEXIBLE) => {
424                Ok(DeviceEvent::_UnknownEvent { ordinal: tx_header.ordinal })
425            }
426            _ => Err(fidl::Error::UnknownOrdinal {
427                ordinal: tx_header.ordinal,
428                protocol_name: <DeviceMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
429            }),
430        }
431    }
432}
433
434/// A Stream of incoming requests for fuchsia.hardware.usb.peripheral/Device.
435pub struct DeviceRequestStream {
436    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
437    is_terminated: bool,
438}
439
440impl std::marker::Unpin for DeviceRequestStream {}
441
442impl futures::stream::FusedStream for DeviceRequestStream {
443    fn is_terminated(&self) -> bool {
444        self.is_terminated
445    }
446}
447
448impl fidl::endpoints::RequestStream for DeviceRequestStream {
449    type Protocol = DeviceMarker;
450    type ControlHandle = DeviceControlHandle;
451
452    fn from_channel(channel: ::fidl::AsyncChannel) -> Self {
453        Self { inner: std::sync::Arc::new(fidl::ServeInner::new(channel)), is_terminated: false }
454    }
455
456    fn control_handle(&self) -> Self::ControlHandle {
457        DeviceControlHandle { inner: self.inner.clone() }
458    }
459
460    fn into_inner(
461        self,
462    ) -> (::std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>, bool)
463    {
464        (self.inner, self.is_terminated)
465    }
466
467    fn from_inner(
468        inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
469        is_terminated: bool,
470    ) -> Self {
471        Self { inner, is_terminated }
472    }
473}
474
475impl futures::Stream for DeviceRequestStream {
476    type Item = Result<DeviceRequest, fidl::Error>;
477
478    fn poll_next(
479        mut self: std::pin::Pin<&mut Self>,
480        cx: &mut std::task::Context<'_>,
481    ) -> std::task::Poll<Option<Self::Item>> {
482        let this = &mut *self;
483        if this.inner.check_shutdown(cx) {
484            this.is_terminated = true;
485            return std::task::Poll::Ready(None);
486        }
487        if this.is_terminated {
488            panic!("polled DeviceRequestStream after completion");
489        }
490        fidl::encoding::with_tls_decode_buf::<_, fidl::encoding::DefaultFuchsiaResourceDialect>(
491            |bytes, handles| {
492                match this.inner.channel().read_etc(cx, bytes, handles) {
493                    std::task::Poll::Ready(Ok(())) => {}
494                    std::task::Poll::Pending => return std::task::Poll::Pending,
495                    std::task::Poll::Ready(Err(zx_status::Status::PEER_CLOSED)) => {
496                        this.is_terminated = true;
497                        return std::task::Poll::Ready(None);
498                    }
499                    std::task::Poll::Ready(Err(e)) => {
500                        return std::task::Poll::Ready(Some(Err(fidl::Error::ServerRequestRead(
501                            e.into(),
502                        ))));
503                    }
504                }
505
506                // A message has been received from the channel
507                let (header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
508
509                std::task::Poll::Ready(Some(match header.ordinal {
510                    0x19fe4f37c3b52e3a => {
511                        header.validate_request_tx_id(fidl::MethodType::TwoWay)?;
512                        let mut req = fidl::new_empty!(
513                            fidl::encoding::EmptyPayload,
514                            fidl::encoding::DefaultFuchsiaResourceDialect
515                        );
516                        fidl::encoding::Decoder::<fidl::encoding::DefaultFuchsiaResourceDialect>::decode_into::<fidl::encoding::EmptyPayload>(&header, _body_bytes, handles, &mut req)?;
517                        let control_handle = DeviceControlHandle { inner: this.inner.clone() };
518                        Ok(DeviceRequest::GetConfiguration {
519                            responder: DeviceGetConfigurationResponder {
520                                control_handle: std::mem::ManuallyDrop::new(control_handle),
521                                tx_id: header.tx_id,
522                            },
523                        })
524                    }
525                    0x464bafee91a3d6de => {
526                        header.validate_request_tx_id(fidl::MethodType::TwoWay)?;
527                        let mut req = fidl::new_empty!(
528                            DeviceSetConfigurationRequest,
529                            fidl::encoding::DefaultFuchsiaResourceDialect
530                        );
531                        fidl::encoding::Decoder::<fidl::encoding::DefaultFuchsiaResourceDialect>::decode_into::<DeviceSetConfigurationRequest>(&header, _body_bytes, handles, &mut req)?;
532                        let control_handle = DeviceControlHandle { inner: this.inner.clone() };
533                        Ok(DeviceRequest::SetConfiguration {
534                            device_desc: req.device_desc,
535                            config_descriptors: req.config_descriptors,
536
537                            responder: DeviceSetConfigurationResponder {
538                                control_handle: std::mem::ManuallyDrop::new(control_handle),
539                                tx_id: header.tx_id,
540                            },
541                        })
542                    }
543                    0x67d9d8086dfab0cb => {
544                        header.validate_request_tx_id(fidl::MethodType::TwoWay)?;
545                        let mut req = fidl::new_empty!(
546                            fidl::encoding::EmptyPayload,
547                            fidl::encoding::DefaultFuchsiaResourceDialect
548                        );
549                        fidl::encoding::Decoder::<fidl::encoding::DefaultFuchsiaResourceDialect>::decode_into::<fidl::encoding::EmptyPayload>(&header, _body_bytes, handles, &mut req)?;
550                        let control_handle = DeviceControlHandle { inner: this.inner.clone() };
551                        Ok(DeviceRequest::ClearFunctions {
552                            responder: DeviceClearFunctionsResponder {
553                                control_handle: std::mem::ManuallyDrop::new(control_handle),
554                                tx_id: header.tx_id,
555                            },
556                        })
557                    }
558                    0x5575723c4674d1d9 => {
559                        header.validate_request_tx_id(fidl::MethodType::OneWay)?;
560                        let mut req = fidl::new_empty!(
561                            DeviceSetStateChangeListenerRequest,
562                            fidl::encoding::DefaultFuchsiaResourceDialect
563                        );
564                        fidl::encoding::Decoder::<fidl::encoding::DefaultFuchsiaResourceDialect>::decode_into::<DeviceSetStateChangeListenerRequest>(&header, _body_bytes, handles, &mut req)?;
565                        let control_handle = DeviceControlHandle { inner: this.inner.clone() };
566                        Ok(DeviceRequest::SetStateChangeListener {
567                            listener: req.listener,
568
569                            control_handle,
570                        })
571                    }
572                    _ if header.tx_id == 0
573                        && header
574                            .dynamic_flags()
575                            .contains(fidl::encoding::DynamicFlags::FLEXIBLE) =>
576                    {
577                        Ok(DeviceRequest::_UnknownMethod {
578                            ordinal: header.ordinal,
579                            control_handle: DeviceControlHandle { inner: this.inner.clone() },
580                            method_type: fidl::MethodType::OneWay,
581                        })
582                    }
583                    _ if header
584                        .dynamic_flags()
585                        .contains(fidl::encoding::DynamicFlags::FLEXIBLE) =>
586                    {
587                        this.inner.send_framework_err(
588                            fidl::encoding::FrameworkErr::UnknownMethod,
589                            header.tx_id,
590                            header.ordinal,
591                            header.dynamic_flags(),
592                            (bytes, handles),
593                        )?;
594                        Ok(DeviceRequest::_UnknownMethod {
595                            ordinal: header.ordinal,
596                            control_handle: DeviceControlHandle { inner: this.inner.clone() },
597                            method_type: fidl::MethodType::TwoWay,
598                        })
599                    }
600                    _ => Err(fidl::Error::UnknownOrdinal {
601                        ordinal: header.ordinal,
602                        protocol_name:
603                            <DeviceMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
604                    }),
605                }))
606            },
607        )
608    }
609}
610
611#[derive(Debug)]
612pub enum DeviceRequest {
613    /// Retrieves the current device descriptor and active configuration descriptors.
614    ///
615    /// Returns the active USB device descriptor and all associated configuration
616    /// descriptors registered with the peripheral device manager.
617    ///
618    /// * error:
619    ///   * `ZX_ERR_BAD_STATE`: The peripheral device has not been configured.
620    GetConfiguration { responder: DeviceGetConfigurationResponder },
621    /// Sets the device's descriptors, adds the functions and creates the child devices for the
622    /// configuration's interfaces.
623    /// At least one function descriptor must be provided.
624    SetConfiguration {
625        device_desc: DeviceDescriptor,
626        config_descriptors: Vec<Vec<FunctionDescriptor>>,
627        responder: DeviceSetConfigurationResponder,
628    },
629    /// Tells the device to remove the child devices for the configuration's interfaces
630    /// and reset the list of functions to empty.
631    /// The caller should wait for the `FunctionsCleared` event.
632    ClearFunctions { responder: DeviceClearFunctionsResponder },
633    /// Adds a state change listener that is invoked when a state change completes.
634    SetStateChangeListener {
635        listener: fidl::endpoints::ClientEnd<EventsMarker>,
636        control_handle: DeviceControlHandle,
637    },
638    /// An interaction was received which does not match any known method.
639    #[non_exhaustive]
640    _UnknownMethod {
641        /// Ordinal of the method that was called.
642        ordinal: u64,
643        control_handle: DeviceControlHandle,
644        method_type: fidl::MethodType,
645    },
646}
647
648impl DeviceRequest {
649    #[allow(irrefutable_let_patterns)]
650    pub fn into_get_configuration(self) -> Option<(DeviceGetConfigurationResponder)> {
651        if let DeviceRequest::GetConfiguration { responder } = self {
652            Some((responder))
653        } else {
654            None
655        }
656    }
657
658    #[allow(irrefutable_let_patterns)]
659    pub fn into_set_configuration(
660        self,
661    ) -> Option<(DeviceDescriptor, Vec<Vec<FunctionDescriptor>>, DeviceSetConfigurationResponder)>
662    {
663        if let DeviceRequest::SetConfiguration { device_desc, config_descriptors, responder } = self
664        {
665            Some((device_desc, config_descriptors, responder))
666        } else {
667            None
668        }
669    }
670
671    #[allow(irrefutable_let_patterns)]
672    pub fn into_clear_functions(self) -> Option<(DeviceClearFunctionsResponder)> {
673        if let DeviceRequest::ClearFunctions { responder } = self {
674            Some((responder))
675        } else {
676            None
677        }
678    }
679
680    #[allow(irrefutable_let_patterns)]
681    pub fn into_set_state_change_listener(
682        self,
683    ) -> Option<(fidl::endpoints::ClientEnd<EventsMarker>, DeviceControlHandle)> {
684        if let DeviceRequest::SetStateChangeListener { listener, control_handle } = self {
685            Some((listener, control_handle))
686        } else {
687            None
688        }
689    }
690
691    /// Name of the method defined in FIDL
692    pub fn method_name(&self) -> &'static str {
693        match *self {
694            DeviceRequest::GetConfiguration { .. } => "get_configuration",
695            DeviceRequest::SetConfiguration { .. } => "set_configuration",
696            DeviceRequest::ClearFunctions { .. } => "clear_functions",
697            DeviceRequest::SetStateChangeListener { .. } => "set_state_change_listener",
698            DeviceRequest::_UnknownMethod { method_type: fidl::MethodType::OneWay, .. } => {
699                "unknown one-way method"
700            }
701            DeviceRequest::_UnknownMethod { method_type: fidl::MethodType::TwoWay, .. } => {
702                "unknown two-way method"
703            }
704        }
705    }
706}
707
708#[derive(Debug, Clone)]
709pub struct DeviceControlHandle {
710    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
711}
712
713impl DeviceControlHandle {
714    pub fn shutdown_with_epitaph(&self, status: impl Into<fidl::Epitaph>) {
715        self.inner.shutdown_with_epitaph(status.into())
716    }
717}
718
719impl fidl::endpoints::ControlHandle for DeviceControlHandle {
720    fn shutdown(&self) {
721        self.inner.shutdown()
722    }
723
724    fn shutdown_with_epitaph(&self, status: fidl::Epitaph) {
725        self.inner.shutdown_with_epitaph(status)
726    }
727
728    fn is_closed(&self) -> bool {
729        self.inner.channel().is_closed()
730    }
731    fn on_closed(&self) -> fidl::OnSignalsRef<'_> {
732        self.inner.channel().on_closed()
733    }
734
735    #[cfg(target_os = "fuchsia")]
736    fn signal_peer(
737        &self,
738        clear_mask: zx::Signals,
739        set_mask: zx::Signals,
740    ) -> Result<(), zx_status::Status> {
741        use fidl::Peered;
742        self.inner.channel().signal_peer(clear_mask, set_mask)
743    }
744}
745
746impl DeviceControlHandle {}
747
748#[must_use = "FIDL methods require a response to be sent"]
749#[derive(Debug)]
750pub struct DeviceGetConfigurationResponder {
751    control_handle: std::mem::ManuallyDrop<DeviceControlHandle>,
752    tx_id: u32,
753}
754
755/// Set the the channel to be shutdown (see [`DeviceControlHandle::shutdown`])
756/// if the responder is dropped without sending a response, so that the client
757/// doesn't hang. To prevent this behavior, call `drop_without_shutdown`.
758impl std::ops::Drop for DeviceGetConfigurationResponder {
759    fn drop(&mut self) {
760        self.control_handle.shutdown();
761        // Safety: drops once, never accessed again
762        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
763    }
764}
765
766impl fidl::endpoints::Responder for DeviceGetConfigurationResponder {
767    type ControlHandle = DeviceControlHandle;
768
769    fn control_handle(&self) -> &DeviceControlHandle {
770        &self.control_handle
771    }
772
773    fn drop_without_shutdown(mut self) {
774        // Safety: drops once, never accessed again due to mem::forget
775        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
776        // Prevent Drop from running (which would shut down the channel)
777        std::mem::forget(self);
778    }
779}
780
781impl DeviceGetConfigurationResponder {
782    /// Sends a response to the FIDL transaction.
783    ///
784    /// Sets the channel to shutdown if an error occurs.
785    pub fn send(
786        self,
787        mut result: Result<(&DeviceDescriptor, &[Vec<FunctionDescriptor>]), i32>,
788    ) -> Result<(), fidl::Error> {
789        let _result = self.send_raw(result);
790        if _result.is_err() {
791            self.control_handle.shutdown();
792        }
793        self.drop_without_shutdown();
794        _result
795    }
796
797    /// Similar to "send" but does not shutdown the channel if an error occurs.
798    pub fn send_no_shutdown_on_err(
799        self,
800        mut result: Result<(&DeviceDescriptor, &[Vec<FunctionDescriptor>]), i32>,
801    ) -> Result<(), fidl::Error> {
802        let _result = self.send_raw(result);
803        self.drop_without_shutdown();
804        _result
805    }
806
807    fn send_raw(
808        &self,
809        mut result: Result<(&DeviceDescriptor, &[Vec<FunctionDescriptor>]), i32>,
810    ) -> Result<(), fidl::Error> {
811        self.control_handle.inner.send::<fidl::encoding::FlexibleResultType<
812            DeviceGetConfigurationResponse,
813            i32,
814        >>(
815            fidl::encoding::FlexibleResult::new(result),
816            self.tx_id,
817            0x19fe4f37c3b52e3a,
818            fidl::encoding::DynamicFlags::FLEXIBLE,
819        )
820    }
821}
822
823#[must_use = "FIDL methods require a response to be sent"]
824#[derive(Debug)]
825pub struct DeviceSetConfigurationResponder {
826    control_handle: std::mem::ManuallyDrop<DeviceControlHandle>,
827    tx_id: u32,
828}
829
830/// Set the the channel to be shutdown (see [`DeviceControlHandle::shutdown`])
831/// if the responder is dropped without sending a response, so that the client
832/// doesn't hang. To prevent this behavior, call `drop_without_shutdown`.
833impl std::ops::Drop for DeviceSetConfigurationResponder {
834    fn drop(&mut self) {
835        self.control_handle.shutdown();
836        // Safety: drops once, never accessed again
837        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
838    }
839}
840
841impl fidl::endpoints::Responder for DeviceSetConfigurationResponder {
842    type ControlHandle = DeviceControlHandle;
843
844    fn control_handle(&self) -> &DeviceControlHandle {
845        &self.control_handle
846    }
847
848    fn drop_without_shutdown(mut self) {
849        // Safety: drops once, never accessed again due to mem::forget
850        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
851        // Prevent Drop from running (which would shut down the channel)
852        std::mem::forget(self);
853    }
854}
855
856impl DeviceSetConfigurationResponder {
857    /// Sends a response to the FIDL transaction.
858    ///
859    /// Sets the channel to shutdown if an error occurs.
860    pub fn send(self, mut result: Result<(), i32>) -> Result<(), fidl::Error> {
861        let _result = self.send_raw(result);
862        if _result.is_err() {
863            self.control_handle.shutdown();
864        }
865        self.drop_without_shutdown();
866        _result
867    }
868
869    /// Similar to "send" but does not shutdown the channel if an error occurs.
870    pub fn send_no_shutdown_on_err(self, mut result: Result<(), i32>) -> Result<(), fidl::Error> {
871        let _result = self.send_raw(result);
872        self.drop_without_shutdown();
873        _result
874    }
875
876    fn send_raw(&self, mut result: Result<(), i32>) -> Result<(), fidl::Error> {
877        self.control_handle.inner.send::<fidl::encoding::FlexibleResultType<
878            fidl::encoding::EmptyStruct,
879            i32,
880        >>(
881            fidl::encoding::FlexibleResult::new(result),
882            self.tx_id,
883            0x464bafee91a3d6de,
884            fidl::encoding::DynamicFlags::FLEXIBLE,
885        )
886    }
887}
888
889#[must_use = "FIDL methods require a response to be sent"]
890#[derive(Debug)]
891pub struct DeviceClearFunctionsResponder {
892    control_handle: std::mem::ManuallyDrop<DeviceControlHandle>,
893    tx_id: u32,
894}
895
896/// Set the the channel to be shutdown (see [`DeviceControlHandle::shutdown`])
897/// if the responder is dropped without sending a response, so that the client
898/// doesn't hang. To prevent this behavior, call `drop_without_shutdown`.
899impl std::ops::Drop for DeviceClearFunctionsResponder {
900    fn drop(&mut self) {
901        self.control_handle.shutdown();
902        // Safety: drops once, never accessed again
903        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
904    }
905}
906
907impl fidl::endpoints::Responder for DeviceClearFunctionsResponder {
908    type ControlHandle = DeviceControlHandle;
909
910    fn control_handle(&self) -> &DeviceControlHandle {
911        &self.control_handle
912    }
913
914    fn drop_without_shutdown(mut self) {
915        // Safety: drops once, never accessed again due to mem::forget
916        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
917        // Prevent Drop from running (which would shut down the channel)
918        std::mem::forget(self);
919    }
920}
921
922impl DeviceClearFunctionsResponder {
923    /// Sends a response to the FIDL transaction.
924    ///
925    /// Sets the channel to shutdown if an error occurs.
926    pub fn send(self) -> Result<(), fidl::Error> {
927        let _result = self.send_raw();
928        if _result.is_err() {
929            self.control_handle.shutdown();
930        }
931        self.drop_without_shutdown();
932        _result
933    }
934
935    /// Similar to "send" but does not shutdown the channel if an error occurs.
936    pub fn send_no_shutdown_on_err(self) -> Result<(), fidl::Error> {
937        let _result = self.send_raw();
938        self.drop_without_shutdown();
939        _result
940    }
941
942    fn send_raw(&self) -> Result<(), fidl::Error> {
943        self.control_handle.inner.send::<fidl::encoding::FlexibleType<fidl::encoding::EmptyStruct>>(
944            fidl::encoding::Flexible::new(()),
945            self.tx_id,
946            0x67d9d8086dfab0cb,
947            fidl::encoding::DynamicFlags::FLEXIBLE,
948        )
949    }
950}
951
952#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
953pub struct EventsMarker;
954
955impl fidl::endpoints::ProtocolMarker for EventsMarker {
956    type Proxy = EventsProxy;
957    type RequestStream = EventsRequestStream;
958    #[cfg(target_os = "fuchsia")]
959    type SynchronousProxy = EventsSynchronousProxy;
960
961    const DEBUG_NAME: &'static str = "(anonymous) Events";
962}
963
964pub trait EventsProxyInterface: Send + Sync {
965    type FunctionRegisteredResponseFut: std::future::Future<Output = Result<(), fidl::Error>> + Send;
966    fn r#function_registered(&self) -> Self::FunctionRegisteredResponseFut;
967    fn r#functions_cleared(&self) -> Result<(), fidl::Error>;
968}
969#[derive(Debug)]
970#[cfg(target_os = "fuchsia")]
971pub struct EventsSynchronousProxy {
972    client: fidl::client::sync::Client,
973}
974
975#[cfg(target_os = "fuchsia")]
976impl fidl::endpoints::SynchronousProxy for EventsSynchronousProxy {
977    type Proxy = EventsProxy;
978    type Protocol = EventsMarker;
979
980    fn from_channel(inner: fidl::Channel) -> Self {
981        Self::new(inner)
982    }
983
984    fn into_channel(self) -> fidl::Channel {
985        self.client.into_channel()
986    }
987
988    fn as_channel(&self) -> &fidl::Channel {
989        self.client.as_channel()
990    }
991}
992
993#[cfg(target_os = "fuchsia")]
994impl EventsSynchronousProxy {
995    pub fn new(channel: fidl::Channel) -> Self {
996        Self { client: fidl::client::sync::Client::new(channel) }
997    }
998
999    pub fn into_channel(self) -> fidl::Channel {
1000        self.client.into_channel()
1001    }
1002
1003    /// Waits until an event arrives and returns it. It is safe for other
1004    /// threads to make concurrent requests while waiting for an event.
1005    pub fn wait_for_event(
1006        &self,
1007        deadline: zx::MonotonicInstant,
1008    ) -> Result<EventsEvent, fidl::Error> {
1009        EventsEvent::decode(self.client.wait_for_event::<EventsMarker>(deadline)?)
1010    }
1011
1012    /// Invoked when a function registers
1013    pub fn r#function_registered(
1014        &self,
1015        ___deadline: zx::MonotonicInstant,
1016    ) -> Result<(), fidl::Error> {
1017        let _response = self.client.send_query::<
1018            fidl::encoding::EmptyPayload,
1019            fidl::encoding::FlexibleType<fidl::encoding::EmptyStruct>,
1020            EventsMarker,
1021        >(
1022            (),
1023            0x191278425c4a96e8,
1024            fidl::encoding::DynamicFlags::FLEXIBLE,
1025            ___deadline,
1026        )?
1027        .into_result::<EventsMarker>("function_registered")?;
1028        Ok(_response)
1029    }
1030
1031    /// Invoked when all functions have been cleared.
1032    pub fn r#functions_cleared(&self) -> Result<(), fidl::Error> {
1033        self.client.send::<fidl::encoding::EmptyPayload>(
1034            (),
1035            0x6feab079055dacf1,
1036            fidl::encoding::DynamicFlags::FLEXIBLE,
1037        )
1038    }
1039}
1040
1041#[cfg(target_os = "fuchsia")]
1042impl From<EventsSynchronousProxy> for zx::NullableHandle {
1043    fn from(value: EventsSynchronousProxy) -> Self {
1044        value.into_channel().into()
1045    }
1046}
1047
1048#[cfg(target_os = "fuchsia")]
1049impl From<fidl::Channel> for EventsSynchronousProxy {
1050    fn from(value: fidl::Channel) -> Self {
1051        Self::new(value)
1052    }
1053}
1054
1055#[cfg(target_os = "fuchsia")]
1056impl fidl::endpoints::FromClient for EventsSynchronousProxy {
1057    type Protocol = EventsMarker;
1058
1059    fn from_client(value: fidl::endpoints::ClientEnd<EventsMarker>) -> Self {
1060        Self::new(value.into_channel())
1061    }
1062}
1063
1064#[derive(Debug, Clone)]
1065pub struct EventsProxy {
1066    client: fidl::client::Client<fidl::encoding::DefaultFuchsiaResourceDialect>,
1067}
1068
1069impl fidl::endpoints::Proxy for EventsProxy {
1070    type Protocol = EventsMarker;
1071
1072    fn from_channel(inner: ::fidl::AsyncChannel) -> Self {
1073        Self::new(inner)
1074    }
1075
1076    fn into_channel(self) -> Result<::fidl::AsyncChannel, Self> {
1077        self.client.into_channel().map_err(|client| Self { client })
1078    }
1079
1080    fn as_channel(&self) -> &::fidl::AsyncChannel {
1081        self.client.as_channel()
1082    }
1083}
1084
1085impl EventsProxy {
1086    /// Create a new Proxy for fuchsia.hardware.usb.peripheral/Events.
1087    pub fn new(channel: ::fidl::AsyncChannel) -> Self {
1088        let protocol_name = <EventsMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME;
1089        Self { client: fidl::client::Client::new(channel, protocol_name) }
1090    }
1091
1092    /// Get a Stream of events from the remote end of the protocol.
1093    ///
1094    /// # Panics
1095    ///
1096    /// Panics if the event stream was already taken.
1097    pub fn take_event_stream(&self) -> EventsEventStream {
1098        EventsEventStream { event_receiver: self.client.take_event_receiver() }
1099    }
1100
1101    /// Invoked when a function registers
1102    pub fn r#function_registered(
1103        &self,
1104    ) -> fidl::client::QueryResponseFut<(), fidl::encoding::DefaultFuchsiaResourceDialect> {
1105        EventsProxyInterface::r#function_registered(self)
1106    }
1107
1108    /// Invoked when all functions have been cleared.
1109    pub fn r#functions_cleared(&self) -> Result<(), fidl::Error> {
1110        EventsProxyInterface::r#functions_cleared(self)
1111    }
1112}
1113
1114impl EventsProxyInterface for EventsProxy {
1115    type FunctionRegisteredResponseFut =
1116        fidl::client::QueryResponseFut<(), fidl::encoding::DefaultFuchsiaResourceDialect>;
1117    fn r#function_registered(&self) -> Self::FunctionRegisteredResponseFut {
1118        fn _decode(
1119            mut _buf: Result<<fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc, fidl::Error>,
1120        ) -> Result<(), fidl::Error> {
1121            let _response = fidl::client::decode_transaction_body::<
1122                fidl::encoding::FlexibleType<fidl::encoding::EmptyStruct>,
1123                fidl::encoding::DefaultFuchsiaResourceDialect,
1124                0x191278425c4a96e8,
1125            >(_buf?)?
1126            .into_result::<EventsMarker>("function_registered")?;
1127            Ok(_response)
1128        }
1129        self.client.send_query_and_decode::<fidl::encoding::EmptyPayload, ()>(
1130            (),
1131            0x191278425c4a96e8,
1132            fidl::encoding::DynamicFlags::FLEXIBLE,
1133            _decode,
1134        )
1135    }
1136
1137    fn r#functions_cleared(&self) -> Result<(), fidl::Error> {
1138        self.client.send::<fidl::encoding::EmptyPayload>(
1139            (),
1140            0x6feab079055dacf1,
1141            fidl::encoding::DynamicFlags::FLEXIBLE,
1142        )
1143    }
1144}
1145
1146pub struct EventsEventStream {
1147    event_receiver: fidl::client::EventReceiver<fidl::encoding::DefaultFuchsiaResourceDialect>,
1148}
1149
1150impl std::marker::Unpin for EventsEventStream {}
1151
1152impl futures::stream::FusedStream for EventsEventStream {
1153    fn is_terminated(&self) -> bool {
1154        self.event_receiver.is_terminated()
1155    }
1156}
1157
1158impl futures::Stream for EventsEventStream {
1159    type Item = Result<EventsEvent, fidl::Error>;
1160
1161    fn poll_next(
1162        mut self: std::pin::Pin<&mut Self>,
1163        cx: &mut std::task::Context<'_>,
1164    ) -> std::task::Poll<Option<Self::Item>> {
1165        match futures::ready!(futures::stream::StreamExt::poll_next_unpin(
1166            &mut self.event_receiver,
1167            cx
1168        )?) {
1169            Some(buf) => std::task::Poll::Ready(Some(EventsEvent::decode(buf))),
1170            None => std::task::Poll::Ready(None),
1171        }
1172    }
1173}
1174
1175#[derive(Debug)]
1176pub enum EventsEvent {
1177    #[non_exhaustive]
1178    _UnknownEvent {
1179        /// Ordinal of the event that was sent.
1180        ordinal: u64,
1181    },
1182}
1183
1184impl EventsEvent {
1185    /// Decodes a message buffer as a [`EventsEvent`].
1186    fn decode(
1187        mut buf: <fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc,
1188    ) -> Result<EventsEvent, fidl::Error> {
1189        let (bytes, _handles) = buf.split_mut();
1190        let (tx_header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
1191        debug_assert_eq!(tx_header.tx_id, 0);
1192        match tx_header.ordinal {
1193            _ if tx_header.dynamic_flags().contains(fidl::encoding::DynamicFlags::FLEXIBLE) => {
1194                Ok(EventsEvent::_UnknownEvent { ordinal: tx_header.ordinal })
1195            }
1196            _ => Err(fidl::Error::UnknownOrdinal {
1197                ordinal: tx_header.ordinal,
1198                protocol_name: <EventsMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
1199            }),
1200        }
1201    }
1202}
1203
1204/// A Stream of incoming requests for fuchsia.hardware.usb.peripheral/Events.
1205pub struct EventsRequestStream {
1206    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
1207    is_terminated: bool,
1208}
1209
1210impl std::marker::Unpin for EventsRequestStream {}
1211
1212impl futures::stream::FusedStream for EventsRequestStream {
1213    fn is_terminated(&self) -> bool {
1214        self.is_terminated
1215    }
1216}
1217
1218impl fidl::endpoints::RequestStream for EventsRequestStream {
1219    type Protocol = EventsMarker;
1220    type ControlHandle = EventsControlHandle;
1221
1222    fn from_channel(channel: ::fidl::AsyncChannel) -> Self {
1223        Self { inner: std::sync::Arc::new(fidl::ServeInner::new(channel)), is_terminated: false }
1224    }
1225
1226    fn control_handle(&self) -> Self::ControlHandle {
1227        EventsControlHandle { inner: self.inner.clone() }
1228    }
1229
1230    fn into_inner(
1231        self,
1232    ) -> (::std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>, bool)
1233    {
1234        (self.inner, self.is_terminated)
1235    }
1236
1237    fn from_inner(
1238        inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
1239        is_terminated: bool,
1240    ) -> Self {
1241        Self { inner, is_terminated }
1242    }
1243}
1244
1245impl futures::Stream for EventsRequestStream {
1246    type Item = Result<EventsRequest, fidl::Error>;
1247
1248    fn poll_next(
1249        mut self: std::pin::Pin<&mut Self>,
1250        cx: &mut std::task::Context<'_>,
1251    ) -> std::task::Poll<Option<Self::Item>> {
1252        let this = &mut *self;
1253        if this.inner.check_shutdown(cx) {
1254            this.is_terminated = true;
1255            return std::task::Poll::Ready(None);
1256        }
1257        if this.is_terminated {
1258            panic!("polled EventsRequestStream after completion");
1259        }
1260        fidl::encoding::with_tls_decode_buf::<_, fidl::encoding::DefaultFuchsiaResourceDialect>(
1261            |bytes, handles| {
1262                match this.inner.channel().read_etc(cx, bytes, handles) {
1263                    std::task::Poll::Ready(Ok(())) => {}
1264                    std::task::Poll::Pending => return std::task::Poll::Pending,
1265                    std::task::Poll::Ready(Err(zx_status::Status::PEER_CLOSED)) => {
1266                        this.is_terminated = true;
1267                        return std::task::Poll::Ready(None);
1268                    }
1269                    std::task::Poll::Ready(Err(e)) => {
1270                        return std::task::Poll::Ready(Some(Err(fidl::Error::ServerRequestRead(
1271                            e.into(),
1272                        ))));
1273                    }
1274                }
1275
1276                // A message has been received from the channel
1277                let (header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
1278
1279                std::task::Poll::Ready(Some(match header.ordinal {
1280                    0x191278425c4a96e8 => {
1281                        header.validate_request_tx_id(fidl::MethodType::TwoWay)?;
1282                        let mut req = fidl::new_empty!(
1283                            fidl::encoding::EmptyPayload,
1284                            fidl::encoding::DefaultFuchsiaResourceDialect
1285                        );
1286                        fidl::encoding::Decoder::<fidl::encoding::DefaultFuchsiaResourceDialect>::decode_into::<fidl::encoding::EmptyPayload>(&header, _body_bytes, handles, &mut req)?;
1287                        let control_handle = EventsControlHandle { inner: this.inner.clone() };
1288                        Ok(EventsRequest::FunctionRegistered {
1289                            responder: EventsFunctionRegisteredResponder {
1290                                control_handle: std::mem::ManuallyDrop::new(control_handle),
1291                                tx_id: header.tx_id,
1292                            },
1293                        })
1294                    }
1295                    0x6feab079055dacf1 => {
1296                        header.validate_request_tx_id(fidl::MethodType::OneWay)?;
1297                        let mut req = fidl::new_empty!(
1298                            fidl::encoding::EmptyPayload,
1299                            fidl::encoding::DefaultFuchsiaResourceDialect
1300                        );
1301                        fidl::encoding::Decoder::<fidl::encoding::DefaultFuchsiaResourceDialect>::decode_into::<fidl::encoding::EmptyPayload>(&header, _body_bytes, handles, &mut req)?;
1302                        let control_handle = EventsControlHandle { inner: this.inner.clone() };
1303                        Ok(EventsRequest::FunctionsCleared { control_handle })
1304                    }
1305                    _ if header.tx_id == 0
1306                        && header
1307                            .dynamic_flags()
1308                            .contains(fidl::encoding::DynamicFlags::FLEXIBLE) =>
1309                    {
1310                        Ok(EventsRequest::_UnknownMethod {
1311                            ordinal: header.ordinal,
1312                            control_handle: EventsControlHandle { inner: this.inner.clone() },
1313                            method_type: fidl::MethodType::OneWay,
1314                        })
1315                    }
1316                    _ if header
1317                        .dynamic_flags()
1318                        .contains(fidl::encoding::DynamicFlags::FLEXIBLE) =>
1319                    {
1320                        this.inner.send_framework_err(
1321                            fidl::encoding::FrameworkErr::UnknownMethod,
1322                            header.tx_id,
1323                            header.ordinal,
1324                            header.dynamic_flags(),
1325                            (bytes, handles),
1326                        )?;
1327                        Ok(EventsRequest::_UnknownMethod {
1328                            ordinal: header.ordinal,
1329                            control_handle: EventsControlHandle { inner: this.inner.clone() },
1330                            method_type: fidl::MethodType::TwoWay,
1331                        })
1332                    }
1333                    _ => Err(fidl::Error::UnknownOrdinal {
1334                        ordinal: header.ordinal,
1335                        protocol_name:
1336                            <EventsMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
1337                    }),
1338                }))
1339            },
1340        )
1341    }
1342}
1343
1344/// Events protocol that is used as a callback to inform the client
1345/// of the completion of various server-side events.
1346/// This callback interface can be registered using the SetStateChangeListener
1347/// method on the Device protocol.
1348#[derive(Debug)]
1349pub enum EventsRequest {
1350    /// Invoked when a function registers
1351    FunctionRegistered { responder: EventsFunctionRegisteredResponder },
1352    /// Invoked when all functions have been cleared.
1353    FunctionsCleared { control_handle: EventsControlHandle },
1354    /// An interaction was received which does not match any known method.
1355    #[non_exhaustive]
1356    _UnknownMethod {
1357        /// Ordinal of the method that was called.
1358        ordinal: u64,
1359        control_handle: EventsControlHandle,
1360        method_type: fidl::MethodType,
1361    },
1362}
1363
1364impl EventsRequest {
1365    #[allow(irrefutable_let_patterns)]
1366    pub fn into_function_registered(self) -> Option<(EventsFunctionRegisteredResponder)> {
1367        if let EventsRequest::FunctionRegistered { responder } = self {
1368            Some((responder))
1369        } else {
1370            None
1371        }
1372    }
1373
1374    #[allow(irrefutable_let_patterns)]
1375    pub fn into_functions_cleared(self) -> Option<(EventsControlHandle)> {
1376        if let EventsRequest::FunctionsCleared { control_handle } = self {
1377            Some((control_handle))
1378        } else {
1379            None
1380        }
1381    }
1382
1383    /// Name of the method defined in FIDL
1384    pub fn method_name(&self) -> &'static str {
1385        match *self {
1386            EventsRequest::FunctionRegistered { .. } => "function_registered",
1387            EventsRequest::FunctionsCleared { .. } => "functions_cleared",
1388            EventsRequest::_UnknownMethod { method_type: fidl::MethodType::OneWay, .. } => {
1389                "unknown one-way method"
1390            }
1391            EventsRequest::_UnknownMethod { method_type: fidl::MethodType::TwoWay, .. } => {
1392                "unknown two-way method"
1393            }
1394        }
1395    }
1396}
1397
1398#[derive(Debug, Clone)]
1399pub struct EventsControlHandle {
1400    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
1401}
1402
1403impl EventsControlHandle {
1404    pub fn shutdown_with_epitaph(&self, status: impl Into<fidl::Epitaph>) {
1405        self.inner.shutdown_with_epitaph(status.into())
1406    }
1407}
1408
1409impl fidl::endpoints::ControlHandle for EventsControlHandle {
1410    fn shutdown(&self) {
1411        self.inner.shutdown()
1412    }
1413
1414    fn shutdown_with_epitaph(&self, status: fidl::Epitaph) {
1415        self.inner.shutdown_with_epitaph(status)
1416    }
1417
1418    fn is_closed(&self) -> bool {
1419        self.inner.channel().is_closed()
1420    }
1421    fn on_closed(&self) -> fidl::OnSignalsRef<'_> {
1422        self.inner.channel().on_closed()
1423    }
1424
1425    #[cfg(target_os = "fuchsia")]
1426    fn signal_peer(
1427        &self,
1428        clear_mask: zx::Signals,
1429        set_mask: zx::Signals,
1430    ) -> Result<(), zx_status::Status> {
1431        use fidl::Peered;
1432        self.inner.channel().signal_peer(clear_mask, set_mask)
1433    }
1434}
1435
1436impl EventsControlHandle {}
1437
1438#[must_use = "FIDL methods require a response to be sent"]
1439#[derive(Debug)]
1440pub struct EventsFunctionRegisteredResponder {
1441    control_handle: std::mem::ManuallyDrop<EventsControlHandle>,
1442    tx_id: u32,
1443}
1444
1445/// Set the the channel to be shutdown (see [`EventsControlHandle::shutdown`])
1446/// if the responder is dropped without sending a response, so that the client
1447/// doesn't hang. To prevent this behavior, call `drop_without_shutdown`.
1448impl std::ops::Drop for EventsFunctionRegisteredResponder {
1449    fn drop(&mut self) {
1450        self.control_handle.shutdown();
1451        // Safety: drops once, never accessed again
1452        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
1453    }
1454}
1455
1456impl fidl::endpoints::Responder for EventsFunctionRegisteredResponder {
1457    type ControlHandle = EventsControlHandle;
1458
1459    fn control_handle(&self) -> &EventsControlHandle {
1460        &self.control_handle
1461    }
1462
1463    fn drop_without_shutdown(mut self) {
1464        // Safety: drops once, never accessed again due to mem::forget
1465        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
1466        // Prevent Drop from running (which would shut down the channel)
1467        std::mem::forget(self);
1468    }
1469}
1470
1471impl EventsFunctionRegisteredResponder {
1472    /// Sends a response to the FIDL transaction.
1473    ///
1474    /// Sets the channel to shutdown if an error occurs.
1475    pub fn send(self) -> Result<(), fidl::Error> {
1476        let _result = self.send_raw();
1477        if _result.is_err() {
1478            self.control_handle.shutdown();
1479        }
1480        self.drop_without_shutdown();
1481        _result
1482    }
1483
1484    /// Similar to "send" but does not shutdown the channel if an error occurs.
1485    pub fn send_no_shutdown_on_err(self) -> Result<(), fidl::Error> {
1486        let _result = self.send_raw();
1487        self.drop_without_shutdown();
1488        _result
1489    }
1490
1491    fn send_raw(&self) -> Result<(), fidl::Error> {
1492        self.control_handle.inner.send::<fidl::encoding::FlexibleType<fidl::encoding::EmptyStruct>>(
1493            fidl::encoding::Flexible::new(()),
1494            self.tx_id,
1495            0x191278425c4a96e8,
1496            fidl::encoding::DynamicFlags::FLEXIBLE,
1497        )
1498    }
1499}
1500
1501#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
1502pub struct ServiceMarker;
1503
1504#[cfg(target_os = "fuchsia")]
1505impl fidl::endpoints::ServiceMarker for ServiceMarker {
1506    type Proxy = ServiceProxy;
1507    type Request = ServiceRequest;
1508    const SERVICE_NAME: &'static str = "fuchsia.hardware.usb.peripheral.Service";
1509}
1510
1511/// A request for one of the member protocols of Service.
1512///
1513#[cfg(target_os = "fuchsia")]
1514pub enum ServiceRequest {
1515    Device(DeviceRequestStream),
1516}
1517
1518#[cfg(target_os = "fuchsia")]
1519impl fidl::endpoints::ServiceRequest for ServiceRequest {
1520    type Service = ServiceMarker;
1521
1522    fn dispatch(name: &str, _channel: fidl::AsyncChannel) -> Self {
1523        match name {
1524            "device" => Self::Device(
1525                <DeviceRequestStream as fidl::endpoints::RequestStream>::from_channel(_channel),
1526            ),
1527            _ => panic!("no such member protocol name for service Service"),
1528        }
1529    }
1530
1531    fn member_names() -> &'static [&'static str] {
1532        &["device"]
1533    }
1534}
1535#[cfg(target_os = "fuchsia")]
1536pub struct ServiceProxy(#[allow(dead_code)] Box<dyn fidl::endpoints::MemberOpener>);
1537
1538#[cfg(target_os = "fuchsia")]
1539impl fidl::endpoints::ServiceProxy for ServiceProxy {
1540    type Service = ServiceMarker;
1541
1542    fn from_member_opener(opener: Box<dyn fidl::endpoints::MemberOpener>) -> Self {
1543        Self(opener)
1544    }
1545}
1546
1547#[cfg(target_os = "fuchsia")]
1548impl ServiceProxy {
1549    pub fn connect_to_device(&self) -> Result<DeviceProxy, fidl::Error> {
1550        let (proxy, server_end) = fidl::endpoints::create_proxy::<DeviceMarker>();
1551        self.connect_channel_to_device(server_end)?;
1552        Ok(proxy)
1553    }
1554
1555    /// Like `connect_to_device`, but returns a sync proxy.
1556    /// See [`Self::connect_to_device`] for more details.
1557    pub fn connect_to_device_sync(&self) -> Result<DeviceSynchronousProxy, fidl::Error> {
1558        let (proxy, server_end) = fidl::endpoints::create_sync_proxy::<DeviceMarker>();
1559        self.connect_channel_to_device(server_end)?;
1560        Ok(proxy)
1561    }
1562
1563    /// Like `connect_to_device`, but accepts a server end.
1564    /// See [`Self::connect_to_device`] for more details.
1565    pub fn connect_channel_to_device(
1566        &self,
1567        server_end: fidl::endpoints::ServerEnd<DeviceMarker>,
1568    ) -> Result<(), fidl::Error> {
1569        self.0.open_member("device", server_end.into_channel())
1570    }
1571
1572    pub fn instance_name(&self) -> &str {
1573        self.0.instance_name()
1574    }
1575}
1576
1577mod internal {
1578    use super::*;
1579
1580    impl fidl::encoding::ResourceTypeMarker for DeviceSetStateChangeListenerRequest {
1581        type Borrowed<'a> = &'a mut Self;
1582        fn take_or_borrow<'a>(
1583            value: &'a mut <Self as fidl::encoding::TypeMarker>::Owned,
1584        ) -> Self::Borrowed<'a> {
1585            value
1586        }
1587    }
1588
1589    unsafe impl fidl::encoding::TypeMarker for DeviceSetStateChangeListenerRequest {
1590        type Owned = Self;
1591
1592        #[inline(always)]
1593        fn inline_align(_context: fidl::encoding::Context) -> usize {
1594            4
1595        }
1596
1597        #[inline(always)]
1598        fn inline_size(_context: fidl::encoding::Context) -> usize {
1599            4
1600        }
1601    }
1602
1603    unsafe impl
1604        fidl::encoding::Encode<
1605            DeviceSetStateChangeListenerRequest,
1606            fidl::encoding::DefaultFuchsiaResourceDialect,
1607        > for &mut DeviceSetStateChangeListenerRequest
1608    {
1609        #[inline]
1610        unsafe fn encode(
1611            self,
1612            encoder: &mut fidl::encoding::Encoder<
1613                '_,
1614                fidl::encoding::DefaultFuchsiaResourceDialect,
1615            >,
1616            offset: usize,
1617            _depth: fidl::encoding::Depth,
1618        ) -> fidl::Result<()> {
1619            encoder.debug_check_bounds::<DeviceSetStateChangeListenerRequest>(offset);
1620            // Delegate to tuple encoding.
1621            fidl::encoding::Encode::<DeviceSetStateChangeListenerRequest, fidl::encoding::DefaultFuchsiaResourceDialect>::encode(
1622                (
1623                    <fidl::encoding::Endpoint<fidl::endpoints::ClientEnd<EventsMarker>> as fidl::encoding::ResourceTypeMarker>::take_or_borrow(&mut self.listener),
1624                ),
1625                encoder, offset, _depth
1626            )
1627        }
1628    }
1629    unsafe impl<
1630        T0: fidl::encoding::Encode<
1631                fidl::encoding::Endpoint<fidl::endpoints::ClientEnd<EventsMarker>>,
1632                fidl::encoding::DefaultFuchsiaResourceDialect,
1633            >,
1634    >
1635        fidl::encoding::Encode<
1636            DeviceSetStateChangeListenerRequest,
1637            fidl::encoding::DefaultFuchsiaResourceDialect,
1638        > for (T0,)
1639    {
1640        #[inline]
1641        unsafe fn encode(
1642            self,
1643            encoder: &mut fidl::encoding::Encoder<
1644                '_,
1645                fidl::encoding::DefaultFuchsiaResourceDialect,
1646            >,
1647            offset: usize,
1648            depth: fidl::encoding::Depth,
1649        ) -> fidl::Result<()> {
1650            encoder.debug_check_bounds::<DeviceSetStateChangeListenerRequest>(offset);
1651            // Zero out padding regions. There's no need to apply masks
1652            // because the unmasked parts will be overwritten by fields.
1653            // Write the fields.
1654            self.0.encode(encoder, offset + 0, depth)?;
1655            Ok(())
1656        }
1657    }
1658
1659    impl fidl::encoding::Decode<Self, fidl::encoding::DefaultFuchsiaResourceDialect>
1660        for DeviceSetStateChangeListenerRequest
1661    {
1662        #[inline(always)]
1663        fn new_empty() -> Self {
1664            Self {
1665                listener: fidl::new_empty!(
1666                    fidl::encoding::Endpoint<fidl::endpoints::ClientEnd<EventsMarker>>,
1667                    fidl::encoding::DefaultFuchsiaResourceDialect
1668                ),
1669            }
1670        }
1671
1672        #[inline]
1673        unsafe fn decode(
1674            &mut self,
1675            decoder: &mut fidl::encoding::Decoder<
1676                '_,
1677                fidl::encoding::DefaultFuchsiaResourceDialect,
1678            >,
1679            offset: usize,
1680            _depth: fidl::encoding::Depth,
1681        ) -> fidl::Result<()> {
1682            decoder.debug_check_bounds::<Self>(offset);
1683            // Verify that padding bytes are zero.
1684            fidl::decode!(
1685                fidl::encoding::Endpoint<fidl::endpoints::ClientEnd<EventsMarker>>,
1686                fidl::encoding::DefaultFuchsiaResourceDialect,
1687                &mut self.listener,
1688                decoder,
1689                offset + 0,
1690                _depth
1691            )?;
1692            Ok(())
1693        }
1694    }
1695}