Skip to main content

fidl_next_protocol/
flexible.rs

1// Copyright 2026 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use crate::FrameworkError;
6
7/// A flexible FIDL response.
8#[derive(Clone, Debug)]
9pub enum Flexible<T> {
10    /// The value of the flexible call when successful.
11    Ok(T),
12    /// The error indicating that the flexible call failed.
13    FrameworkErr(FrameworkError),
14}
15
16impl<T> Flexible<T> {
17    /// Returns whether the flexible response is `Ok`.
18    pub fn is_ok(&self) -> bool {
19        matches!(self, Self::Ok(_))
20    }
21
22    /// Returns whether the flexible response is `FrameworkErr`.
23    pub fn is_framework_err(&self) -> bool {
24        matches!(self, Self::FrameworkErr(_))
25    }
26
27    /// Returns the `Ok` value of the response, if any.
28    pub fn ok(self) -> Option<T> {
29        if let Self::Ok(value) = self { Some(value) } else { None }
30    }
31
32    /// Returns the `FrameworkErr` value of the response, if any.
33    pub fn framework_err(self) -> Option<FrameworkError> {
34        if let Self::FrameworkErr(error) = self { Some(error) } else { None }
35    }
36
37    /// Returns the contained `Ok` value.
38    ///
39    /// Panics if the response was not `Ok`.
40    pub fn unwrap(self) -> T {
41        self.ok().unwrap()
42    }
43
44    /// Returns the contained `FrameworkErr` value.
45    ///
46    /// Panics if the response was not `FrameworkErr`.
47    pub fn unwrap_framework_err(self) -> FrameworkError {
48        self.framework_err().unwrap()
49    }
50
51    /// Converts from `&Flexible<T>` to `Flexible<&T>`.
52    pub fn as_ref(&self) -> Flexible<&T> {
53        match self {
54            Self::Ok(value) => Flexible::Ok(value),
55            Self::FrameworkErr(framework_error) => Flexible::FrameworkErr(*framework_error),
56        }
57    }
58}
59
60impl<T, T2> PartialEq<Flexible<T2>> for Flexible<T>
61where
62    T: PartialEq<T2>,
63{
64    fn eq(&self, other: &Flexible<T2>) -> bool {
65        match (self, other) {
66            (Flexible::Ok(lhs), Flexible::Ok(rhs)) => lhs == rhs,
67            (Flexible::FrameworkErr(lhs), Flexible::FrameworkErr(rhs)) => lhs == rhs,
68            _ => false,
69        }
70    }
71}