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 _};
10use futures::future::{self, MaybeDone, TryFutureExt};
11use zx_status;
12
13#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
14pub struct ColocatedGetVmosResponse {
15    pub vmos: Vec<u64>,
16}
17
18impl fidl::Persistable for ColocatedGetVmosResponse {}
19
20#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
21pub struct ColocatedMarker;
22
23impl fidl::endpoints::ProtocolMarker for ColocatedMarker {
24    type Proxy = ColocatedProxy;
25    type RequestStream = ColocatedRequestStream;
26    #[cfg(target_os = "fuchsia")]
27    type SynchronousProxy = ColocatedSynchronousProxy;
28
29    const DEBUG_NAME: &'static str = "fuchsia.examples.colocated.Colocated";
30}
31impl fidl::endpoints::DiscoverableProtocolMarker for ColocatedMarker {}
32
33pub trait ColocatedProxyInterface: Send + Sync {
34    type GetVmosResponseFut: std::future::Future<Output = Result<Vec<u64>, fidl::Error>> + Send;
35    fn r#get_vmos(&self) -> Self::GetVmosResponseFut;
36}
37#[derive(Debug)]
38#[cfg(target_os = "fuchsia")]
39pub struct ColocatedSynchronousProxy {
40    client: fidl::client::sync::Client,
41}
42
43#[cfg(target_os = "fuchsia")]
44impl fidl::endpoints::SynchronousProxy for ColocatedSynchronousProxy {
45    type Proxy = ColocatedProxy;
46    type Protocol = ColocatedMarker;
47
48    fn from_channel(inner: fidl::Channel) -> Self {
49        Self::new(inner)
50    }
51
52    fn into_channel(self) -> fidl::Channel {
53        self.client.into_channel()
54    }
55
56    fn as_channel(&self) -> &fidl::Channel {
57        self.client.as_channel()
58    }
59}
60
61#[cfg(target_os = "fuchsia")]
62impl ColocatedSynchronousProxy {
63    pub fn new(channel: fidl::Channel) -> Self {
64        let protocol_name = <ColocatedMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME;
65        Self { client: fidl::client::sync::Client::new(channel, protocol_name) }
66    }
67
68    pub fn into_channel(self) -> fidl::Channel {
69        self.client.into_channel()
70    }
71
72    /// Waits until an event arrives and returns it. It is safe for other
73    /// threads to make concurrent requests while waiting for an event.
74    pub fn wait_for_event(
75        &self,
76        deadline: zx::MonotonicInstant,
77    ) -> Result<ColocatedEvent, fidl::Error> {
78        ColocatedEvent::decode(self.client.wait_for_event(deadline)?)
79    }
80
81    /// Returns a list of VMO Koids used by the component,
82    pub fn r#get_vmos(&self, ___deadline: zx::MonotonicInstant) -> Result<Vec<u64>, fidl::Error> {
83        let _response = self.client.send_query::<
84            fidl::encoding::EmptyPayload,
85            fidl::encoding::FlexibleType<ColocatedGetVmosResponse>,
86        >(
87            (),
88            0x6e0e1cca8af3632a,
89            fidl::encoding::DynamicFlags::FLEXIBLE,
90            ___deadline,
91        )?
92        .into_result::<ColocatedMarker>("get_vmos")?;
93        Ok(_response.vmos)
94    }
95}
96
97#[derive(Debug, Clone)]
98pub struct ColocatedProxy {
99    client: fidl::client::Client<fidl::encoding::DefaultFuchsiaResourceDialect>,
100}
101
102impl fidl::endpoints::Proxy for ColocatedProxy {
103    type Protocol = ColocatedMarker;
104
105    fn from_channel(inner: ::fidl::AsyncChannel) -> Self {
106        Self::new(inner)
107    }
108
109    fn into_channel(self) -> Result<::fidl::AsyncChannel, Self> {
110        self.client.into_channel().map_err(|client| Self { client })
111    }
112
113    fn as_channel(&self) -> &::fidl::AsyncChannel {
114        self.client.as_channel()
115    }
116}
117
118impl ColocatedProxy {
119    /// Create a new Proxy for fuchsia.examples.colocated/Colocated.
120    pub fn new(channel: ::fidl::AsyncChannel) -> Self {
121        let protocol_name = <ColocatedMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME;
122        Self { client: fidl::client::Client::new(channel, protocol_name) }
123    }
124
125    /// Get a Stream of events from the remote end of the protocol.
126    ///
127    /// # Panics
128    ///
129    /// Panics if the event stream was already taken.
130    pub fn take_event_stream(&self) -> ColocatedEventStream {
131        ColocatedEventStream { event_receiver: self.client.take_event_receiver() }
132    }
133
134    /// Returns a list of VMO Koids used by the component,
135    pub fn r#get_vmos(
136        &self,
137    ) -> fidl::client::QueryResponseFut<Vec<u64>, fidl::encoding::DefaultFuchsiaResourceDialect>
138    {
139        ColocatedProxyInterface::r#get_vmos(self)
140    }
141}
142
143impl ColocatedProxyInterface for ColocatedProxy {
144    type GetVmosResponseFut =
145        fidl::client::QueryResponseFut<Vec<u64>, fidl::encoding::DefaultFuchsiaResourceDialect>;
146    fn r#get_vmos(&self) -> Self::GetVmosResponseFut {
147        fn _decode(
148            mut _buf: Result<<fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc, fidl::Error>,
149        ) -> Result<Vec<u64>, fidl::Error> {
150            let _response = fidl::client::decode_transaction_body::<
151                fidl::encoding::FlexibleType<ColocatedGetVmosResponse>,
152                fidl::encoding::DefaultFuchsiaResourceDialect,
153                0x6e0e1cca8af3632a,
154            >(_buf?)?
155            .into_result::<ColocatedMarker>("get_vmos")?;
156            Ok(_response.vmos)
157        }
158        self.client.send_query_and_decode::<fidl::encoding::EmptyPayload, Vec<u64>>(
159            (),
160            0x6e0e1cca8af3632a,
161            fidl::encoding::DynamicFlags::FLEXIBLE,
162            _decode,
163        )
164    }
165}
166
167pub struct ColocatedEventStream {
168    event_receiver: fidl::client::EventReceiver<fidl::encoding::DefaultFuchsiaResourceDialect>,
169}
170
171impl std::marker::Unpin for ColocatedEventStream {}
172
173impl futures::stream::FusedStream for ColocatedEventStream {
174    fn is_terminated(&self) -> bool {
175        self.event_receiver.is_terminated()
176    }
177}
178
179impl futures::Stream for ColocatedEventStream {
180    type Item = Result<ColocatedEvent, fidl::Error>;
181
182    fn poll_next(
183        mut self: std::pin::Pin<&mut Self>,
184        cx: &mut std::task::Context<'_>,
185    ) -> std::task::Poll<Option<Self::Item>> {
186        match futures::ready!(futures::stream::StreamExt::poll_next_unpin(
187            &mut self.event_receiver,
188            cx
189        )?) {
190            Some(buf) => std::task::Poll::Ready(Some(ColocatedEvent::decode(buf))),
191            None => std::task::Poll::Ready(None),
192        }
193    }
194}
195
196#[derive(Debug)]
197pub enum ColocatedEvent {
198    #[non_exhaustive]
199    _UnknownEvent {
200        /// Ordinal of the event that was sent.
201        ordinal: u64,
202    },
203}
204
205impl ColocatedEvent {
206    /// Decodes a message buffer as a [`ColocatedEvent`].
207    fn decode(
208        mut buf: <fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc,
209    ) -> Result<ColocatedEvent, fidl::Error> {
210        let (bytes, _handles) = buf.split_mut();
211        let (tx_header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
212        debug_assert_eq!(tx_header.tx_id, 0);
213        match tx_header.ordinal {
214            _ if tx_header.dynamic_flags().contains(fidl::encoding::DynamicFlags::FLEXIBLE) => {
215                Ok(ColocatedEvent::_UnknownEvent { ordinal: tx_header.ordinal })
216            }
217            _ => Err(fidl::Error::UnknownOrdinal {
218                ordinal: tx_header.ordinal,
219                protocol_name: <ColocatedMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
220            }),
221        }
222    }
223}
224
225/// A Stream of incoming requests for fuchsia.examples.colocated/Colocated.
226pub struct ColocatedRequestStream {
227    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
228    is_terminated: bool,
229}
230
231impl std::marker::Unpin for ColocatedRequestStream {}
232
233impl futures::stream::FusedStream for ColocatedRequestStream {
234    fn is_terminated(&self) -> bool {
235        self.is_terminated
236    }
237}
238
239impl fidl::endpoints::RequestStream for ColocatedRequestStream {
240    type Protocol = ColocatedMarker;
241    type ControlHandle = ColocatedControlHandle;
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        ColocatedControlHandle { 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 ColocatedRequestStream {
267    type Item = Result<ColocatedRequest, 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 ColocatedRequestStream 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                    0x6e0e1cca8af3632a => {
302                        header.validate_request_tx_id(fidl::MethodType::TwoWay)?;
303                        let mut req = fidl::new_empty!(
304                            fidl::encoding::EmptyPayload,
305                            fidl::encoding::DefaultFuchsiaResourceDialect
306                        );
307                        fidl::encoding::Decoder::<fidl::encoding::DefaultFuchsiaResourceDialect>::decode_into::<fidl::encoding::EmptyPayload>(&header, _body_bytes, handles, &mut req)?;
308                        let control_handle = ColocatedControlHandle { inner: this.inner.clone() };
309                        Ok(ColocatedRequest::GetVmos {
310                            responder: ColocatedGetVmosResponder {
311                                control_handle: std::mem::ManuallyDrop::new(control_handle),
312                                tx_id: header.tx_id,
313                            },
314                        })
315                    }
316                    _ if header.tx_id == 0
317                        && header
318                            .dynamic_flags()
319                            .contains(fidl::encoding::DynamicFlags::FLEXIBLE) =>
320                    {
321                        Ok(ColocatedRequest::_UnknownMethod {
322                            ordinal: header.ordinal,
323                            control_handle: ColocatedControlHandle { inner: this.inner.clone() },
324                            method_type: fidl::MethodType::OneWay,
325                        })
326                    }
327                    _ if header
328                        .dynamic_flags()
329                        .contains(fidl::encoding::DynamicFlags::FLEXIBLE) =>
330                    {
331                        this.inner.send_framework_err(
332                            fidl::encoding::FrameworkErr::UnknownMethod,
333                            header.tx_id,
334                            header.ordinal,
335                            header.dynamic_flags(),
336                            (bytes, handles),
337                        )?;
338                        Ok(ColocatedRequest::_UnknownMethod {
339                            ordinal: header.ordinal,
340                            control_handle: ColocatedControlHandle { inner: this.inner.clone() },
341                            method_type: fidl::MethodType::TwoWay,
342                        })
343                    }
344                    _ => Err(fidl::Error::UnknownOrdinal {
345                        ordinal: header.ordinal,
346                        protocol_name:
347                            <ColocatedMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
348                    }),
349                }))
350            },
351        )
352    }
353}
354
355/// A protocol for reporting one's own VMO usage.
356///
357/// This protocol is used for integration testing.
358#[derive(Debug)]
359pub enum ColocatedRequest {
360    /// Returns a list of VMO Koids used by the component,
361    GetVmos { responder: ColocatedGetVmosResponder },
362    /// An interaction was received which does not match any known method.
363    #[non_exhaustive]
364    _UnknownMethod {
365        /// Ordinal of the method that was called.
366        ordinal: u64,
367        control_handle: ColocatedControlHandle,
368        method_type: fidl::MethodType,
369    },
370}
371
372impl ColocatedRequest {
373    #[allow(irrefutable_let_patterns)]
374    pub fn into_get_vmos(self) -> Option<(ColocatedGetVmosResponder)> {
375        if let ColocatedRequest::GetVmos { responder } = self {
376            Some((responder))
377        } else {
378            None
379        }
380    }
381
382    /// Name of the method defined in FIDL
383    pub fn method_name(&self) -> &'static str {
384        match *self {
385            ColocatedRequest::GetVmos { .. } => "get_vmos",
386            ColocatedRequest::_UnknownMethod { method_type: fidl::MethodType::OneWay, .. } => {
387                "unknown one-way method"
388            }
389            ColocatedRequest::_UnknownMethod { method_type: fidl::MethodType::TwoWay, .. } => {
390                "unknown two-way method"
391            }
392        }
393    }
394}
395
396#[derive(Debug, Clone)]
397pub struct ColocatedControlHandle {
398    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
399}
400
401impl fidl::endpoints::ControlHandle for ColocatedControlHandle {
402    fn shutdown(&self) {
403        self.inner.shutdown()
404    }
405    fn shutdown_with_epitaph(&self, status: zx_status::Status) {
406        self.inner.shutdown_with_epitaph(status)
407    }
408
409    fn is_closed(&self) -> bool {
410        self.inner.channel().is_closed()
411    }
412    fn on_closed(&self) -> fidl::OnSignalsRef<'_> {
413        self.inner.channel().on_closed()
414    }
415
416    #[cfg(target_os = "fuchsia")]
417    fn signal_peer(
418        &self,
419        clear_mask: zx::Signals,
420        set_mask: zx::Signals,
421    ) -> Result<(), zx_status::Status> {
422        use fidl::Peered;
423        self.inner.channel().signal_peer(clear_mask, set_mask)
424    }
425}
426
427impl ColocatedControlHandle {}
428
429#[must_use = "FIDL methods require a response to be sent"]
430#[derive(Debug)]
431pub struct ColocatedGetVmosResponder {
432    control_handle: std::mem::ManuallyDrop<ColocatedControlHandle>,
433    tx_id: u32,
434}
435
436/// Set the the channel to be shutdown (see [`ColocatedControlHandle::shutdown`])
437/// if the responder is dropped without sending a response, so that the client
438/// doesn't hang. To prevent this behavior, call `drop_without_shutdown`.
439impl std::ops::Drop for ColocatedGetVmosResponder {
440    fn drop(&mut self) {
441        self.control_handle.shutdown();
442        // Safety: drops once, never accessed again
443        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
444    }
445}
446
447impl fidl::endpoints::Responder for ColocatedGetVmosResponder {
448    type ControlHandle = ColocatedControlHandle;
449
450    fn control_handle(&self) -> &ColocatedControlHandle {
451        &self.control_handle
452    }
453
454    fn drop_without_shutdown(mut self) {
455        // Safety: drops once, never accessed again due to mem::forget
456        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
457        // Prevent Drop from running (which would shut down the channel)
458        std::mem::forget(self);
459    }
460}
461
462impl ColocatedGetVmosResponder {
463    /// Sends a response to the FIDL transaction.
464    ///
465    /// Sets the channel to shutdown if an error occurs.
466    pub fn send(self, mut vmos: &[u64]) -> Result<(), fidl::Error> {
467        let _result = self.send_raw(vmos);
468        if _result.is_err() {
469            self.control_handle.shutdown();
470        }
471        self.drop_without_shutdown();
472        _result
473    }
474
475    /// Similar to "send" but does not shutdown the channel if an error occurs.
476    pub fn send_no_shutdown_on_err(self, mut vmos: &[u64]) -> Result<(), fidl::Error> {
477        let _result = self.send_raw(vmos);
478        self.drop_without_shutdown();
479        _result
480    }
481
482    fn send_raw(&self, mut vmos: &[u64]) -> Result<(), fidl::Error> {
483        self.control_handle.inner.send::<fidl::encoding::FlexibleType<ColocatedGetVmosResponse>>(
484            fidl::encoding::Flexible::new((vmos,)),
485            self.tx_id,
486            0x6e0e1cca8af3632a,
487            fidl::encoding::DynamicFlags::FLEXIBLE,
488        )
489    }
490}
491
492mod internal {
493    use super::*;
494
495    impl fidl::encoding::ValueTypeMarker for ColocatedGetVmosResponse {
496        type Borrowed<'a> = &'a Self;
497        fn borrow(value: &<Self as fidl::encoding::TypeMarker>::Owned) -> Self::Borrowed<'_> {
498            value
499        }
500    }
501
502    unsafe impl fidl::encoding::TypeMarker for ColocatedGetVmosResponse {
503        type Owned = Self;
504
505        #[inline(always)]
506        fn inline_align(_context: fidl::encoding::Context) -> usize {
507            8
508        }
509
510        #[inline(always)]
511        fn inline_size(_context: fidl::encoding::Context) -> usize {
512            16
513        }
514    }
515
516    unsafe impl<D: fidl::encoding::ResourceDialect>
517        fidl::encoding::Encode<ColocatedGetVmosResponse, D> for &ColocatedGetVmosResponse
518    {
519        #[inline]
520        unsafe fn encode(
521            self,
522            encoder: &mut fidl::encoding::Encoder<'_, D>,
523            offset: usize,
524            _depth: fidl::encoding::Depth,
525        ) -> fidl::Result<()> {
526            encoder.debug_check_bounds::<ColocatedGetVmosResponse>(offset);
527            // Delegate to tuple encoding.
528            fidl::encoding::Encode::<ColocatedGetVmosResponse, D>::encode(
529                (
530                    <fidl::encoding::UnboundedVector<u64> as fidl::encoding::ValueTypeMarker>::borrow(&self.vmos),
531                ),
532                encoder, offset, _depth
533            )
534        }
535    }
536    unsafe impl<
537            D: fidl::encoding::ResourceDialect,
538            T0: fidl::encoding::Encode<fidl::encoding::UnboundedVector<u64>, D>,
539        > fidl::encoding::Encode<ColocatedGetVmosResponse, D> for (T0,)
540    {
541        #[inline]
542        unsafe fn encode(
543            self,
544            encoder: &mut fidl::encoding::Encoder<'_, D>,
545            offset: usize,
546            depth: fidl::encoding::Depth,
547        ) -> fidl::Result<()> {
548            encoder.debug_check_bounds::<ColocatedGetVmosResponse>(offset);
549            // Zero out padding regions. There's no need to apply masks
550            // because the unmasked parts will be overwritten by fields.
551            // Write the fields.
552            self.0.encode(encoder, offset + 0, depth)?;
553            Ok(())
554        }
555    }
556
557    impl<D: fidl::encoding::ResourceDialect> fidl::encoding::Decode<Self, D>
558        for ColocatedGetVmosResponse
559    {
560        #[inline(always)]
561        fn new_empty() -> Self {
562            Self { vmos: fidl::new_empty!(fidl::encoding::UnboundedVector<u64>, D) }
563        }
564
565        #[inline]
566        unsafe fn decode(
567            &mut self,
568            decoder: &mut fidl::encoding::Decoder<'_, D>,
569            offset: usize,
570            _depth: fidl::encoding::Depth,
571        ) -> fidl::Result<()> {
572            decoder.debug_check_bounds::<Self>(offset);
573            // Verify that padding bytes are zero.
574            fidl::decode!(
575                fidl::encoding::UnboundedVector<u64>,
576                D,
577                &mut self.vmos,
578                decoder,
579                offset + 0,
580                _depth
581            )?;
582            Ok(())
583        }
584    }
585}