fidl_fuchsia_examples_colocated/
fidl_fuchsia_examples_colocated.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_colocated_common::*;
11use futures::future::{self, MaybeDone, TryFutureExt};
12use zx_status;
13
14#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
15pub struct ColocatedMarker;
16
17impl fidl::endpoints::ProtocolMarker for ColocatedMarker {
18    type Proxy = ColocatedProxy;
19    type RequestStream = ColocatedRequestStream;
20    #[cfg(target_os = "fuchsia")]
21    type SynchronousProxy = ColocatedSynchronousProxy;
22
23    const DEBUG_NAME: &'static str = "fuchsia.examples.colocated.Colocated";
24}
25impl fidl::endpoints::DiscoverableProtocolMarker for ColocatedMarker {}
26
27pub trait ColocatedProxyInterface: Send + Sync {
28    type GetVmosResponseFut: std::future::Future<Output = Result<Vec<u64>, fidl::Error>> + Send;
29    fn r#get_vmos(&self) -> Self::GetVmosResponseFut;
30}
31#[derive(Debug)]
32#[cfg(target_os = "fuchsia")]
33pub struct ColocatedSynchronousProxy {
34    client: fidl::client::sync::Client,
35}
36
37#[cfg(target_os = "fuchsia")]
38impl fidl::endpoints::SynchronousProxy for ColocatedSynchronousProxy {
39    type Proxy = ColocatedProxy;
40    type Protocol = ColocatedMarker;
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 ColocatedSynchronousProxy {
57    pub fn new(channel: fidl::Channel) -> Self {
58        let protocol_name = <ColocatedMarker 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(
69        &self,
70        deadline: zx::MonotonicInstant,
71    ) -> Result<ColocatedEvent, fidl::Error> {
72        ColocatedEvent::decode(self.client.wait_for_event(deadline)?)
73    }
74
75    /// Returns a list of VMO Koids used by the component,
76    pub fn r#get_vmos(&self, ___deadline: zx::MonotonicInstant) -> Result<Vec<u64>, fidl::Error> {
77        let _response = self.client.send_query::<
78            fidl::encoding::EmptyPayload,
79            fidl::encoding::FlexibleType<ColocatedGetVmosResponse>,
80        >(
81            (),
82            0x6e0e1cca8af3632a,
83            fidl::encoding::DynamicFlags::FLEXIBLE,
84            ___deadline,
85        )?
86        .into_result::<ColocatedMarker>("get_vmos")?;
87        Ok(_response.vmos)
88    }
89}
90
91#[derive(Debug, Clone)]
92pub struct ColocatedProxy {
93    client: fidl::client::Client<fidl::encoding::DefaultFuchsiaResourceDialect>,
94}
95
96impl fidl::endpoints::Proxy for ColocatedProxy {
97    type Protocol = ColocatedMarker;
98
99    fn from_channel(inner: ::fidl::AsyncChannel) -> Self {
100        Self::new(inner)
101    }
102
103    fn into_channel(self) -> Result<::fidl::AsyncChannel, Self> {
104        self.client.into_channel().map_err(|client| Self { client })
105    }
106
107    fn as_channel(&self) -> &::fidl::AsyncChannel {
108        self.client.as_channel()
109    }
110}
111
112impl ColocatedProxy {
113    /// Create a new Proxy for fuchsia.examples.colocated/Colocated.
114    pub fn new(channel: ::fidl::AsyncChannel) -> Self {
115        let protocol_name = <ColocatedMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME;
116        Self { client: fidl::client::Client::new(channel, protocol_name) }
117    }
118
119    /// Get a Stream of events from the remote end of the protocol.
120    ///
121    /// # Panics
122    ///
123    /// Panics if the event stream was already taken.
124    pub fn take_event_stream(&self) -> ColocatedEventStream {
125        ColocatedEventStream { event_receiver: self.client.take_event_receiver() }
126    }
127
128    /// Returns a list of VMO Koids used by the component,
129    pub fn r#get_vmos(
130        &self,
131    ) -> fidl::client::QueryResponseFut<Vec<u64>, fidl::encoding::DefaultFuchsiaResourceDialect>
132    {
133        ColocatedProxyInterface::r#get_vmos(self)
134    }
135}
136
137impl ColocatedProxyInterface for ColocatedProxy {
138    type GetVmosResponseFut =
139        fidl::client::QueryResponseFut<Vec<u64>, fidl::encoding::DefaultFuchsiaResourceDialect>;
140    fn r#get_vmos(&self) -> Self::GetVmosResponseFut {
141        fn _decode(
142            mut _buf: Result<<fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc, fidl::Error>,
143        ) -> Result<Vec<u64>, fidl::Error> {
144            let _response = fidl::client::decode_transaction_body::<
145                fidl::encoding::FlexibleType<ColocatedGetVmosResponse>,
146                fidl::encoding::DefaultFuchsiaResourceDialect,
147                0x6e0e1cca8af3632a,
148            >(_buf?)?
149            .into_result::<ColocatedMarker>("get_vmos")?;
150            Ok(_response.vmos)
151        }
152        self.client.send_query_and_decode::<fidl::encoding::EmptyPayload, Vec<u64>>(
153            (),
154            0x6e0e1cca8af3632a,
155            fidl::encoding::DynamicFlags::FLEXIBLE,
156            _decode,
157        )
158    }
159}
160
161pub struct ColocatedEventStream {
162    event_receiver: fidl::client::EventReceiver<fidl::encoding::DefaultFuchsiaResourceDialect>,
163}
164
165impl std::marker::Unpin for ColocatedEventStream {}
166
167impl futures::stream::FusedStream for ColocatedEventStream {
168    fn is_terminated(&self) -> bool {
169        self.event_receiver.is_terminated()
170    }
171}
172
173impl futures::Stream for ColocatedEventStream {
174    type Item = Result<ColocatedEvent, fidl::Error>;
175
176    fn poll_next(
177        mut self: std::pin::Pin<&mut Self>,
178        cx: &mut std::task::Context<'_>,
179    ) -> std::task::Poll<Option<Self::Item>> {
180        match futures::ready!(futures::stream::StreamExt::poll_next_unpin(
181            &mut self.event_receiver,
182            cx
183        )?) {
184            Some(buf) => std::task::Poll::Ready(Some(ColocatedEvent::decode(buf))),
185            None => std::task::Poll::Ready(None),
186        }
187    }
188}
189
190#[derive(Debug)]
191pub enum ColocatedEvent {
192    #[non_exhaustive]
193    _UnknownEvent {
194        /// Ordinal of the event that was sent.
195        ordinal: u64,
196    },
197}
198
199impl ColocatedEvent {
200    /// Decodes a message buffer as a [`ColocatedEvent`].
201    fn decode(
202        mut buf: <fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc,
203    ) -> Result<ColocatedEvent, fidl::Error> {
204        let (bytes, _handles) = buf.split_mut();
205        let (tx_header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
206        debug_assert_eq!(tx_header.tx_id, 0);
207        match tx_header.ordinal {
208            _ if tx_header.dynamic_flags().contains(fidl::encoding::DynamicFlags::FLEXIBLE) => {
209                Ok(ColocatedEvent::_UnknownEvent { ordinal: tx_header.ordinal })
210            }
211            _ => Err(fidl::Error::UnknownOrdinal {
212                ordinal: tx_header.ordinal,
213                protocol_name: <ColocatedMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
214            }),
215        }
216    }
217}
218
219/// A Stream of incoming requests for fuchsia.examples.colocated/Colocated.
220pub struct ColocatedRequestStream {
221    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
222    is_terminated: bool,
223}
224
225impl std::marker::Unpin for ColocatedRequestStream {}
226
227impl futures::stream::FusedStream for ColocatedRequestStream {
228    fn is_terminated(&self) -> bool {
229        self.is_terminated
230    }
231}
232
233impl fidl::endpoints::RequestStream for ColocatedRequestStream {
234    type Protocol = ColocatedMarker;
235    type ControlHandle = ColocatedControlHandle;
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        ColocatedControlHandle { 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 ColocatedRequestStream {
261    type Item = Result<ColocatedRequest, 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 ColocatedRequestStream 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                    0x6e0e1cca8af3632a => {
296                        header.validate_request_tx_id(fidl::MethodType::TwoWay)?;
297                        let mut req = fidl::new_empty!(
298                            fidl::encoding::EmptyPayload,
299                            fidl::encoding::DefaultFuchsiaResourceDialect
300                        );
301                        fidl::encoding::Decoder::<fidl::encoding::DefaultFuchsiaResourceDialect>::decode_into::<fidl::encoding::EmptyPayload>(&header, _body_bytes, handles, &mut req)?;
302                        let control_handle = ColocatedControlHandle { inner: this.inner.clone() };
303                        Ok(ColocatedRequest::GetVmos {
304                            responder: ColocatedGetVmosResponder {
305                                control_handle: std::mem::ManuallyDrop::new(control_handle),
306                                tx_id: header.tx_id,
307                            },
308                        })
309                    }
310                    _ if header.tx_id == 0
311                        && header
312                            .dynamic_flags()
313                            .contains(fidl::encoding::DynamicFlags::FLEXIBLE) =>
314                    {
315                        Ok(ColocatedRequest::_UnknownMethod {
316                            ordinal: header.ordinal,
317                            control_handle: ColocatedControlHandle { inner: this.inner.clone() },
318                            method_type: fidl::MethodType::OneWay,
319                        })
320                    }
321                    _ if header
322                        .dynamic_flags()
323                        .contains(fidl::encoding::DynamicFlags::FLEXIBLE) =>
324                    {
325                        this.inner.send_framework_err(
326                            fidl::encoding::FrameworkErr::UnknownMethod,
327                            header.tx_id,
328                            header.ordinal,
329                            header.dynamic_flags(),
330                            (bytes, handles),
331                        )?;
332                        Ok(ColocatedRequest::_UnknownMethod {
333                            ordinal: header.ordinal,
334                            control_handle: ColocatedControlHandle { inner: this.inner.clone() },
335                            method_type: fidl::MethodType::TwoWay,
336                        })
337                    }
338                    _ => Err(fidl::Error::UnknownOrdinal {
339                        ordinal: header.ordinal,
340                        protocol_name:
341                            <ColocatedMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
342                    }),
343                }))
344            },
345        )
346    }
347}
348
349/// A protocol for reporting one's own VMO usage.
350///
351/// This protocol is used for integration testing.
352#[derive(Debug)]
353pub enum ColocatedRequest {
354    /// Returns a list of VMO Koids used by the component,
355    GetVmos { responder: ColocatedGetVmosResponder },
356    /// An interaction was received which does not match any known method.
357    #[non_exhaustive]
358    _UnknownMethod {
359        /// Ordinal of the method that was called.
360        ordinal: u64,
361        control_handle: ColocatedControlHandle,
362        method_type: fidl::MethodType,
363    },
364}
365
366impl ColocatedRequest {
367    #[allow(irrefutable_let_patterns)]
368    pub fn into_get_vmos(self) -> Option<(ColocatedGetVmosResponder)> {
369        if let ColocatedRequest::GetVmos { responder } = self {
370            Some((responder))
371        } else {
372            None
373        }
374    }
375
376    /// Name of the method defined in FIDL
377    pub fn method_name(&self) -> &'static str {
378        match *self {
379            ColocatedRequest::GetVmos { .. } => "get_vmos",
380            ColocatedRequest::_UnknownMethod { method_type: fidl::MethodType::OneWay, .. } => {
381                "unknown one-way method"
382            }
383            ColocatedRequest::_UnknownMethod { method_type: fidl::MethodType::TwoWay, .. } => {
384                "unknown two-way method"
385            }
386        }
387    }
388}
389
390#[derive(Debug, Clone)]
391pub struct ColocatedControlHandle {
392    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
393}
394
395impl fidl::endpoints::ControlHandle for ColocatedControlHandle {
396    fn shutdown(&self) {
397        self.inner.shutdown()
398    }
399    fn shutdown_with_epitaph(&self, status: zx_status::Status) {
400        self.inner.shutdown_with_epitaph(status)
401    }
402
403    fn is_closed(&self) -> bool {
404        self.inner.channel().is_closed()
405    }
406    fn on_closed(&self) -> fidl::OnSignalsRef<'_> {
407        self.inner.channel().on_closed()
408    }
409
410    #[cfg(target_os = "fuchsia")]
411    fn signal_peer(
412        &self,
413        clear_mask: zx::Signals,
414        set_mask: zx::Signals,
415    ) -> Result<(), zx_status::Status> {
416        use fidl::Peered;
417        self.inner.channel().signal_peer(clear_mask, set_mask)
418    }
419}
420
421impl ColocatedControlHandle {}
422
423#[must_use = "FIDL methods require a response to be sent"]
424#[derive(Debug)]
425pub struct ColocatedGetVmosResponder {
426    control_handle: std::mem::ManuallyDrop<ColocatedControlHandle>,
427    tx_id: u32,
428}
429
430/// Set the the channel to be shutdown (see [`ColocatedControlHandle::shutdown`])
431/// if the responder is dropped without sending a response, so that the client
432/// doesn't hang. To prevent this behavior, call `drop_without_shutdown`.
433impl std::ops::Drop for ColocatedGetVmosResponder {
434    fn drop(&mut self) {
435        self.control_handle.shutdown();
436        // Safety: drops once, never accessed again
437        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
438    }
439}
440
441impl fidl::endpoints::Responder for ColocatedGetVmosResponder {
442    type ControlHandle = ColocatedControlHandle;
443
444    fn control_handle(&self) -> &ColocatedControlHandle {
445        &self.control_handle
446    }
447
448    fn drop_without_shutdown(mut self) {
449        // Safety: drops once, never accessed again due to mem::forget
450        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
451        // Prevent Drop from running (which would shut down the channel)
452        std::mem::forget(self);
453    }
454}
455
456impl ColocatedGetVmosResponder {
457    /// Sends a response to the FIDL transaction.
458    ///
459    /// Sets the channel to shutdown if an error occurs.
460    pub fn send(self, mut vmos: &[u64]) -> Result<(), fidl::Error> {
461        let _result = self.send_raw(vmos);
462        if _result.is_err() {
463            self.control_handle.shutdown();
464        }
465        self.drop_without_shutdown();
466        _result
467    }
468
469    /// Similar to "send" but does not shutdown the channel if an error occurs.
470    pub fn send_no_shutdown_on_err(self, mut vmos: &[u64]) -> Result<(), fidl::Error> {
471        let _result = self.send_raw(vmos);
472        self.drop_without_shutdown();
473        _result
474    }
475
476    fn send_raw(&self, mut vmos: &[u64]) -> Result<(), fidl::Error> {
477        self.control_handle.inner.send::<fidl::encoding::FlexibleType<ColocatedGetVmosResponse>>(
478            fidl::encoding::Flexible::new((vmos,)),
479            self.tx_id,
480            0x6e0e1cca8af3632a,
481            fidl::encoding::DynamicFlags::FLEXIBLE,
482        )
483    }
484}
485
486mod internal {
487    use super::*;
488}