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