fidl_examples_keyvaluestore_supporttrees/
fidl_examples_keyvaluestore_supporttrees.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_examples_keyvaluestore_supporttrees_common::*;
11use futures::future::{self, MaybeDone, TryFutureExt};
12use zx_status;
13
14#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
15pub struct StoreMarker;
16
17impl fidl::endpoints::ProtocolMarker for StoreMarker {
18    type Proxy = StoreProxy;
19    type RequestStream = StoreRequestStream;
20    #[cfg(target_os = "fuchsia")]
21    type SynchronousProxy = StoreSynchronousProxy;
22
23    const DEBUG_NAME: &'static str = "examples.keyvaluestore.supporttrees.Store";
24}
25impl fidl::endpoints::DiscoverableProtocolMarker for StoreMarker {}
26pub type StoreWriteItemResult = Result<(), WriteError>;
27
28pub trait StoreProxyInterface: Send + Sync {
29    type WriteItemResponseFut: std::future::Future<Output = Result<StoreWriteItemResult, fidl::Error>>
30        + Send;
31    fn r#write_item(&self, attempt: &Item) -> Self::WriteItemResponseFut;
32}
33#[derive(Debug)]
34#[cfg(target_os = "fuchsia")]
35pub struct StoreSynchronousProxy {
36    client: fidl::client::sync::Client,
37}
38
39#[cfg(target_os = "fuchsia")]
40impl fidl::endpoints::SynchronousProxy for StoreSynchronousProxy {
41    type Proxy = StoreProxy;
42    type Protocol = StoreMarker;
43
44    fn from_channel(inner: fidl::Channel) -> Self {
45        Self::new(inner)
46    }
47
48    fn into_channel(self) -> fidl::Channel {
49        self.client.into_channel()
50    }
51
52    fn as_channel(&self) -> &fidl::Channel {
53        self.client.as_channel()
54    }
55}
56
57#[cfg(target_os = "fuchsia")]
58impl StoreSynchronousProxy {
59    pub fn new(channel: fidl::Channel) -> Self {
60        let protocol_name = <StoreMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME;
61        Self { client: fidl::client::sync::Client::new(channel, protocol_name) }
62    }
63
64    pub fn into_channel(self) -> fidl::Channel {
65        self.client.into_channel()
66    }
67
68    /// Waits until an event arrives and returns it. It is safe for other
69    /// threads to make concurrent requests while waiting for an event.
70    pub fn wait_for_event(
71        &self,
72        deadline: zx::MonotonicInstant,
73    ) -> Result<StoreEvent, fidl::Error> {
74        StoreEvent::decode(self.client.wait_for_event(deadline)?)
75    }
76
77    /// Writes an item to the store.
78    pub fn r#write_item(
79        &self,
80        mut attempt: &Item,
81        ___deadline: zx::MonotonicInstant,
82    ) -> Result<StoreWriteItemResult, fidl::Error> {
83        let _response = self.client.send_query::<
84            StoreWriteItemRequest,
85            fidl::encoding::FlexibleResultType<fidl::encoding::EmptyStruct, WriteError>,
86        >(
87            (attempt,),
88            0x4a01d5d999e00aa2,
89            fidl::encoding::DynamicFlags::FLEXIBLE,
90            ___deadline,
91        )?
92        .into_result::<StoreMarker>("write_item")?;
93        Ok(_response.map(|x| x))
94    }
95}
96
97#[derive(Debug, Clone)]
98pub struct StoreProxy {
99    client: fidl::client::Client<fidl::encoding::DefaultFuchsiaResourceDialect>,
100}
101
102impl fidl::endpoints::Proxy for StoreProxy {
103    type Protocol = StoreMarker;
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 StoreProxy {
119    /// Create a new Proxy for examples.keyvaluestore.supporttrees/Store.
120    pub fn new(channel: ::fidl::AsyncChannel) -> Self {
121        let protocol_name = <StoreMarker 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) -> StoreEventStream {
131        StoreEventStream { event_receiver: self.client.take_event_receiver() }
132    }
133
134    /// Writes an item to the store.
135    pub fn r#write_item(
136        &self,
137        mut attempt: &Item,
138    ) -> fidl::client::QueryResponseFut<
139        StoreWriteItemResult,
140        fidl::encoding::DefaultFuchsiaResourceDialect,
141    > {
142        StoreProxyInterface::r#write_item(self, attempt)
143    }
144}
145
146impl StoreProxyInterface for StoreProxy {
147    type WriteItemResponseFut = fidl::client::QueryResponseFut<
148        StoreWriteItemResult,
149        fidl::encoding::DefaultFuchsiaResourceDialect,
150    >;
151    fn r#write_item(&self, mut attempt: &Item) -> Self::WriteItemResponseFut {
152        fn _decode(
153            mut _buf: Result<<fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc, fidl::Error>,
154        ) -> Result<StoreWriteItemResult, fidl::Error> {
155            let _response = fidl::client::decode_transaction_body::<
156                fidl::encoding::FlexibleResultType<fidl::encoding::EmptyStruct, WriteError>,
157                fidl::encoding::DefaultFuchsiaResourceDialect,
158                0x4a01d5d999e00aa2,
159            >(_buf?)?
160            .into_result::<StoreMarker>("write_item")?;
161            Ok(_response.map(|x| x))
162        }
163        self.client.send_query_and_decode::<StoreWriteItemRequest, StoreWriteItemResult>(
164            (attempt,),
165            0x4a01d5d999e00aa2,
166            fidl::encoding::DynamicFlags::FLEXIBLE,
167            _decode,
168        )
169    }
170}
171
172pub struct StoreEventStream {
173    event_receiver: fidl::client::EventReceiver<fidl::encoding::DefaultFuchsiaResourceDialect>,
174}
175
176impl std::marker::Unpin for StoreEventStream {}
177
178impl futures::stream::FusedStream for StoreEventStream {
179    fn is_terminated(&self) -> bool {
180        self.event_receiver.is_terminated()
181    }
182}
183
184impl futures::Stream for StoreEventStream {
185    type Item = Result<StoreEvent, fidl::Error>;
186
187    fn poll_next(
188        mut self: std::pin::Pin<&mut Self>,
189        cx: &mut std::task::Context<'_>,
190    ) -> std::task::Poll<Option<Self::Item>> {
191        match futures::ready!(futures::stream::StreamExt::poll_next_unpin(
192            &mut self.event_receiver,
193            cx
194        )?) {
195            Some(buf) => std::task::Poll::Ready(Some(StoreEvent::decode(buf))),
196            None => std::task::Poll::Ready(None),
197        }
198    }
199}
200
201#[derive(Debug)]
202pub enum StoreEvent {
203    #[non_exhaustive]
204    _UnknownEvent {
205        /// Ordinal of the event that was sent.
206        ordinal: u64,
207    },
208}
209
210impl StoreEvent {
211    /// Decodes a message buffer as a [`StoreEvent`].
212    fn decode(
213        mut buf: <fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc,
214    ) -> Result<StoreEvent, 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            _ if tx_header.dynamic_flags().contains(fidl::encoding::DynamicFlags::FLEXIBLE) => {
220                Ok(StoreEvent::_UnknownEvent { ordinal: tx_header.ordinal })
221            }
222            _ => Err(fidl::Error::UnknownOrdinal {
223                ordinal: tx_header.ordinal,
224                protocol_name: <StoreMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
225            }),
226        }
227    }
228}
229
230/// A Stream of incoming requests for examples.keyvaluestore.supporttrees/Store.
231pub struct StoreRequestStream {
232    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
233    is_terminated: bool,
234}
235
236impl std::marker::Unpin for StoreRequestStream {}
237
238impl futures::stream::FusedStream for StoreRequestStream {
239    fn is_terminated(&self) -> bool {
240        self.is_terminated
241    }
242}
243
244impl fidl::endpoints::RequestStream for StoreRequestStream {
245    type Protocol = StoreMarker;
246    type ControlHandle = StoreControlHandle;
247
248    fn from_channel(channel: ::fidl::AsyncChannel) -> Self {
249        Self { inner: std::sync::Arc::new(fidl::ServeInner::new(channel)), is_terminated: false }
250    }
251
252    fn control_handle(&self) -> Self::ControlHandle {
253        StoreControlHandle { inner: self.inner.clone() }
254    }
255
256    fn into_inner(
257        self,
258    ) -> (::std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>, bool)
259    {
260        (self.inner, self.is_terminated)
261    }
262
263    fn from_inner(
264        inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
265        is_terminated: bool,
266    ) -> Self {
267        Self { inner, is_terminated }
268    }
269}
270
271impl futures::Stream for StoreRequestStream {
272    type Item = Result<StoreRequest, fidl::Error>;
273
274    fn poll_next(
275        mut self: std::pin::Pin<&mut Self>,
276        cx: &mut std::task::Context<'_>,
277    ) -> std::task::Poll<Option<Self::Item>> {
278        let this = &mut *self;
279        if this.inner.check_shutdown(cx) {
280            this.is_terminated = true;
281            return std::task::Poll::Ready(None);
282        }
283        if this.is_terminated {
284            panic!("polled StoreRequestStream after completion");
285        }
286        fidl::encoding::with_tls_decode_buf::<_, fidl::encoding::DefaultFuchsiaResourceDialect>(
287            |bytes, handles| {
288                match this.inner.channel().read_etc(cx, bytes, handles) {
289                    std::task::Poll::Ready(Ok(())) => {}
290                    std::task::Poll::Pending => return std::task::Poll::Pending,
291                    std::task::Poll::Ready(Err(zx_status::Status::PEER_CLOSED)) => {
292                        this.is_terminated = true;
293                        return std::task::Poll::Ready(None);
294                    }
295                    std::task::Poll::Ready(Err(e)) => {
296                        return std::task::Poll::Ready(Some(Err(fidl::Error::ServerRequestRead(
297                            e.into(),
298                        ))))
299                    }
300                }
301
302                // A message has been received from the channel
303                let (header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
304
305                std::task::Poll::Ready(Some(match header.ordinal {
306                    0x4a01d5d999e00aa2 => {
307                        header.validate_request_tx_id(fidl::MethodType::TwoWay)?;
308                        let mut req = fidl::new_empty!(
309                            StoreWriteItemRequest,
310                            fidl::encoding::DefaultFuchsiaResourceDialect
311                        );
312                        fidl::encoding::Decoder::<fidl::encoding::DefaultFuchsiaResourceDialect>::decode_into::<StoreWriteItemRequest>(&header, _body_bytes, handles, &mut req)?;
313                        let control_handle = StoreControlHandle { inner: this.inner.clone() };
314                        Ok(StoreRequest::WriteItem {
315                            attempt: req.attempt,
316
317                            responder: StoreWriteItemResponder {
318                                control_handle: std::mem::ManuallyDrop::new(control_handle),
319                                tx_id: header.tx_id,
320                            },
321                        })
322                    }
323                    _ if header.tx_id == 0
324                        && header
325                            .dynamic_flags()
326                            .contains(fidl::encoding::DynamicFlags::FLEXIBLE) =>
327                    {
328                        Ok(StoreRequest::_UnknownMethod {
329                            ordinal: header.ordinal,
330                            control_handle: StoreControlHandle { inner: this.inner.clone() },
331                            method_type: fidl::MethodType::OneWay,
332                        })
333                    }
334                    _ if header
335                        .dynamic_flags()
336                        .contains(fidl::encoding::DynamicFlags::FLEXIBLE) =>
337                    {
338                        this.inner.send_framework_err(
339                            fidl::encoding::FrameworkErr::UnknownMethod,
340                            header.tx_id,
341                            header.ordinal,
342                            header.dynamic_flags(),
343                            (bytes, handles),
344                        )?;
345                        Ok(StoreRequest::_UnknownMethod {
346                            ordinal: header.ordinal,
347                            control_handle: StoreControlHandle { inner: this.inner.clone() },
348                            method_type: fidl::MethodType::TwoWay,
349                        })
350                    }
351                    _ => Err(fidl::Error::UnknownOrdinal {
352                        ordinal: header.ordinal,
353                        protocol_name: <StoreMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
354                    }),
355                }))
356            },
357        )
358    }
359}
360
361/// A very basic key-value store.
362#[derive(Debug)]
363pub enum StoreRequest {
364    /// Writes an item to the store.
365    WriteItem { attempt: Item, responder: StoreWriteItemResponder },
366    /// An interaction was received which does not match any known method.
367    #[non_exhaustive]
368    _UnknownMethod {
369        /// Ordinal of the method that was called.
370        ordinal: u64,
371        control_handle: StoreControlHandle,
372        method_type: fidl::MethodType,
373    },
374}
375
376impl StoreRequest {
377    #[allow(irrefutable_let_patterns)]
378    pub fn into_write_item(self) -> Option<(Item, StoreWriteItemResponder)> {
379        if let StoreRequest::WriteItem { attempt, responder } = self {
380            Some((attempt, responder))
381        } else {
382            None
383        }
384    }
385
386    /// Name of the method defined in FIDL
387    pub fn method_name(&self) -> &'static str {
388        match *self {
389            StoreRequest::WriteItem { .. } => "write_item",
390            StoreRequest::_UnknownMethod { method_type: fidl::MethodType::OneWay, .. } => {
391                "unknown one-way method"
392            }
393            StoreRequest::_UnknownMethod { method_type: fidl::MethodType::TwoWay, .. } => {
394                "unknown two-way method"
395            }
396        }
397    }
398}
399
400#[derive(Debug, Clone)]
401pub struct StoreControlHandle {
402    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
403}
404
405impl fidl::endpoints::ControlHandle for StoreControlHandle {
406    fn shutdown(&self) {
407        self.inner.shutdown()
408    }
409    fn shutdown_with_epitaph(&self, status: zx_status::Status) {
410        self.inner.shutdown_with_epitaph(status)
411    }
412
413    fn is_closed(&self) -> bool {
414        self.inner.channel().is_closed()
415    }
416    fn on_closed(&self) -> fidl::OnSignalsRef<'_> {
417        self.inner.channel().on_closed()
418    }
419
420    #[cfg(target_os = "fuchsia")]
421    fn signal_peer(
422        &self,
423        clear_mask: zx::Signals,
424        set_mask: zx::Signals,
425    ) -> Result<(), zx_status::Status> {
426        use fidl::Peered;
427        self.inner.channel().signal_peer(clear_mask, set_mask)
428    }
429}
430
431impl StoreControlHandle {}
432
433#[must_use = "FIDL methods require a response to be sent"]
434#[derive(Debug)]
435pub struct StoreWriteItemResponder {
436    control_handle: std::mem::ManuallyDrop<StoreControlHandle>,
437    tx_id: u32,
438}
439
440/// Set the the channel to be shutdown (see [`StoreControlHandle::shutdown`])
441/// if the responder is dropped without sending a response, so that the client
442/// doesn't hang. To prevent this behavior, call `drop_without_shutdown`.
443impl std::ops::Drop for StoreWriteItemResponder {
444    fn drop(&mut self) {
445        self.control_handle.shutdown();
446        // Safety: drops once, never accessed again
447        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
448    }
449}
450
451impl fidl::endpoints::Responder for StoreWriteItemResponder {
452    type ControlHandle = StoreControlHandle;
453
454    fn control_handle(&self) -> &StoreControlHandle {
455        &self.control_handle
456    }
457
458    fn drop_without_shutdown(mut self) {
459        // Safety: drops once, never accessed again due to mem::forget
460        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
461        // Prevent Drop from running (which would shut down the channel)
462        std::mem::forget(self);
463    }
464}
465
466impl StoreWriteItemResponder {
467    /// Sends a response to the FIDL transaction.
468    ///
469    /// Sets the channel to shutdown if an error occurs.
470    pub fn send(self, mut result: Result<(), WriteError>) -> Result<(), fidl::Error> {
471        let _result = self.send_raw(result);
472        if _result.is_err() {
473            self.control_handle.shutdown();
474        }
475        self.drop_without_shutdown();
476        _result
477    }
478
479    /// Similar to "send" but does not shutdown the channel if an error occurs.
480    pub fn send_no_shutdown_on_err(
481        self,
482        mut result: Result<(), WriteError>,
483    ) -> Result<(), fidl::Error> {
484        let _result = self.send_raw(result);
485        self.drop_without_shutdown();
486        _result
487    }
488
489    fn send_raw(&self, mut result: Result<(), WriteError>) -> Result<(), fidl::Error> {
490        self.control_handle.inner.send::<fidl::encoding::FlexibleResultType<
491            fidl::encoding::EmptyStruct,
492            WriteError,
493        >>(
494            fidl::encoding::FlexibleResult::new(result),
495            self.tx_id,
496            0x4a01d5d999e00aa2,
497            fidl::encoding::DynamicFlags::FLEXIBLE,
498        )
499    }
500}
501
502mod internal {
503    use super::*;
504}