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