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