fidl_fuchsia_examples/
fidl_fuchsia_examples.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_examples__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 = "fuchsia.examples.Echo";
24}
25impl fidl::endpoints::DiscoverableProtocolMarker for EchoMarker {}
26
27pub trait EchoProxyInterface: Send + Sync {
28    type EchoStringResponseFut: std::future::Future<Output = Result<String, fidl::Error>> + Send;
29    fn r#echo_string(&self, value: &str) -> Self::EchoStringResponseFut;
30}
31#[derive(Debug)]
32#[cfg(target_os = "fuchsia")]
33pub struct EchoSynchronousProxy {
34    client: fidl::client::sync::Client,
35}
36
37#[cfg(target_os = "fuchsia")]
38impl fidl::endpoints::SynchronousProxy for EchoSynchronousProxy {
39    type Proxy = EchoProxy;
40    type Protocol = EchoMarker;
41
42    fn from_channel(inner: fidl::Channel) -> Self {
43        Self::new(inner)
44    }
45
46    fn into_channel(self) -> fidl::Channel {
47        self.client.into_channel()
48    }
49
50    fn as_channel(&self) -> &fidl::Channel {
51        self.client.as_channel()
52    }
53}
54
55#[cfg(target_os = "fuchsia")]
56impl EchoSynchronousProxy {
57    pub fn new(channel: fidl::Channel) -> Self {
58        let protocol_name = <EchoMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME;
59        Self { client: fidl::client::sync::Client::new(channel, protocol_name) }
60    }
61
62    pub fn into_channel(self) -> fidl::Channel {
63        self.client.into_channel()
64    }
65
66    /// Waits until an event arrives and returns it. It is safe for other
67    /// threads to make concurrent requests while waiting for an event.
68    pub fn wait_for_event(&self, deadline: zx::MonotonicInstant) -> Result<EchoEvent, fidl::Error> {
69        EchoEvent::decode(self.client.wait_for_event(deadline)?)
70    }
71
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            0x75b8274e52d9a616,
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.examples/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    pub fn r#echo_string(
148        &self,
149        mut value: &str,
150    ) -> fidl::client::QueryResponseFut<String, fidl::encoding::DefaultFuchsiaResourceDialect> {
151        EchoProxyInterface::r#echo_string(self, value)
152    }
153}
154
155impl EchoProxyInterface for EchoProxy {
156    type EchoStringResponseFut =
157        fidl::client::QueryResponseFut<String, fidl::encoding::DefaultFuchsiaResourceDialect>;
158    fn r#echo_string(&self, mut value: &str) -> Self::EchoStringResponseFut {
159        fn _decode(
160            mut _buf: Result<<fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc, fidl::Error>,
161        ) -> Result<String, fidl::Error> {
162            let _response = fidl::client::decode_transaction_body::<
163                EchoEchoStringResponse,
164                fidl::encoding::DefaultFuchsiaResourceDialect,
165                0x75b8274e52d9a616,
166            >(_buf?)?;
167            Ok(_response.response)
168        }
169        self.client.send_query_and_decode::<EchoEchoStringRequest, String>(
170            (value,),
171            0x75b8274e52d9a616,
172            fidl::encoding::DynamicFlags::empty(),
173            _decode,
174        )
175    }
176}
177
178pub struct EchoEventStream {
179    event_receiver: fidl::client::EventReceiver<fidl::encoding::DefaultFuchsiaResourceDialect>,
180}
181
182impl std::marker::Unpin for EchoEventStream {}
183
184impl futures::stream::FusedStream for EchoEventStream {
185    fn is_terminated(&self) -> bool {
186        self.event_receiver.is_terminated()
187    }
188}
189
190impl futures::Stream for EchoEventStream {
191    type Item = Result<EchoEvent, fidl::Error>;
192
193    fn poll_next(
194        mut self: std::pin::Pin<&mut Self>,
195        cx: &mut std::task::Context<'_>,
196    ) -> std::task::Poll<Option<Self::Item>> {
197        match futures::ready!(futures::stream::StreamExt::poll_next_unpin(
198            &mut self.event_receiver,
199            cx
200        )?) {
201            Some(buf) => std::task::Poll::Ready(Some(EchoEvent::decode(buf))),
202            None => std::task::Poll::Ready(None),
203        }
204    }
205}
206
207#[derive(Debug)]
208pub enum EchoEvent {}
209
210impl EchoEvent {
211    /// Decodes a message buffer as a [`EchoEvent`].
212    fn decode(
213        mut buf: <fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc,
214    ) -> Result<EchoEvent, fidl::Error> {
215        let (bytes, _handles) = buf.split_mut();
216        let (tx_header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
217        debug_assert_eq!(tx_header.tx_id, 0);
218        match tx_header.ordinal {
219            _ => Err(fidl::Error::UnknownOrdinal {
220                ordinal: tx_header.ordinal,
221                protocol_name: <EchoMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
222            }),
223        }
224    }
225}
226
227/// A Stream of incoming requests for fuchsia.examples/Echo.
228pub struct EchoRequestStream {
229    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
230    is_terminated: bool,
231}
232
233impl std::marker::Unpin for EchoRequestStream {}
234
235impl futures::stream::FusedStream for EchoRequestStream {
236    fn is_terminated(&self) -> bool {
237        self.is_terminated
238    }
239}
240
241impl fidl::endpoints::RequestStream for EchoRequestStream {
242    type Protocol = EchoMarker;
243    type ControlHandle = EchoControlHandle;
244
245    fn from_channel(channel: ::fidl::AsyncChannel) -> Self {
246        Self { inner: std::sync::Arc::new(fidl::ServeInner::new(channel)), is_terminated: false }
247    }
248
249    fn control_handle(&self) -> Self::ControlHandle {
250        EchoControlHandle { inner: self.inner.clone() }
251    }
252
253    fn into_inner(
254        self,
255    ) -> (::std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>, bool)
256    {
257        (self.inner, self.is_terminated)
258    }
259
260    fn from_inner(
261        inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
262        is_terminated: bool,
263    ) -> Self {
264        Self { inner, is_terminated }
265    }
266}
267
268impl futures::Stream for EchoRequestStream {
269    type Item = Result<EchoRequest, fidl::Error>;
270
271    fn poll_next(
272        mut self: std::pin::Pin<&mut Self>,
273        cx: &mut std::task::Context<'_>,
274    ) -> std::task::Poll<Option<Self::Item>> {
275        let this = &mut *self;
276        if this.inner.check_shutdown(cx) {
277            this.is_terminated = true;
278            return std::task::Poll::Ready(None);
279        }
280        if this.is_terminated {
281            panic!("polled EchoRequestStream after completion");
282        }
283        fidl::encoding::with_tls_decode_buf::<_, fidl::encoding::DefaultFuchsiaResourceDialect>(
284            |bytes, handles| {
285                match this.inner.channel().read_etc(cx, bytes, handles) {
286                    std::task::Poll::Ready(Ok(())) => {}
287                    std::task::Poll::Pending => return std::task::Poll::Pending,
288                    std::task::Poll::Ready(Err(zx_status::Status::PEER_CLOSED)) => {
289                        this.is_terminated = true;
290                        return std::task::Poll::Ready(None);
291                    }
292                    std::task::Poll::Ready(Err(e)) => {
293                        return std::task::Poll::Ready(Some(Err(fidl::Error::ServerRequestRead(
294                            e.into(),
295                        ))))
296                    }
297                }
298
299                // A message has been received from the channel
300                let (header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
301
302                std::task::Poll::Ready(Some(match header.ordinal {
303                    0x75b8274e52d9a616 => {
304                        header.validate_request_tx_id(fidl::MethodType::TwoWay)?;
305                        let mut req = fidl::new_empty!(
306                            EchoEchoStringRequest,
307                            fidl::encoding::DefaultFuchsiaResourceDialect
308                        );
309                        fidl::encoding::Decoder::<fidl::encoding::DefaultFuchsiaResourceDialect>::decode_into::<EchoEchoStringRequest>(&header, _body_bytes, handles, &mut req)?;
310                        let control_handle = EchoControlHandle { inner: this.inner.clone() };
311                        Ok(EchoRequest::EchoString {
312                            value: req.value,
313
314                            responder: EchoEchoStringResponder {
315                                control_handle: std::mem::ManuallyDrop::new(control_handle),
316                                tx_id: header.tx_id,
317                            },
318                        })
319                    }
320                    _ => Err(fidl::Error::UnknownOrdinal {
321                        ordinal: header.ordinal,
322                        protocol_name: <EchoMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
323                    }),
324                }))
325            },
326        )
327    }
328}
329
330#[derive(Debug)]
331pub enum EchoRequest {
332    EchoString { value: String, responder: EchoEchoStringResponder },
333}
334
335impl EchoRequest {
336    #[allow(irrefutable_let_patterns)]
337    pub fn into_echo_string(self) -> Option<(String, EchoEchoStringResponder)> {
338        if let EchoRequest::EchoString { value, responder } = self {
339            Some((value, responder))
340        } else {
341            None
342        }
343    }
344
345    /// Name of the method defined in FIDL
346    pub fn method_name(&self) -> &'static str {
347        match *self {
348            EchoRequest::EchoString { .. } => "echo_string",
349        }
350    }
351}
352
353#[derive(Debug, Clone)]
354pub struct EchoControlHandle {
355    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
356}
357
358impl fidl::endpoints::ControlHandle for EchoControlHandle {
359    fn shutdown(&self) {
360        self.inner.shutdown()
361    }
362    fn shutdown_with_epitaph(&self, status: zx_status::Status) {
363        self.inner.shutdown_with_epitaph(status)
364    }
365
366    fn is_closed(&self) -> bool {
367        self.inner.channel().is_closed()
368    }
369    fn on_closed(&self) -> fidl::OnSignalsRef<'_> {
370        self.inner.channel().on_closed()
371    }
372
373    #[cfg(target_os = "fuchsia")]
374    fn signal_peer(
375        &self,
376        clear_mask: zx::Signals,
377        set_mask: zx::Signals,
378    ) -> Result<(), zx_status::Status> {
379        use fidl::Peered;
380        self.inner.channel().signal_peer(clear_mask, set_mask)
381    }
382}
383
384impl EchoControlHandle {}
385
386#[must_use = "FIDL methods require a response to be sent"]
387#[derive(Debug)]
388pub struct EchoEchoStringResponder {
389    control_handle: std::mem::ManuallyDrop<EchoControlHandle>,
390    tx_id: u32,
391}
392
393/// Set the the channel to be shutdown (see [`EchoControlHandle::shutdown`])
394/// if the responder is dropped without sending a response, so that the client
395/// doesn't hang. To prevent this behavior, call `drop_without_shutdown`.
396impl std::ops::Drop for EchoEchoStringResponder {
397    fn drop(&mut self) {
398        self.control_handle.shutdown();
399        // Safety: drops once, never accessed again
400        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
401    }
402}
403
404impl fidl::endpoints::Responder for EchoEchoStringResponder {
405    type ControlHandle = EchoControlHandle;
406
407    fn control_handle(&self) -> &EchoControlHandle {
408        &self.control_handle
409    }
410
411    fn drop_without_shutdown(mut self) {
412        // Safety: drops once, never accessed again due to mem::forget
413        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
414        // Prevent Drop from running (which would shut down the channel)
415        std::mem::forget(self);
416    }
417}
418
419impl EchoEchoStringResponder {
420    /// Sends a response to the FIDL transaction.
421    ///
422    /// Sets the channel to shutdown if an error occurs.
423    pub fn send(self, mut response: &str) -> Result<(), fidl::Error> {
424        let _result = self.send_raw(response);
425        if _result.is_err() {
426            self.control_handle.shutdown();
427        }
428        self.drop_without_shutdown();
429        _result
430    }
431
432    /// Similar to "send" but does not shutdown the channel if an error occurs.
433    pub fn send_no_shutdown_on_err(self, mut response: &str) -> Result<(), fidl::Error> {
434        let _result = self.send_raw(response);
435        self.drop_without_shutdown();
436        _result
437    }
438
439    fn send_raw(&self, mut response: &str) -> Result<(), fidl::Error> {
440        self.control_handle.inner.send::<EchoEchoStringResponse>(
441            (response,),
442            self.tx_id,
443            0x75b8274e52d9a616,
444            fidl::encoding::DynamicFlags::empty(),
445        )
446    }
447}
448
449#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
450pub struct EchoServiceMarker;
451
452#[cfg(target_os = "fuchsia")]
453impl fidl::endpoints::ServiceMarker for EchoServiceMarker {
454    type Proxy = EchoServiceProxy;
455    type Request = EchoServiceRequest;
456    const SERVICE_NAME: &'static str = "fuchsia.examples.EchoService";
457}
458
459/// A request for one of the member protocols of EchoService.
460///
461#[cfg(target_os = "fuchsia")]
462pub enum EchoServiceRequest {
463    RegularEcho(EchoRequestStream),
464    ReversedEcho(EchoRequestStream),
465}
466
467#[cfg(target_os = "fuchsia")]
468impl fidl::endpoints::ServiceRequest for EchoServiceRequest {
469    type Service = EchoServiceMarker;
470
471    fn dispatch(name: &str, _channel: fidl::AsyncChannel) -> Self {
472        match name {
473            "regular_echo" => Self::RegularEcho(
474                <EchoRequestStream as fidl::endpoints::RequestStream>::from_channel(_channel),
475            ),
476            "reversed_echo" => Self::ReversedEcho(
477                <EchoRequestStream as fidl::endpoints::RequestStream>::from_channel(_channel),
478            ),
479            _ => panic!("no such member protocol name for service EchoService"),
480        }
481    }
482
483    fn member_names() -> &'static [&'static str] {
484        &["regular_echo", "reversed_echo"]
485    }
486}
487#[cfg(target_os = "fuchsia")]
488pub struct EchoServiceProxy(#[allow(dead_code)] Box<dyn fidl::endpoints::MemberOpener>);
489
490#[cfg(target_os = "fuchsia")]
491impl fidl::endpoints::ServiceProxy for EchoServiceProxy {
492    type Service = EchoServiceMarker;
493
494    fn from_member_opener(opener: Box<dyn fidl::endpoints::MemberOpener>) -> Self {
495        Self(opener)
496    }
497}
498
499#[cfg(target_os = "fuchsia")]
500impl EchoServiceProxy {
501    pub fn connect_to_regular_echo(&self) -> Result<EchoProxy, fidl::Error> {
502        let (proxy, server_end) = fidl::endpoints::create_proxy::<EchoMarker>();
503        self.connect_channel_to_regular_echo(server_end)?;
504        Ok(proxy)
505    }
506
507    /// Like `connect_to_regular_echo`, but returns a sync proxy.
508    /// See [`Self::connect_to_regular_echo`] for more details.
509    pub fn connect_to_regular_echo_sync(&self) -> Result<EchoSynchronousProxy, fidl::Error> {
510        let (proxy, server_end) = fidl::endpoints::create_sync_proxy::<EchoMarker>();
511        self.connect_channel_to_regular_echo(server_end)?;
512        Ok(proxy)
513    }
514
515    /// Like `connect_to_regular_echo`, but accepts a server end.
516    /// See [`Self::connect_to_regular_echo`] for more details.
517    pub fn connect_channel_to_regular_echo(
518        &self,
519        server_end: fidl::endpoints::ServerEnd<EchoMarker>,
520    ) -> Result<(), fidl::Error> {
521        self.0.open_member("regular_echo", server_end.into_channel())
522    }
523    pub fn connect_to_reversed_echo(&self) -> Result<EchoProxy, fidl::Error> {
524        let (proxy, server_end) = fidl::endpoints::create_proxy::<EchoMarker>();
525        self.connect_channel_to_reversed_echo(server_end)?;
526        Ok(proxy)
527    }
528
529    /// Like `connect_to_reversed_echo`, but returns a sync proxy.
530    /// See [`Self::connect_to_reversed_echo`] for more details.
531    pub fn connect_to_reversed_echo_sync(&self) -> Result<EchoSynchronousProxy, fidl::Error> {
532        let (proxy, server_end) = fidl::endpoints::create_sync_proxy::<EchoMarker>();
533        self.connect_channel_to_reversed_echo(server_end)?;
534        Ok(proxy)
535    }
536
537    /// Like `connect_to_reversed_echo`, but accepts a server end.
538    /// See [`Self::connect_to_reversed_echo`] for more details.
539    pub fn connect_channel_to_reversed_echo(
540        &self,
541        server_end: fidl::endpoints::ServerEnd<EchoMarker>,
542    ) -> Result<(), fidl::Error> {
543        self.0.open_member("reversed_echo", server_end.into_channel())
544    }
545
546    pub fn instance_name(&self) -> &str {
547        self.0.instance_name()
548    }
549}
550
551mod internal {
552    use super::*;
553}