option.rs 30 KB

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