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