• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2023 Google LLC.  All rights reserved.
3 //
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file or at
6 // https://developers.google.com/open-source/licenses/bsd
7 
8 //! Items specific to `optional` fields.
9 #![allow(dead_code)]
10 #![allow(unused)]
11 
12 use crate::__internal::Private;
13 use crate::{Mut, MutProxied, MutProxy, Proxied, View, ViewProxy};
14 use std::convert::{AsMut, AsRef};
15 use std::fmt::{self, Debug};
16 use std::panic;
17 use std::ptr;
18 
19 /// A protobuf value from a field that may not be set.
20 ///
21 /// This can be pattern matched with `match` or `if let` to determine if the
22 /// field is set and access the field data.
23 ///
24 /// Two `Optional`s are equal if they match both presence and the field values.
25 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
26 pub enum Optional<T> {
27     /// The field is set; it is present in the serialized message.
28     ///
29     /// - For an `_opt()` accessor, this contains a `View<impl Proxied>`.
30     /// - For a `_mut()` accessor, this contains a [`PresentField`] that can be
31     ///   used to access the current value, convert to [`Mut`], clear presence,
32     ///   or set a new value.
33     Set(T),
34 
35     /// The field is unset; it is absent in the serialized message.
36     ///
37     /// - For an `_opt()` accessor, this contains a `View<impl Proxied>` with
38     ///   the default value.
39     /// - For a `_mut()` accessor, this contains an [`AbsentField`] that can be
40     ///   used to access the default or set a new value.
41     Unset(T),
42 }
43 
44 impl<T> Optional<T> {
45     /// Gets the field value, ignoring whether it was set or not.
into_inner(self) -> T46     pub fn into_inner(self) -> T {
47         match self {
48             Optional::Set(x) | Optional::Unset(x) => x,
49         }
50     }
51 
52     /// Constructs an `Optional<T>` with a `T` value and presence bit.
new(val: T, is_set: bool) -> Self53     pub fn new(val: T, is_set: bool) -> Self {
54         if is_set { Optional::Set(val) } else { Optional::Unset(val) }
55     }
56 
57     /// Converts into an `Option` of the set value, ignoring any unset value.
into_option(self) -> Option<T>58     pub fn into_option(self) -> Option<T> {
59         if let Optional::Set(x) = self { Some(x) } else { None }
60     }
61 
62     /// Returns if the field is set.
is_set(&self) -> bool63     pub fn is_set(&self) -> bool {
64         matches!(self, Optional::Set(_))
65     }
66 
67     /// Returns if the field is unset.
is_unset(&self) -> bool68     pub fn is_unset(&self) -> bool {
69         matches!(self, Optional::Unset(_))
70     }
71 }
72 
73 impl<T> From<Optional<T>> for Option<T> {
from(x: Optional<T>) -> Option<T>74     fn from(x: Optional<T>) -> Option<T> {
75         x.into_option()
76     }
77 }
78