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