Skip to main content

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