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