solana_program/
program_option.rs

1//! A C representation of Rust's `Option`, used across the FFI
2//! boundary for Safecoin program interfaces.
3//!
4//! This implementation mostly matches `std::option` except iterators since the iteration
5//! trait requires returning `std::option::Option`
6
7use std::{
8    convert, mem,
9    ops::{Deref, DerefMut},
10};
11
12/// A C representation of Rust's `std::option::Option`
13#[repr(C)]
14#[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
15pub enum COption<T> {
16    /// No value
17    None,
18    /// Some value `T`
19    Some(T),
20}
21
22/////////////////////////////////////////////////////////////////////////////
23// Type implementation
24/////////////////////////////////////////////////////////////////////////////
25
26impl<T> COption<T> {
27    /////////////////////////////////////////////////////////////////////////
28    // Querying the contained values
29    /////////////////////////////////////////////////////////////////////////
30
31    /// Returns `true` if the option is a [`COption::Some`] value.
32    ///
33    /// # Examples
34    ///
35    /// ```ignore
36    /// let x: COption<u32> = COption::Some(2);
37    /// assert_eq!(x.is_some(), true);
38    ///
39    /// let x: COption<u32> = COption::None;
40    /// assert_eq!(x.is_some(), false);
41    /// ```
42    ///
43    /// [`COption::Some`]: #variant.COption::Some
44    #[must_use = "if you intended to assert that this has a value, consider `.unwrap()` instead"]
45    #[inline]
46    pub fn is_some(&self) -> bool {
47        match *self {
48            COption::Some(_) => true,
49            COption::None => false,
50        }
51    }
52
53    /// Returns `true` if the option is a [`COption::None`] value.
54    ///
55    /// # Examples
56    ///
57    /// ```ignore
58    /// let x: COption<u32> = COption::Some(2);
59    /// assert_eq!(x.is_none(), false);
60    ///
61    /// let x: COption<u32> = COption::None;
62    /// assert_eq!(x.is_none(), true);
63    /// ```
64    ///
65    /// [`COption::None`]: #variant.COption::None
66    #[must_use = "if you intended to assert that this doesn't have a value, consider \
67                  `.and_then(|| panic!(\"`COption` had a value when expected `COption::None`\"))` instead"]
68    #[inline]
69    pub fn is_none(&self) -> bool {
70        !self.is_some()
71    }
72
73    /// Returns `true` if the option is a [`COption::Some`] value containing the given value.
74    ///
75    /// # Examples
76    ///
77    /// ```ignore
78    /// #![feature(option_result_contains)]
79    ///
80    /// let x: COption<u32> = COption::Some(2);
81    /// assert_eq!(x.contains(&2), true);
82    ///
83    /// let x: COption<u32> = COption::Some(3);
84    /// assert_eq!(x.contains(&2), false);
85    ///
86    /// let x: COption<u32> = COption::None;
87    /// assert_eq!(x.contains(&2), false);
88    /// ```
89    #[must_use]
90    #[inline]
91    pub fn contains<U>(&self, x: &U) -> bool
92    where
93        U: PartialEq<T>,
94    {
95        match self {
96            COption::Some(y) => x == y,
97            COption::None => false,
98        }
99    }
100
101    /////////////////////////////////////////////////////////////////////////
102    // Adapter for working with references
103    /////////////////////////////////////////////////////////////////////////
104
105    /// Converts from `&COption<T>` to `COption<&T>`.
106    ///
107    /// # Examples
108    ///
109    /// Converts an `COption<`[`String`]`>` into an `COption<`[`usize`]`>`, preserving the original.
110    /// The [`map`] method takes the `self` argument by value, consuming the original,
111    /// so this technique uses `as_ref` to first take an `COption` to a reference
112    /// to the value inside the original.
113    ///
114    /// [`map`]: enum.COption.html#method.map
115    /// [`String`]: ../../std/string/struct.String.html
116    /// [`usize`]: ../../std/primitive.usize.html
117    ///
118    /// ```ignore
119    /// let text: COption<String> = COption::Some("Hello, world!".to_string());
120    /// // First, cast `COption<String>` to `COption<&String>` with `as_ref`,
121    /// // then consume *that* with `map`, leaving `text` on the stack.
122    /// let text_length: COption<usize> = text.as_ref().map(|s| s.len());
123    /// println!("still can print text: {:?}", text);
124    /// ```
125    #[inline]
126    pub fn as_ref(&self) -> COption<&T> {
127        match *self {
128            COption::Some(ref x) => COption::Some(x),
129            COption::None => COption::None,
130        }
131    }
132
133    /// Converts from `&mut COption<T>` to `COption<&mut T>`.
134    ///
135    /// # Examples
136    ///
137    /// ```ignore
138    /// let mut x = COption::Some(2);
139    /// match x.as_mut() {
140    ///     COption::Some(v) => *v = 42,
141    ///     COption::None => {},
142    /// }
143    /// assert_eq!(x, COption::Some(42));
144    /// ```
145    #[inline]
146    pub fn as_mut(&mut self) -> COption<&mut T> {
147        match *self {
148            COption::Some(ref mut x) => COption::Some(x),
149            COption::None => COption::None,
150        }
151    }
152
153    /////////////////////////////////////////////////////////////////////////
154    // Getting to contained values
155    /////////////////////////////////////////////////////////////////////////
156
157    /// Unwraps an option, yielding the content of a [`COption::Some`].
158    ///
159    /// # Panics
160    ///
161    /// Panics if the value is a [`COption::None`] with a custom panic message provided by
162    /// `msg`.
163    ///
164    /// [`COption::Some`]: #variant.COption::Some
165    /// [`COption::None`]: #variant.COption::None
166    ///
167    /// # Examples
168    ///
169    /// ```ignore
170    /// let x = COption::Some("value");
171    /// assert_eq!(x.expect("the world is ending"), "value");
172    /// ```
173    ///
174    /// ```ignore{.should_panic}
175    /// let x: COption<&str> = COption::None;
176    /// x.expect("the world is ending"); // panics with `the world is ending`
177    /// ```
178    #[inline]
179    pub fn expect(self, msg: &str) -> T {
180        match self {
181            COption::Some(val) => val,
182            COption::None => expect_failed(msg),
183        }
184    }
185
186    /// Moves the value `v` out of the `COption<T>` if it is [`COption::Some(v)`].
187    ///
188    /// In general, because this function may panic, its use is discouraged.
189    /// Instead, prefer to use pattern matching and handle the [`COption::None`]
190    /// case explicitly.
191    ///
192    /// # Panics
193    ///
194    /// Panics if the self value equals [`COption::None`].
195    ///
196    /// [`COption::Some(v)`]: #variant.COption::Some
197    /// [`COption::None`]: #variant.COption::None
198    ///
199    /// # Examples
200    ///
201    /// ```ignore
202    /// let x = COption::Some("air");
203    /// assert_eq!(x.unwrap(), "air");
204    /// ```
205    ///
206    /// ```ignore{.should_panic}
207    /// let x: COption<&str> = COption::None;
208    /// assert_eq!(x.unwrap(), "air"); // fails
209    /// ```
210    #[inline]
211    pub fn unwrap(self) -> T {
212        match self {
213            COption::Some(val) => val,
214            COption::None => panic!("called `COption::unwrap()` on a `COption::None` value"),
215        }
216    }
217
218    /// Returns the contained value or a default.
219    ///
220    /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
221    /// the result of a function call, it is recommended to use [`unwrap_or_else`],
222    /// which is lazily evaluated.
223    ///
224    /// [`unwrap_or_else`]: #method.unwrap_or_else
225    ///
226    /// # Examples
227    ///
228    /// ```ignore
229    /// assert_eq!(COption::Some("car").unwrap_or("bike"), "car");
230    /// assert_eq!(COption::None.unwrap_or("bike"), "bike");
231    /// ```
232    #[inline]
233    pub fn unwrap_or(self, def: T) -> T {
234        match self {
235            COption::Some(x) => x,
236            COption::None => def,
237        }
238    }
239
240    /// Returns the contained value or computes it from a closure.
241    ///
242    /// # Examples
243    ///
244    /// ```ignore
245    /// let k = 10;
246    /// assert_eq!(COption::Some(4).unwrap_or_else(|| 2 * k), 4);
247    /// assert_eq!(COption::None.unwrap_or_else(|| 2 * k), 20);
248    /// ```
249    #[inline]
250    pub fn unwrap_or_else<F: FnOnce() -> T>(self, f: F) -> T {
251        match self {
252            COption::Some(x) => x,
253            COption::None => f(),
254        }
255    }
256
257    /////////////////////////////////////////////////////////////////////////
258    // Transforming contained values
259    /////////////////////////////////////////////////////////////////////////
260
261    /// Maps an `COption<T>` to `COption<U>` by applying a function to a contained value.
262    ///
263    /// # Examples
264    ///
265    /// Converts an `COption<`[`String`]`>` into an `COption<`[`usize`]`>`, consuming the original:
266    ///
267    /// [`String`]: ../../std/string/struct.String.html
268    /// [`usize`]: ../../std/primitive.usize.html
269    ///
270    /// ```ignore
271    /// let maybe_some_string = COption::Some(String::from("Hello, World!"));
272    /// // `COption::map` takes self *by value*, consuming `maybe_some_string`
273    /// let maybe_some_len = maybe_some_string.map(|s| s.len());
274    ///
275    /// assert_eq!(maybe_some_len, COption::Some(13));
276    /// ```
277    #[inline]
278    pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> COption<U> {
279        match self {
280            COption::Some(x) => COption::Some(f(x)),
281            COption::None => COption::None,
282        }
283    }
284
285    /// Applies a function to the contained value (if any),
286    /// or returns the provided default (if not).
287    ///
288    /// # Examples
289    ///
290    /// ```ignore
291    /// let x = COption::Some("foo");
292    /// assert_eq!(x.map_or(42, |v| v.len()), 3);
293    ///
294    /// let x: COption<&str> = COption::None;
295    /// assert_eq!(x.map_or(42, |v| v.len()), 42);
296    /// ```
297    #[inline]
298    pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
299        match self {
300            COption::Some(t) => f(t),
301            COption::None => default,
302        }
303    }
304
305    /// Applies a function to the contained value (if any),
306    /// or computes a default (if not).
307    ///
308    /// # Examples
309    ///
310    /// ```ignore
311    /// let k = 21;
312    ///
313    /// let x = COption::Some("foo");
314    /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
315    ///
316    /// let x: COption<&str> = COption::None;
317    /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
318    /// ```
319    #[inline]
320    pub fn map_or_else<U, D: FnOnce() -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
321        match self {
322            COption::Some(t) => f(t),
323            COption::None => default(),
324        }
325    }
326
327    /// Transforms the `COption<T>` into a [`Result<T, E>`], mapping [`COption::Some(v)`] to
328    /// [`Ok(v)`] and [`COption::None`] to [`Err(err)`].
329    ///
330    /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the
331    /// result of a function call, it is recommended to use [`ok_or_else`], which is
332    /// lazily evaluated.
333    ///
334    /// [`Result<T, E>`]: ../../std/result/enum.Result.html
335    /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok
336    /// [`Err(err)`]: ../../std/result/enum.Result.html#variant.Err
337    /// [`COption::None`]: #variant.COption::None
338    /// [`COption::Some(v)`]: #variant.COption::Some
339    /// [`ok_or_else`]: #method.ok_or_else
340    ///
341    /// # Examples
342    ///
343    /// ```ignore
344    /// let x = COption::Some("foo");
345    /// assert_eq!(x.ok_or(0), Ok("foo"));
346    ///
347    /// let x: COption<&str> = COption::None;
348    /// assert_eq!(x.ok_or(0), Err(0));
349    /// ```
350    #[inline]
351    pub fn ok_or<E>(self, err: E) -> Result<T, E> {
352        match self {
353            COption::Some(v) => Ok(v),
354            COption::None => Err(err),
355        }
356    }
357
358    /// Transforms the `COption<T>` into a [`Result<T, E>`], mapping [`COption::Some(v)`] to
359    /// [`Ok(v)`] and [`COption::None`] to [`Err(err())`].
360    ///
361    /// [`Result<T, E>`]: ../../std/result/enum.Result.html
362    /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok
363    /// [`Err(err())`]: ../../std/result/enum.Result.html#variant.Err
364    /// [`COption::None`]: #variant.COption::None
365    /// [`COption::Some(v)`]: #variant.COption::Some
366    ///
367    /// # Examples
368    ///
369    /// ```ignore
370    /// let x = COption::Some("foo");
371    /// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
372    ///
373    /// let x: COption<&str> = COption::None;
374    /// assert_eq!(x.ok_or_else(|| 0), Err(0));
375    /// ```
376    #[inline]
377    pub fn ok_or_else<E, F: FnOnce() -> E>(self, err: F) -> Result<T, E> {
378        match self {
379            COption::Some(v) => Ok(v),
380            COption::None => Err(err()),
381        }
382    }
383
384    /////////////////////////////////////////////////////////////////////////
385    // Boolean operations on the values, eager and lazy
386    /////////////////////////////////////////////////////////////////////////
387
388    /// Returns [`COption::None`] if the option is [`COption::None`], otherwise returns `optb`.
389    ///
390    /// [`COption::None`]: #variant.COption::None
391    ///
392    /// # Examples
393    ///
394    /// ```ignore
395    /// let x = COption::Some(2);
396    /// let y: COption<&str> = COption::None;
397    /// assert_eq!(x.and(y), COption::None);
398    ///
399    /// let x: COption<u32> = COption::None;
400    /// let y = COption::Some("foo");
401    /// assert_eq!(x.and(y), COption::None);
402    ///
403    /// let x = COption::Some(2);
404    /// let y = COption::Some("foo");
405    /// assert_eq!(x.and(y), COption::Some("foo"));
406    ///
407    /// let x: COption<u32> = COption::None;
408    /// let y: COption<&str> = COption::None;
409    /// assert_eq!(x.and(y), COption::None);
410    /// ```
411    #[inline]
412    pub fn and<U>(self, optb: COption<U>) -> COption<U> {
413        match self {
414            COption::Some(_) => optb,
415            COption::None => COption::None,
416        }
417    }
418
419    /// Returns [`COption::None`] if the option is [`COption::None`], otherwise calls `f` with the
420    /// wrapped value and returns the result.
421    ///
422    /// COption::Some languages call this operation flatmap.
423    ///
424    /// [`COption::None`]: #variant.COption::None
425    ///
426    /// # Examples
427    ///
428    /// ```ignore
429    /// fn sq(x: u32) -> COption<u32> { COption::Some(x * x) }
430    /// fn nope(_: u32) -> COption<u32> { COption::None }
431    ///
432    /// assert_eq!(COption::Some(2).and_then(sq).and_then(sq), COption::Some(16));
433    /// assert_eq!(COption::Some(2).and_then(sq).and_then(nope), COption::None);
434    /// assert_eq!(COption::Some(2).and_then(nope).and_then(sq), COption::None);
435    /// assert_eq!(COption::None.and_then(sq).and_then(sq), COption::None);
436    /// ```
437    #[inline]
438    pub fn and_then<U, F: FnOnce(T) -> COption<U>>(self, f: F) -> COption<U> {
439        match self {
440            COption::Some(x) => f(x),
441            COption::None => COption::None,
442        }
443    }
444
445    /// Returns [`COption::None`] if the option is [`COption::None`], otherwise calls `predicate`
446    /// with the wrapped value and returns:
447    ///
448    /// - [`COption::Some(t)`] if `predicate` returns `true` (where `t` is the wrapped
449    ///   value), and
450    /// - [`COption::None`] if `predicate` returns `false`.
451    ///
452    /// This function works similar to [`Iterator::filter()`]. You can imagine
453    /// the `COption<T>` being an iterator over one or zero elements. `filter()`
454    /// lets you decide which elements to keep.
455    ///
456    /// # Examples
457    ///
458    /// ```ignore
459    /// fn is_even(n: &i32) -> bool {
460    ///     n % 2 == 0
461    /// }
462    ///
463    /// assert_eq!(COption::None.filter(is_even), COption::None);
464    /// assert_eq!(COption::Some(3).filter(is_even), COption::None);
465    /// assert_eq!(COption::Some(4).filter(is_even), COption::Some(4));
466    /// ```
467    ///
468    /// [`COption::None`]: #variant.COption::None
469    /// [`COption::Some(t)`]: #variant.COption::Some
470    /// [`Iterator::filter()`]: ../../std/iter/trait.Iterator.html#method.filter
471    #[inline]
472    pub fn filter<P: FnOnce(&T) -> bool>(self, predicate: P) -> Self {
473        if let COption::Some(x) = self {
474            if predicate(&x) {
475                return COption::Some(x);
476            }
477        }
478        COption::None
479    }
480
481    /// Returns the option if it contains a value, otherwise returns `optb`.
482    ///
483    /// Arguments passed to `or` are eagerly evaluated; if you are passing the
484    /// result of a function call, it is recommended to use [`or_else`], which is
485    /// lazily evaluated.
486    ///
487    /// [`or_else`]: #method.or_else
488    ///
489    /// # Examples
490    ///
491    /// ```ignore
492    /// let x = COption::Some(2);
493    /// let y = COption::None;
494    /// assert_eq!(x.or(y), COption::Some(2));
495    ///
496    /// let x = COption::None;
497    /// let y = COption::Some(100);
498    /// assert_eq!(x.or(y), COption::Some(100));
499    ///
500    /// let x = COption::Some(2);
501    /// let y = COption::Some(100);
502    /// assert_eq!(x.or(y), COption::Some(2));
503    ///
504    /// let x: COption<u32> = COption::None;
505    /// let y = COption::None;
506    /// assert_eq!(x.or(y), COption::None);
507    /// ```
508    #[inline]
509    pub fn or(self, optb: COption<T>) -> COption<T> {
510        match self {
511            COption::Some(_) => self,
512            COption::None => optb,
513        }
514    }
515
516    /// Returns the option if it contains a value, otherwise calls `f` and
517    /// returns the result.
518    ///
519    /// # Examples
520    ///
521    /// ```ignore
522    /// fn nobody() -> COption<&'static str> { COption::None }
523    /// fn vikings() -> COption<&'static str> { COption::Some("vikings") }
524    ///
525    /// assert_eq!(COption::Some("barbarians").or_else(vikings), COption::Some("barbarians"));
526    /// assert_eq!(COption::None.or_else(vikings), COption::Some("vikings"));
527    /// assert_eq!(COption::None.or_else(nobody), COption::None);
528    /// ```
529    #[inline]
530    pub fn or_else<F: FnOnce() -> COption<T>>(self, f: F) -> COption<T> {
531        match self {
532            COption::Some(_) => self,
533            COption::None => f(),
534        }
535    }
536
537    /// Returns [`COption::Some`] if exactly one of `self`, `optb` is [`COption::Some`], otherwise returns [`COption::None`].
538    ///
539    /// [`COption::Some`]: #variant.COption::Some
540    /// [`COption::None`]: #variant.COption::None
541    ///
542    /// # Examples
543    ///
544    /// ```ignore
545    /// let x = COption::Some(2);
546    /// let y: COption<u32> = COption::None;
547    /// assert_eq!(x.xor(y), COption::Some(2));
548    ///
549    /// let x: COption<u32> = COption::None;
550    /// let y = COption::Some(2);
551    /// assert_eq!(x.xor(y), COption::Some(2));
552    ///
553    /// let x = COption::Some(2);
554    /// let y = COption::Some(2);
555    /// assert_eq!(x.xor(y), COption::None);
556    ///
557    /// let x: COption<u32> = COption::None;
558    /// let y: COption<u32> = COption::None;
559    /// assert_eq!(x.xor(y), COption::None);
560    /// ```
561    #[inline]
562    pub fn xor(self, optb: COption<T>) -> COption<T> {
563        match (self, optb) {
564            (COption::Some(a), COption::None) => COption::Some(a),
565            (COption::None, COption::Some(b)) => COption::Some(b),
566            _ => COption::None,
567        }
568    }
569
570    /////////////////////////////////////////////////////////////////////////
571    // Entry-like operations to insert if COption::None and return a reference
572    /////////////////////////////////////////////////////////////////////////
573
574    /// Inserts `v` into the option if it is [`COption::None`], then
575    /// returns a mutable reference to the contained value.
576    ///
577    /// [`COption::None`]: #variant.COption::None
578    ///
579    /// # Examples
580    ///
581    /// ```ignore
582    /// let mut x = COption::None;
583    ///
584    /// {
585    ///     let y: &mut u32 = x.get_or_insert(5);
586    ///     assert_eq!(y, &5);
587    ///
588    ///     *y = 7;
589    /// }
590    ///
591    /// assert_eq!(x, COption::Some(7));
592    /// ```
593    #[inline]
594    pub fn get_or_insert(&mut self, v: T) -> &mut T {
595        self.get_or_insert_with(|| v)
596    }
597
598    /// Inserts a value computed from `f` into the option if it is [`COption::None`], then
599    /// returns a mutable reference to the contained value.
600    ///
601    /// [`COption::None`]: #variant.COption::None
602    ///
603    /// # Examples
604    ///
605    /// ```ignore
606    /// let mut x = COption::None;
607    ///
608    /// {
609    ///     let y: &mut u32 = x.get_or_insert_with(|| 5);
610    ///     assert_eq!(y, &5);
611    ///
612    ///     *y = 7;
613    /// }
614    ///
615    /// assert_eq!(x, COption::Some(7));
616    /// ```
617    #[inline]
618    pub fn get_or_insert_with<F: FnOnce() -> T>(&mut self, f: F) -> &mut T {
619        if let COption::None = *self {
620            *self = COption::Some(f())
621        }
622
623        match *self {
624            COption::Some(ref mut v) => v,
625            COption::None => unreachable!(),
626        }
627    }
628
629    /////////////////////////////////////////////////////////////////////////
630    // Misc
631    /////////////////////////////////////////////////////////////////////////
632
633    /// Replaces the actual value in the option by the value given in parameter,
634    /// returning the old value if present,
635    /// leaving a [`COption::Some`] in its place without deinitializing either one.
636    ///
637    /// [`COption::Some`]: #variant.COption::Some
638    ///
639    /// # Examples
640    ///
641    /// ```ignore
642    /// let mut x = COption::Some(2);
643    /// let old = x.replace(5);
644    /// assert_eq!(x, COption::Some(5));
645    /// assert_eq!(old, COption::Some(2));
646    ///
647    /// let mut x = COption::None;
648    /// let old = x.replace(3);
649    /// assert_eq!(x, COption::Some(3));
650    /// assert_eq!(old, COption::None);
651    /// ```
652    #[inline]
653    pub fn replace(&mut self, value: T) -> COption<T> {
654        mem::replace(self, COption::Some(value))
655    }
656}
657
658impl<T: Copy> COption<&T> {
659    /// Maps an `COption<&T>` to an `COption<T>` by copying the contents of the
660    /// option.
661    ///
662    /// # Examples
663    ///
664    /// ```ignore
665    /// let x = 12;
666    /// let opt_x = COption::Some(&x);
667    /// assert_eq!(opt_x, COption::Some(&12));
668    /// let copied = opt_x.copied();
669    /// assert_eq!(copied, COption::Some(12));
670    /// ```
671    pub fn copied(self) -> COption<T> {
672        self.map(|&t| t)
673    }
674}
675
676impl<T: Copy> COption<&mut T> {
677    /// Maps an `COption<&mut T>` to an `COption<T>` by copying the contents of the
678    /// option.
679    ///
680    /// # Examples
681    ///
682    /// ```ignore
683    /// let mut x = 12;
684    /// let opt_x = COption::Some(&mut x);
685    /// assert_eq!(opt_x, COption::Some(&mut 12));
686    /// let copied = opt_x.copied();
687    /// assert_eq!(copied, COption::Some(12));
688    /// ```
689    pub fn copied(self) -> COption<T> {
690        self.map(|&mut t| t)
691    }
692}
693
694impl<T: Clone> COption<&T> {
695    /// Maps an `COption<&T>` to an `COption<T>` by cloning the contents of the
696    /// option.
697    ///
698    /// # Examples
699    ///
700    /// ```ignore
701    /// let x = 12;
702    /// let opt_x = COption::Some(&x);
703    /// assert_eq!(opt_x, COption::Some(&12));
704    /// let cloned = opt_x.cloned();
705    /// assert_eq!(cloned, COption::Some(12));
706    /// ```
707    pub fn cloned(self) -> COption<T> {
708        self.map(|t| t.clone())
709    }
710}
711
712impl<T: Clone> COption<&mut T> {
713    /// Maps an `COption<&mut T>` to an `COption<T>` by cloning the contents of the
714    /// option.
715    ///
716    /// # Examples
717    ///
718    /// ```ignore
719    /// let mut x = 12;
720    /// let opt_x = COption::Some(&mut x);
721    /// assert_eq!(opt_x, COption::Some(&mut 12));
722    /// let cloned = opt_x.cloned();
723    /// assert_eq!(cloned, COption::Some(12));
724    /// ```
725    pub fn cloned(self) -> COption<T> {
726        self.map(|t| t.clone())
727    }
728}
729
730impl<T: Default> COption<T> {
731    /// Returns the contained value or a default
732    ///
733    /// Consumes the `self` argument then, if [`COption::Some`], returns the contained
734    /// value, otherwise if [`COption::None`], returns the [default value] for that
735    /// type.
736    ///
737    /// # Examples
738    ///
739    /// Converts a string to an integer, turning poorly-formed strings
740    /// into 0 (the default value for integers). [`parse`] converts
741    /// a string to any other type that implements [`FromStr`], returning
742    /// [`COption::None`] on error.
743    ///
744    /// ```ignore
745    /// let good_year_from_input = "1909";
746    /// let bad_year_from_input = "190blarg";
747    /// let good_year = good_year_from_input.parse().ok().unwrap_or_default();
748    /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();
749    ///
750    /// assert_eq!(1909, good_year);
751    /// assert_eq!(0, bad_year);
752    /// ```
753    ///
754    /// [`COption::Some`]: #variant.COption::Some
755    /// [`COption::None`]: #variant.COption::None
756    /// [default value]: ../default/trait.Default.html#tymethod.default
757    /// [`parse`]: ../../std/primitive.str.html#method.parse
758    /// [`FromStr`]: ../../std/str/trait.FromStr.html
759    #[inline]
760    pub fn unwrap_or_default(self) -> T {
761        match self {
762            COption::Some(x) => x,
763            COption::None => T::default(),
764        }
765    }
766}
767
768impl<T: Deref> COption<T> {
769    /// Converts from `COption<T>` (or `&COption<T>`) to `COption<&T::Target>`.
770    ///
771    /// Leaves the original COption in-place, creating a new one with a reference
772    /// to the original one, additionally coercing the contents via [`Deref`].
773    ///
774    /// [`Deref`]: ../../std/ops/trait.Deref.html
775    ///
776    /// # Examples
777    ///
778    /// ```ignore
779    /// #![feature(inner_deref)]
780    ///
781    /// let x: COption<String> = COption::Some("hey".to_owned());
782    /// assert_eq!(x.as_deref(), COption::Some("hey"));
783    ///
784    /// let x: COption<String> = COption::None;
785    /// assert_eq!(x.as_deref(), COption::None);
786    /// ```
787    pub fn as_deref(&self) -> COption<&T::Target> {
788        self.as_ref().map(|t| t.deref())
789    }
790}
791
792impl<T: DerefMut> COption<T> {
793    /// Converts from `COption<T>` (or `&mut COption<T>`) to `COption<&mut T::Target>`.
794    ///
795    /// Leaves the original `COption` in-place, creating a new one containing a mutable reference to
796    /// the inner type's `Deref::Target` type.
797    ///
798    /// # Examples
799    ///
800    /// ```ignore
801    /// #![feature(inner_deref)]
802    ///
803    /// let mut x: COption<String> = COption::Some("hey".to_owned());
804    /// assert_eq!(x.as_deref_mut().map(|x| {
805    ///     x.make_ascii_uppercase();
806    ///     x
807    /// }), COption::Some("HEY".to_owned().as_mut_str()));
808    /// ```
809    pub fn as_deref_mut(&mut self) -> COption<&mut T::Target> {
810        self.as_mut().map(|t| t.deref_mut())
811    }
812}
813
814impl<T, E> COption<Result<T, E>> {
815    /// Transposes an `COption` of a [`Result`] into a [`Result`] of an `COption`.
816    ///
817    /// [`COption::None`] will be mapped to [`Ok`]`(`[`COption::None`]`)`.
818    /// [`COption::Some`]`(`[`Ok`]`(_))` and [`COption::Some`]`(`[`Err`]`(_))` will be mapped to
819    /// [`Ok`]`(`[`COption::Some`]`(_))` and [`Err`]`(_)`.
820    ///
821    /// [`COption::None`]: #variant.COption::None
822    /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
823    /// [`COption::Some`]: #variant.COption::Some
824    /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
825    ///
826    /// # Examples
827    ///
828    /// ```ignore
829    /// #[derive(Debug, Eq, PartialEq)]
830    /// struct COption::SomeErr;
831    ///
832    /// let x: Result<COption<i32>, COption::SomeErr> = Ok(COption::Some(5));
833    /// let y: COption<Result<i32, COption::SomeErr>> = COption::Some(Ok(5));
834    /// assert_eq!(x, y.transpose());
835    /// ```
836    #[inline]
837    pub fn transpose(self) -> Result<COption<T>, E> {
838        match self {
839            COption::Some(Ok(x)) => Ok(COption::Some(x)),
840            COption::Some(Err(e)) => Err(e),
841            COption::None => Ok(COption::None),
842        }
843    }
844}
845
846// This is a separate function to reduce the code size of .expect() itself.
847#[inline(never)]
848#[cold]
849fn expect_failed(msg: &str) -> ! {
850    panic!("{}", msg)
851}
852
853// // This is a separate function to reduce the code size of .expect_none() itself.
854// #[inline(never)]
855// #[cold]
856// fn expect_none_failed(msg: &str, value: &dyn fmt::Debug) -> ! {
857//     panic!("{}: {:?}", msg, value)
858// }
859
860/////////////////////////////////////////////////////////////////////////////
861// Trait implementations
862/////////////////////////////////////////////////////////////////////////////
863
864impl<T: Clone> Clone for COption<T> {
865    #[inline]
866    fn clone(&self) -> Self {
867        match self {
868            COption::Some(x) => COption::Some(x.clone()),
869            COption::None => COption::None,
870        }
871    }
872
873    #[inline]
874    fn clone_from(&mut self, source: &Self) {
875        match (self, source) {
876            (COption::Some(to), COption::Some(from)) => to.clone_from(from),
877            (to, from) => *to = from.clone(),
878        }
879    }
880}
881
882impl<T> Default for COption<T> {
883    /// Returns [`COption::None`][COption::None].
884    ///
885    /// # Examples
886    ///
887    /// ```ignore
888    /// let opt: COption<u32> = COption::default();
889    /// assert!(opt.is_none());
890    /// ```
891    #[inline]
892    fn default() -> COption<T> {
893        COption::None
894    }
895}
896
897impl<T> From<T> for COption<T> {
898    fn from(val: T) -> COption<T> {
899        COption::Some(val)
900    }
901}
902
903impl<'a, T> From<&'a COption<T>> for COption<&'a T> {
904    fn from(o: &'a COption<T>) -> COption<&'a T> {
905        o.as_ref()
906    }
907}
908
909impl<'a, T> From<&'a mut COption<T>> for COption<&'a mut T> {
910    fn from(o: &'a mut COption<T>) -> COption<&'a mut T> {
911        o.as_mut()
912    }
913}
914
915impl<T> COption<COption<T>> {
916    /// Converts from `COption<COption<T>>` to `COption<T>`
917    ///
918    /// # Examples
919    /// Basic usage:
920    /// ```ignore
921    /// #![feature(option_flattening)]
922    /// let x: COption<COption<u32>> = COption::Some(COption::Some(6));
923    /// assert_eq!(COption::Some(6), x.flatten());
924    ///
925    /// let x: COption<COption<u32>> = COption::Some(COption::None);
926    /// assert_eq!(COption::None, x.flatten());
927    ///
928    /// let x: COption<COption<u32>> = COption::None;
929    /// assert_eq!(COption::None, x.flatten());
930    /// ```
931    /// Flattening once only removes one level of nesting:
932    /// ```ignore
933    /// #![feature(option_flattening)]
934    /// let x: COption<COption<COption<u32>>> = COption::Some(COption::Some(COption::Some(6)));
935    /// assert_eq!(COption::Some(COption::Some(6)), x.flatten());
936    /// assert_eq!(COption::Some(6), x.flatten().flatten());
937    /// ```
938    #[inline]
939    pub fn flatten(self) -> COption<T> {
940        self.and_then(convert::identity)
941    }
942}
943
944impl<T> From<Option<T>> for COption<T> {
945    fn from(option: Option<T>) -> Self {
946        match option {
947            Some(value) => COption::Some(value),
948            None => COption::None,
949        }
950    }
951}
952
953#[rustversion::since(1.49.0)]
954impl<T> From<COption<T>> for Option<T> {
955    fn from(coption: COption<T>) -> Self {
956        match coption {
957            COption::Some(value) => Some(value),
958            COption::None => None,
959        }
960    }
961}
962
963#[rustversion::before(1.49.0)] // Remove `Into` once the BPF toolchain upgrades to 1.49.0 or newer
964impl<T> Into<Option<T>> for COption<T> {
965    fn into(self) -> Option<T> {
966        match self {
967            COption::Some(value) => Some(value),
968            COption::None => None,
969        }
970    }
971}
972
973#[cfg(test)]
974mod test {
975    use super::*;
976
977    #[test]
978    fn test_from_rust_option() {
979        let option = Some(99u64);
980        let c_option: COption<u64> = option.into();
981        assert_eq!(c_option, COption::Some(99u64));
982        let expected = c_option.into();
983        assert_eq!(option, expected);
984
985        let option = None;
986        let c_option: COption<u64> = option.into();
987        assert_eq!(c_option, COption::None);
988        let expected = c_option.into();
989        assert_eq!(option, expected);
990    }
991}