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 _};
10use futures::future::{self, MaybeDone, TryFutureExt};
11use zx_status;
12
13pub const MAX_STRING_LENGTH: u64 = 64;
14
15#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
16pub struct EchoEchoStringRequest {
17    pub value: Option<String>,
18}
19
20impl fidl::Persistable for EchoEchoStringRequest {}
21
22#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
23pub struct EchoEchoStringResponse {
24    pub response: Option<String>,
25}
26
27impl fidl::Persistable for EchoEchoStringResponse {}
28
29#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
30pub struct EchoMarker;
31
32impl fidl::endpoints::ProtocolMarker for EchoMarker {
33    type Proxy = EchoProxy;
34    type RequestStream = EchoRequestStream;
35    #[cfg(target_os = "fuchsia")]
36    type SynchronousProxy = EchoSynchronousProxy;
37
38    const DEBUG_NAME: &'static str = "fidl.examples.routing.echo.Echo";
39}
40impl fidl::endpoints::DiscoverableProtocolMarker for EchoMarker {}
41
42pub trait EchoProxyInterface: Send + Sync {
43    type EchoStringResponseFut: std::future::Future<Output = Result<Option<String>, fidl::Error>>
44        + Send;
45    fn r#echo_string(&self, value: Option<&str>) -> Self::EchoStringResponseFut;
46}
47#[derive(Debug)]
48#[cfg(target_os = "fuchsia")]
49pub struct EchoSynchronousProxy {
50    client: fidl::client::sync::Client,
51}
52
53#[cfg(target_os = "fuchsia")]
54impl fidl::endpoints::SynchronousProxy for EchoSynchronousProxy {
55    type Proxy = EchoProxy;
56    type Protocol = EchoMarker;
57
58    fn from_channel(inner: fidl::Channel) -> Self {
59        Self::new(inner)
60    }
61
62    fn into_channel(self) -> fidl::Channel {
63        self.client.into_channel()
64    }
65
66    fn as_channel(&self) -> &fidl::Channel {
67        self.client.as_channel()
68    }
69}
70
71#[cfg(target_os = "fuchsia")]
72impl EchoSynchronousProxy {
73    pub fn new(channel: fidl::Channel) -> Self {
74        let protocol_name = <EchoMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME;
75        Self { client: fidl::client::sync::Client::new(channel, protocol_name) }
76    }
77
78    pub fn into_channel(self) -> fidl::Channel {
79        self.client.into_channel()
80    }
81
82    /// Waits until an event arrives and returns it. It is safe for other
83    /// threads to make concurrent requests while waiting for an event.
84    pub fn wait_for_event(&self, deadline: zx::MonotonicInstant) -> Result<EchoEvent, fidl::Error> {
85        EchoEvent::decode(self.client.wait_for_event(deadline)?)
86    }
87
88    /// Returns the input.
89    pub fn r#echo_string(
90        &self,
91        mut value: Option<&str>,
92        ___deadline: zx::MonotonicInstant,
93    ) -> Result<Option<String>, fidl::Error> {
94        let _response = self.client.send_query::<EchoEchoStringRequest, EchoEchoStringResponse>(
95            (value,),
96            0x638ea3c09c0084f2,
97            fidl::encoding::DynamicFlags::empty(),
98            ___deadline,
99        )?;
100        Ok(_response.response)
101    }
102}
103
104#[derive(Debug, Clone)]
105pub struct EchoProxy {
106    client: fidl::client::Client<fidl::encoding::DefaultFuchsiaResourceDialect>,
107}
108
109impl fidl::endpoints::Proxy for EchoProxy {
110    type Protocol = EchoMarker;
111
112    fn from_channel(inner: ::fidl::AsyncChannel) -> Self {
113        Self::new(inner)
114    }
115
116    fn into_channel(self) -> Result<::fidl::AsyncChannel, Self> {
117        self.client.into_channel().map_err(|client| Self { client })
118    }
119
120    fn as_channel(&self) -> &::fidl::AsyncChannel {
121        self.client.as_channel()
122    }
123}
124
125impl EchoProxy {
126    /// Create a new Proxy for fidl.examples.routing.echo/Echo.
127    pub fn new(channel: ::fidl::AsyncChannel) -> Self {
128        let protocol_name = <EchoMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME;
129        Self { client: fidl::client::Client::new(channel, protocol_name) }
130    }
131
132    /// Get a Stream of events from the remote end of the protocol.
133    ///
134    /// # Panics
135    ///
136    /// Panics if the event stream was already taken.
137    pub fn take_event_stream(&self) -> EchoEventStream {
138        EchoEventStream { event_receiver: self.client.take_event_receiver() }
139    }
140
141    /// Returns the input.
142    pub fn r#echo_string(
143        &self,
144        mut value: Option<&str>,
145    ) -> fidl::client::QueryResponseFut<Option<String>, fidl::encoding::DefaultFuchsiaResourceDialect>
146    {
147        EchoProxyInterface::r#echo_string(self, value)
148    }
149}
150
151impl EchoProxyInterface for EchoProxy {
152    type EchoStringResponseFut = fidl::client::QueryResponseFut<
153        Option<String>,
154        fidl::encoding::DefaultFuchsiaResourceDialect,
155    >;
156    fn r#echo_string(&self, mut value: Option<&str>) -> Self::EchoStringResponseFut {
157        fn _decode(
158            mut _buf: Result<<fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc, fidl::Error>,
159        ) -> Result<Option<String>, fidl::Error> {
160            let _response = fidl::client::decode_transaction_body::<
161                EchoEchoStringResponse,
162                fidl::encoding::DefaultFuchsiaResourceDialect,
163                0x638ea3c09c0084f2,
164            >(_buf?)?;
165            Ok(_response.response)
166        }
167        self.client.send_query_and_decode::<EchoEchoStringRequest, Option<String>>(
168            (value,),
169            0x638ea3c09c0084f2,
170            fidl::encoding::DynamicFlags::empty(),
171            _decode,
172        )
173    }
174}
175
176pub struct EchoEventStream {
177    event_receiver: fidl::client::EventReceiver<fidl::encoding::DefaultFuchsiaResourceDialect>,
178}
179
180impl std::marker::Unpin for EchoEventStream {}
181
182impl futures::stream::FusedStream for EchoEventStream {
183    fn is_terminated(&self) -> bool {
184        self.event_receiver.is_terminated()
185    }
186}
187
188impl futures::Stream for EchoEventStream {
189    type Item = Result<EchoEvent, fidl::Error>;
190
191    fn poll_next(
192        mut self: std::pin::Pin<&mut Self>,
193        cx: &mut std::task::Context<'_>,
194    ) -> std::task::Poll<Option<Self::Item>> {
195        match futures::ready!(futures::stream::StreamExt::poll_next_unpin(
196            &mut self.event_receiver,
197            cx
198        )?) {
199            Some(buf) => std::task::Poll::Ready(Some(EchoEvent::decode(buf))),
200            None => std::task::Poll::Ready(None),
201        }
202    }
203}
204
205#[derive(Debug)]
206pub enum EchoEvent {}
207
208impl EchoEvent {
209    /// Decodes a message buffer as a [`EchoEvent`].
210    fn decode(
211        mut buf: <fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc,
212    ) -> Result<EchoEvent, fidl::Error> {
213        let (bytes, _handles) = buf.split_mut();
214        let (tx_header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
215        debug_assert_eq!(tx_header.tx_id, 0);
216        match tx_header.ordinal {
217            _ => Err(fidl::Error::UnknownOrdinal {
218                ordinal: tx_header.ordinal,
219                protocol_name: <EchoMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
220            }),
221        }
222    }
223}
224
225/// A Stream of incoming requests for fidl.examples.routing.echo/Echo.
226pub struct EchoRequestStream {
227    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
228    is_terminated: bool,
229}
230
231impl std::marker::Unpin for EchoRequestStream {}
232
233impl futures::stream::FusedStream for EchoRequestStream {
234    fn is_terminated(&self) -> bool {
235        self.is_terminated
236    }
237}
238
239impl fidl::endpoints::RequestStream for EchoRequestStream {
240    type Protocol = EchoMarker;
241    type ControlHandle = EchoControlHandle;
242
243    fn from_channel(channel: ::fidl::AsyncChannel) -> Self {
244        Self { inner: std::sync::Arc::new(fidl::ServeInner::new(channel)), is_terminated: false }
245    }
246
247    fn control_handle(&self) -> Self::ControlHandle {
248        EchoControlHandle { inner: self.inner.clone() }
249    }
250
251    fn into_inner(
252        self,
253    ) -> (::std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>, bool)
254    {
255        (self.inner, self.is_terminated)
256    }
257
258    fn from_inner(
259        inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
260        is_terminated: bool,
261    ) -> Self {
262        Self { inner, is_terminated }
263    }
264}
265
266impl futures::Stream for EchoRequestStream {
267    type Item = Result<EchoRequest, fidl::Error>;
268
269    fn poll_next(
270        mut self: std::pin::Pin<&mut Self>,
271        cx: &mut std::task::Context<'_>,
272    ) -> std::task::Poll<Option<Self::Item>> {
273        let this = &mut *self;
274        if this.inner.check_shutdown(cx) {
275            this.is_terminated = true;
276            return std::task::Poll::Ready(None);
277        }
278        if this.is_terminated {
279            panic!("polled EchoRequestStream after completion");
280        }
281        fidl::encoding::with_tls_decode_buf::<_, fidl::encoding::DefaultFuchsiaResourceDialect>(
282            |bytes, handles| {
283                match this.inner.channel().read_etc(cx, bytes, handles) {
284                    std::task::Poll::Ready(Ok(())) => {}
285                    std::task::Poll::Pending => return std::task::Poll::Pending,
286                    std::task::Poll::Ready(Err(zx_status::Status::PEER_CLOSED)) => {
287                        this.is_terminated = true;
288                        return std::task::Poll::Ready(None);
289                    }
290                    std::task::Poll::Ready(Err(e)) => {
291                        return std::task::Poll::Ready(Some(Err(fidl::Error::ServerRequestRead(
292                            e.into(),
293                        ))))
294                    }
295                }
296
297                // A message has been received from the channel
298                let (header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
299
300                std::task::Poll::Ready(Some(match header.ordinal {
301                    0x638ea3c09c0084f2 => {
302                        header.validate_request_tx_id(fidl::MethodType::TwoWay)?;
303                        let mut req = fidl::new_empty!(
304                            EchoEchoStringRequest,
305                            fidl::encoding::DefaultFuchsiaResourceDialect
306                        );
307                        fidl::encoding::Decoder::<fidl::encoding::DefaultFuchsiaResourceDialect>::decode_into::<EchoEchoStringRequest>(&header, _body_bytes, handles, &mut req)?;
308                        let control_handle = EchoControlHandle { inner: this.inner.clone() };
309                        Ok(EchoRequest::EchoString {
310                            value: req.value,
311
312                            responder: EchoEchoStringResponder {
313                                control_handle: std::mem::ManuallyDrop::new(control_handle),
314                                tx_id: header.tx_id,
315                            },
316                        })
317                    }
318                    _ => Err(fidl::Error::UnknownOrdinal {
319                        ordinal: header.ordinal,
320                        protocol_name: <EchoMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
321                    }),
322                }))
323            },
324        )
325    }
326}
327
328#[derive(Debug)]
329pub enum EchoRequest {
330    /// Returns the input.
331    EchoString { value: Option<String>, responder: EchoEchoStringResponder },
332}
333
334impl EchoRequest {
335    #[allow(irrefutable_let_patterns)]
336    pub fn into_echo_string(self) -> Option<(Option<String>, EchoEchoStringResponder)> {
337        if let EchoRequest::EchoString { value, responder } = self {
338            Some((value, responder))
339        } else {
340            None
341        }
342    }
343
344    /// Name of the method defined in FIDL
345    pub fn method_name(&self) -> &'static str {
346        match *self {
347            EchoRequest::EchoString { .. } => "echo_string",
348        }
349    }
350}
351
352#[derive(Debug, Clone)]
353pub struct EchoControlHandle {
354    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
355}
356
357impl fidl::endpoints::ControlHandle for EchoControlHandle {
358    fn shutdown(&self) {
359        self.inner.shutdown()
360    }
361    fn shutdown_with_epitaph(&self, status: zx_status::Status) {
362        self.inner.shutdown_with_epitaph(status)
363    }
364
365    fn is_closed(&self) -> bool {
366        self.inner.channel().is_closed()
367    }
368    fn on_closed(&self) -> fidl::OnSignalsRef<'_> {
369        self.inner.channel().on_closed()
370    }
371
372    #[cfg(target_os = "fuchsia")]
373    fn signal_peer(
374        &self,
375        clear_mask: zx::Signals,
376        set_mask: zx::Signals,
377    ) -> Result<(), zx_status::Status> {
378        use fidl::Peered;
379        self.inner.channel().signal_peer(clear_mask, set_mask)
380    }
381}
382
383impl EchoControlHandle {}
384
385#[must_use = "FIDL methods require a response to be sent"]
386#[derive(Debug)]
387pub struct EchoEchoStringResponder {
388    control_handle: std::mem::ManuallyDrop<EchoControlHandle>,
389    tx_id: u32,
390}
391
392/// Set the the channel to be shutdown (see [`EchoControlHandle::shutdown`])
393/// if the responder is dropped without sending a response, so that the client
394/// doesn't hang. To prevent this behavior, call `drop_without_shutdown`.
395impl std::ops::Drop for EchoEchoStringResponder {
396    fn drop(&mut self) {
397        self.control_handle.shutdown();
398        // Safety: drops once, never accessed again
399        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
400    }
401}
402
403impl fidl::endpoints::Responder for EchoEchoStringResponder {
404    type ControlHandle = EchoControlHandle;
405
406    fn control_handle(&self) -> &EchoControlHandle {
407        &self.control_handle
408    }
409
410    fn drop_without_shutdown(mut self) {
411        // Safety: drops once, never accessed again due to mem::forget
412        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
413        // Prevent Drop from running (which would shut down the channel)
414        std::mem::forget(self);
415    }
416}
417
418impl EchoEchoStringResponder {
419    /// Sends a response to the FIDL transaction.
420    ///
421    /// Sets the channel to shutdown if an error occurs.
422    pub fn send(self, mut response: Option<&str>) -> Result<(), fidl::Error> {
423        let _result = self.send_raw(response);
424        if _result.is_err() {
425            self.control_handle.shutdown();
426        }
427        self.drop_without_shutdown();
428        _result
429    }
430
431    /// Similar to "send" but does not shutdown the channel if an error occurs.
432    pub fn send_no_shutdown_on_err(self, mut response: Option<&str>) -> Result<(), fidl::Error> {
433        let _result = self.send_raw(response);
434        self.drop_without_shutdown();
435        _result
436    }
437
438    fn send_raw(&self, mut response: Option<&str>) -> Result<(), fidl::Error> {
439        self.control_handle.inner.send::<EchoEchoStringResponse>(
440            (response,),
441            self.tx_id,
442            0x638ea3c09c0084f2,
443            fidl::encoding::DynamicFlags::empty(),
444        )
445    }
446}
447
448mod internal {
449    use super::*;
450
451    impl fidl::encoding::ValueTypeMarker for EchoEchoStringRequest {
452        type Borrowed<'a> = &'a Self;
453        fn borrow(value: &<Self as fidl::encoding::TypeMarker>::Owned) -> Self::Borrowed<'_> {
454            value
455        }
456    }
457
458    unsafe impl fidl::encoding::TypeMarker for EchoEchoStringRequest {
459        type Owned = Self;
460
461        #[inline(always)]
462        fn inline_align(_context: fidl::encoding::Context) -> usize {
463            8
464        }
465
466        #[inline(always)]
467        fn inline_size(_context: fidl::encoding::Context) -> usize {
468            16
469        }
470    }
471
472    unsafe impl<D: fidl::encoding::ResourceDialect> fidl::encoding::Encode<EchoEchoStringRequest, D>
473        for &EchoEchoStringRequest
474    {
475        #[inline]
476        unsafe fn encode(
477            self,
478            encoder: &mut fidl::encoding::Encoder<'_, D>,
479            offset: usize,
480            _depth: fidl::encoding::Depth,
481        ) -> fidl::Result<()> {
482            encoder.debug_check_bounds::<EchoEchoStringRequest>(offset);
483            // Delegate to tuple encoding.
484            fidl::encoding::Encode::<EchoEchoStringRequest, D>::encode(
485                (
486                    <fidl::encoding::Optional<fidl::encoding::BoundedString<64>> as fidl::encoding::ValueTypeMarker>::borrow(&self.value),
487                ),
488                encoder, offset, _depth
489            )
490        }
491    }
492    unsafe impl<
493            D: fidl::encoding::ResourceDialect,
494            T0: fidl::encoding::Encode<fidl::encoding::Optional<fidl::encoding::BoundedString<64>>, D>,
495        > fidl::encoding::Encode<EchoEchoStringRequest, D> for (T0,)
496    {
497        #[inline]
498        unsafe fn encode(
499            self,
500            encoder: &mut fidl::encoding::Encoder<'_, D>,
501            offset: usize,
502            depth: fidl::encoding::Depth,
503        ) -> fidl::Result<()> {
504            encoder.debug_check_bounds::<EchoEchoStringRequest>(offset);
505            // Zero out padding regions. There's no need to apply masks
506            // because the unmasked parts will be overwritten by fields.
507            // Write the fields.
508            self.0.encode(encoder, offset + 0, depth)?;
509            Ok(())
510        }
511    }
512
513    impl<D: fidl::encoding::ResourceDialect> fidl::encoding::Decode<Self, D> for EchoEchoStringRequest {
514        #[inline(always)]
515        fn new_empty() -> Self {
516            Self {
517                value: fidl::new_empty!(
518                    fidl::encoding::Optional<fidl::encoding::BoundedString<64>>,
519                    D
520                ),
521            }
522        }
523
524        #[inline]
525        unsafe fn decode(
526            &mut self,
527            decoder: &mut fidl::encoding::Decoder<'_, D>,
528            offset: usize,
529            _depth: fidl::encoding::Depth,
530        ) -> fidl::Result<()> {
531            decoder.debug_check_bounds::<Self>(offset);
532            // Verify that padding bytes are zero.
533            fidl::decode!(
534                fidl::encoding::Optional<fidl::encoding::BoundedString<64>>,
535                D,
536                &mut self.value,
537                decoder,
538                offset + 0,
539                _depth
540            )?;
541            Ok(())
542        }
543    }
544
545    impl fidl::encoding::ValueTypeMarker for EchoEchoStringResponse {
546        type Borrowed<'a> = &'a Self;
547        fn borrow(value: &<Self as fidl::encoding::TypeMarker>::Owned) -> Self::Borrowed<'_> {
548            value
549        }
550    }
551
552    unsafe impl fidl::encoding::TypeMarker for EchoEchoStringResponse {
553        type Owned = Self;
554
555        #[inline(always)]
556        fn inline_align(_context: fidl::encoding::Context) -> usize {
557            8
558        }
559
560        #[inline(always)]
561        fn inline_size(_context: fidl::encoding::Context) -> usize {
562            16
563        }
564    }
565
566    unsafe impl<D: fidl::encoding::ResourceDialect>
567        fidl::encoding::Encode<EchoEchoStringResponse, D> for &EchoEchoStringResponse
568    {
569        #[inline]
570        unsafe fn encode(
571            self,
572            encoder: &mut fidl::encoding::Encoder<'_, D>,
573            offset: usize,
574            _depth: fidl::encoding::Depth,
575        ) -> fidl::Result<()> {
576            encoder.debug_check_bounds::<EchoEchoStringResponse>(offset);
577            // Delegate to tuple encoding.
578            fidl::encoding::Encode::<EchoEchoStringResponse, D>::encode(
579                (
580                    <fidl::encoding::Optional<fidl::encoding::BoundedString<64>> as fidl::encoding::ValueTypeMarker>::borrow(&self.response),
581                ),
582                encoder, offset, _depth
583            )
584        }
585    }
586    unsafe impl<
587            D: fidl::encoding::ResourceDialect,
588            T0: fidl::encoding::Encode<fidl::encoding::Optional<fidl::encoding::BoundedString<64>>, D>,
589        > fidl::encoding::Encode<EchoEchoStringResponse, D> for (T0,)
590    {
591        #[inline]
592        unsafe fn encode(
593            self,
594            encoder: &mut fidl::encoding::Encoder<'_, D>,
595            offset: usize,
596            depth: fidl::encoding::Depth,
597        ) -> fidl::Result<()> {
598            encoder.debug_check_bounds::<EchoEchoStringResponse>(offset);
599            // Zero out padding regions. There's no need to apply masks
600            // because the unmasked parts will be overwritten by fields.
601            // Write the fields.
602            self.0.encode(encoder, offset + 0, depth)?;
603            Ok(())
604        }
605    }
606
607    impl<D: fidl::encoding::ResourceDialect> fidl::encoding::Decode<Self, D>
608        for EchoEchoStringResponse
609    {
610        #[inline(always)]
611        fn new_empty() -> Self {
612            Self {
613                response: fidl::new_empty!(
614                    fidl::encoding::Optional<fidl::encoding::BoundedString<64>>,
615                    D
616                ),
617            }
618        }
619
620        #[inline]
621        unsafe fn decode(
622            &mut self,
623            decoder: &mut fidl::encoding::Decoder<'_, D>,
624            offset: usize,
625            _depth: fidl::encoding::Depth,
626        ) -> fidl::Result<()> {
627            decoder.debug_check_bounds::<Self>(offset);
628            // Verify that padding bytes are zero.
629            fidl::decode!(
630                fidl::encoding::Optional<fidl::encoding::BoundedString<64>>,
631                D,
632                &mut self.response,
633                decoder,
634                offset + 0,
635                _depth
636            )?;
637            Ok(())
638        }
639    }
640}