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