Skip to main content

solana_program_option/
lib.rs

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