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