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#[cfg(target_os = "fuchsia")]
92impl From<ColocatedSynchronousProxy> for zx::Handle {
93    fn from(value: ColocatedSynchronousProxy) -> Self {
94        value.into_channel().into()
95    }
96}
97
98#[cfg(target_os = "fuchsia")]
99impl From<fidl::Channel> for ColocatedSynchronousProxy {
100    fn from(value: fidl::Channel) -> Self {
101        Self::new(value)
102    }
103}
104
105#[cfg(target_os = "fuchsia")]
106impl fidl::endpoints::FromClient for ColocatedSynchronousProxy {
107    type Protocol = ColocatedMarker;
108
109    fn from_client(value: fidl::endpoints::ClientEnd<ColocatedMarker>) -> Self {
110        Self::new(value.into_channel())
111    }
112}
113
114#[derive(Debug, Clone)]
115pub struct ColocatedProxy {
116    client: fidl::client::Client<fidl::encoding::DefaultFuchsiaResourceDialect>,
117}
118
119impl fidl::endpoints::Proxy for ColocatedProxy {
120    type Protocol = ColocatedMarker;
121
122    fn from_channel(inner: ::fidl::AsyncChannel) -> Self {
123        Self::new(inner)
124    }
125
126    fn into_channel(self) -> Result<::fidl::AsyncChannel, Self> {
127        self.client.into_channel().map_err(|client| Self { client })
128    }
129
130    fn as_channel(&self) -> &::fidl::AsyncChannel {
131        self.client.as_channel()
132    }
133}
134
135impl ColocatedProxy {
136    /// Create a new Proxy for fuchsia.examples.colocated/Colocated.
137    pub fn new(channel: ::fidl::AsyncChannel) -> Self {
138        let protocol_name = <ColocatedMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME;
139        Self { client: fidl::client::Client::new(channel, protocol_name) }
140    }
141
142    /// Get a Stream of events from the remote end of the protocol.
143    ///
144    /// # Panics
145    ///
146    /// Panics if the event stream was already taken.
147    pub fn take_event_stream(&self) -> ColocatedEventStream {
148        ColocatedEventStream { event_receiver: self.client.take_event_receiver() }
149    }
150
151    /// Returns a list of VMO Koids used by the component,
152    pub fn r#get_vmos(
153        &self,
154    ) -> fidl::client::QueryResponseFut<Vec<u64>, fidl::encoding::DefaultFuchsiaResourceDialect>
155    {
156        ColocatedProxyInterface::r#get_vmos(self)
157    }
158}
159
160impl ColocatedProxyInterface for ColocatedProxy {
161    type GetVmosResponseFut =
162        fidl::client::QueryResponseFut<Vec<u64>, fidl::encoding::DefaultFuchsiaResourceDialect>;
163    fn r#get_vmos(&self) -> Self::GetVmosResponseFut {
164        fn _decode(
165            mut _buf: Result<<fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc, fidl::Error>,
166        ) -> Result<Vec<u64>, fidl::Error> {
167            let _response = fidl::client::decode_transaction_body::<
168                fidl::encoding::FlexibleType<ColocatedGetVmosResponse>,
169                fidl::encoding::DefaultFuchsiaResourceDialect,
170                0x6e0e1cca8af3632a,
171            >(_buf?)?
172            .into_result::<ColocatedMarker>("get_vmos")?;
173            Ok(_response.vmos)
174        }
175        self.client.send_query_and_decode::<fidl::encoding::EmptyPayload, Vec<u64>>(
176            (),
177            0x6e0e1cca8af3632a,
178            fidl::encoding::DynamicFlags::FLEXIBLE,
179            _decode,
180        )
181    }
182}
183
184pub struct ColocatedEventStream {
185    event_receiver: fidl::client::EventReceiver<fidl::encoding::DefaultFuchsiaResourceDialect>,
186}
187
188impl std::marker::Unpin for ColocatedEventStream {}
189
190impl futures::stream::FusedStream for ColocatedEventStream {
191    fn is_terminated(&self) -> bool {
192        self.event_receiver.is_terminated()
193    }
194}
195
196impl futures::Stream for ColocatedEventStream {
197    type Item = Result<ColocatedEvent, 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(ColocatedEvent::decode(buf))),
208            None => std::task::Poll::Ready(None),
209        }
210    }
211}
212
213#[derive(Debug)]
214pub enum ColocatedEvent {
215    #[non_exhaustive]
216    _UnknownEvent {
217        /// Ordinal of the event that was sent.
218        ordinal: u64,
219    },
220}
221
222impl ColocatedEvent {
223    /// Decodes a message buffer as a [`ColocatedEvent`].
224    fn decode(
225        mut buf: <fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc,
226    ) -> Result<ColocatedEvent, fidl::Error> {
227        let (bytes, _handles) = buf.split_mut();
228        let (tx_header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
229        debug_assert_eq!(tx_header.tx_id, 0);
230        match tx_header.ordinal {
231            _ if tx_header.dynamic_flags().contains(fidl::encoding::DynamicFlags::FLEXIBLE) => {
232                Ok(ColocatedEvent::_UnknownEvent { ordinal: tx_header.ordinal })
233            }
234            _ => Err(fidl::Error::UnknownOrdinal {
235                ordinal: tx_header.ordinal,
236                protocol_name: <ColocatedMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
237            }),
238        }
239    }
240}
241
242/// A Stream of incoming requests for fuchsia.examples.colocated/Colocated.
243pub struct ColocatedRequestStream {
244    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
245    is_terminated: bool,
246}
247
248impl std::marker::Unpin for ColocatedRequestStream {}
249
250impl futures::stream::FusedStream for ColocatedRequestStream {
251    fn is_terminated(&self) -> bool {
252        self.is_terminated
253    }
254}
255
256impl fidl::endpoints::RequestStream for ColocatedRequestStream {
257    type Protocol = ColocatedMarker;
258    type ControlHandle = ColocatedControlHandle;
259
260    fn from_channel(channel: ::fidl::AsyncChannel) -> Self {
261        Self { inner: std::sync::Arc::new(fidl::ServeInner::new(channel)), is_terminated: false }
262    }
263
264    fn control_handle(&self) -> Self::ControlHandle {
265        ColocatedControlHandle { inner: self.inner.clone() }
266    }
267
268    fn into_inner(
269        self,
270    ) -> (::std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>, bool)
271    {
272        (self.inner, self.is_terminated)
273    }
274
275    fn from_inner(
276        inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
277        is_terminated: bool,
278    ) -> Self {
279        Self { inner, is_terminated }
280    }
281}
282
283impl futures::Stream for ColocatedRequestStream {
284    type Item = Result<ColocatedRequest, fidl::Error>;
285
286    fn poll_next(
287        mut self: std::pin::Pin<&mut Self>,
288        cx: &mut std::task::Context<'_>,
289    ) -> std::task::Poll<Option<Self::Item>> {
290        let this = &mut *self;
291        if this.inner.check_shutdown(cx) {
292            this.is_terminated = true;
293            return std::task::Poll::Ready(None);
294        }
295        if this.is_terminated {
296            panic!("polled ColocatedRequestStream after completion");
297        }
298        fidl::encoding::with_tls_decode_buf::<_, fidl::encoding::DefaultFuchsiaResourceDialect>(
299            |bytes, handles| {
300                match this.inner.channel().read_etc(cx, bytes, handles) {
301                    std::task::Poll::Ready(Ok(())) => {}
302                    std::task::Poll::Pending => return std::task::Poll::Pending,
303                    std::task::Poll::Ready(Err(zx_status::Status::PEER_CLOSED)) => {
304                        this.is_terminated = true;
305                        return std::task::Poll::Ready(None);
306                    }
307                    std::task::Poll::Ready(Err(e)) => {
308                        return std::task::Poll::Ready(Some(Err(fidl::Error::ServerRequestRead(
309                            e.into(),
310                        ))))
311                    }
312                }
313
314                // A message has been received from the channel
315                let (header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
316
317                std::task::Poll::Ready(Some(match header.ordinal {
318                    0x6e0e1cca8af3632a => {
319                        header.validate_request_tx_id(fidl::MethodType::TwoWay)?;
320                        let mut req = fidl::new_empty!(
321                            fidl::encoding::EmptyPayload,
322                            fidl::encoding::DefaultFuchsiaResourceDialect
323                        );
324                        fidl::encoding::Decoder::<fidl::encoding::DefaultFuchsiaResourceDialect>::decode_into::<fidl::encoding::EmptyPayload>(&header, _body_bytes, handles, &mut req)?;
325                        let control_handle = ColocatedControlHandle { inner: this.inner.clone() };
326                        Ok(ColocatedRequest::GetVmos {
327                            responder: ColocatedGetVmosResponder {
328                                control_handle: std::mem::ManuallyDrop::new(control_handle),
329                                tx_id: header.tx_id,
330                            },
331                        })
332                    }
333                    _ if header.tx_id == 0
334                        && header
335                            .dynamic_flags()
336                            .contains(fidl::encoding::DynamicFlags::FLEXIBLE) =>
337                    {
338                        Ok(ColocatedRequest::_UnknownMethod {
339                            ordinal: header.ordinal,
340                            control_handle: ColocatedControlHandle { inner: this.inner.clone() },
341                            method_type: fidl::MethodType::OneWay,
342                        })
343                    }
344                    _ if header
345                        .dynamic_flags()
346                        .contains(fidl::encoding::DynamicFlags::FLEXIBLE) =>
347                    {
348                        this.inner.send_framework_err(
349                            fidl::encoding::FrameworkErr::UnknownMethod,
350                            header.tx_id,
351                            header.ordinal,
352                            header.dynamic_flags(),
353                            (bytes, handles),
354                        )?;
355                        Ok(ColocatedRequest::_UnknownMethod {
356                            ordinal: header.ordinal,
357                            control_handle: ColocatedControlHandle { inner: this.inner.clone() },
358                            method_type: fidl::MethodType::TwoWay,
359                        })
360                    }
361                    _ => Err(fidl::Error::UnknownOrdinal {
362                        ordinal: header.ordinal,
363                        protocol_name:
364                            <ColocatedMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
365                    }),
366                }))
367            },
368        )
369    }
370}
371
372/// A protocol for reporting one's own VMO usage.
373///
374/// This protocol is used for integration testing.
375#[derive(Debug)]
376pub enum ColocatedRequest {
377    /// Returns a list of VMO Koids used by the component,
378    GetVmos { responder: ColocatedGetVmosResponder },
379    /// An interaction was received which does not match any known method.
380    #[non_exhaustive]
381    _UnknownMethod {
382        /// Ordinal of the method that was called.
383        ordinal: u64,
384        control_handle: ColocatedControlHandle,
385        method_type: fidl::MethodType,
386    },
387}
388
389impl ColocatedRequest {
390    #[allow(irrefutable_let_patterns)]
391    pub fn into_get_vmos(self) -> Option<(ColocatedGetVmosResponder)> {
392        if let ColocatedRequest::GetVmos { responder } = self {
393            Some((responder))
394        } else {
395            None
396        }
397    }
398
399    /// Name of the method defined in FIDL
400    pub fn method_name(&self) -> &'static str {
401        match *self {
402            ColocatedRequest::GetVmos { .. } => "get_vmos",
403            ColocatedRequest::_UnknownMethod { method_type: fidl::MethodType::OneWay, .. } => {
404                "unknown one-way method"
405            }
406            ColocatedRequest::_UnknownMethod { method_type: fidl::MethodType::TwoWay, .. } => {
407                "unknown two-way method"
408            }
409        }
410    }
411}
412
413#[derive(Debug, Clone)]
414pub struct ColocatedControlHandle {
415    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
416}
417
418impl fidl::endpoints::ControlHandle for ColocatedControlHandle {
419    fn shutdown(&self) {
420        self.inner.shutdown()
421    }
422    fn shutdown_with_epitaph(&self, status: zx_status::Status) {
423        self.inner.shutdown_with_epitaph(status)
424    }
425
426    fn is_closed(&self) -> bool {
427        self.inner.channel().is_closed()
428    }
429    fn on_closed(&self) -> fidl::OnSignalsRef<'_> {
430        self.inner.channel().on_closed()
431    }
432
433    #[cfg(target_os = "fuchsia")]
434    fn signal_peer(
435        &self,
436        clear_mask: zx::Signals,
437        set_mask: zx::Signals,
438    ) -> Result<(), zx_status::Status> {
439        use fidl::Peered;
440        self.inner.channel().signal_peer(clear_mask, set_mask)
441    }
442}
443
444impl ColocatedControlHandle {}
445
446#[must_use = "FIDL methods require a response to be sent"]
447#[derive(Debug)]
448pub struct ColocatedGetVmosResponder {
449    control_handle: std::mem::ManuallyDrop<ColocatedControlHandle>,
450    tx_id: u32,
451}
452
453/// Set the the channel to be shutdown (see [`ColocatedControlHandle::shutdown`])
454/// if the responder is dropped without sending a response, so that the client
455/// doesn't hang. To prevent this behavior, call `drop_without_shutdown`.
456impl std::ops::Drop for ColocatedGetVmosResponder {
457    fn drop(&mut self) {
458        self.control_handle.shutdown();
459        // Safety: drops once, never accessed again
460        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
461    }
462}
463
464impl fidl::endpoints::Responder for ColocatedGetVmosResponder {
465    type ControlHandle = ColocatedControlHandle;
466
467    fn control_handle(&self) -> &ColocatedControlHandle {
468        &self.control_handle
469    }
470
471    fn drop_without_shutdown(mut self) {
472        // Safety: drops once, never accessed again due to mem::forget
473        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
474        // Prevent Drop from running (which would shut down the channel)
475        std::mem::forget(self);
476    }
477}
478
479impl ColocatedGetVmosResponder {
480    /// Sends a response to the FIDL transaction.
481    ///
482    /// Sets the channel to shutdown if an error occurs.
483    pub fn send(self, mut vmos: &[u64]) -> Result<(), fidl::Error> {
484        let _result = self.send_raw(vmos);
485        if _result.is_err() {
486            self.control_handle.shutdown();
487        }
488        self.drop_without_shutdown();
489        _result
490    }
491
492    /// Similar to "send" but does not shutdown the channel if an error occurs.
493    pub fn send_no_shutdown_on_err(self, mut vmos: &[u64]) -> Result<(), fidl::Error> {
494        let _result = self.send_raw(vmos);
495        self.drop_without_shutdown();
496        _result
497    }
498
499    fn send_raw(&self, mut vmos: &[u64]) -> Result<(), fidl::Error> {
500        self.control_handle.inner.send::<fidl::encoding::FlexibleType<ColocatedGetVmosResponse>>(
501            fidl::encoding::Flexible::new((vmos,)),
502            self.tx_id,
503            0x6e0e1cca8af3632a,
504            fidl::encoding::DynamicFlags::FLEXIBLE,
505        )
506    }
507}
508
509mod internal {
510    use super::*;
511}