option.rs 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112
  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. // SPL Token-Specific Methods
  645. /////////////////////////////////////////////////////////////////////////
  646. /// Packs a COption into a mutable slice as compactly as possible
  647. #[inline]
  648. pub fn pack(&self, output: &mut [u8], cursor: &mut usize)
  649. where
  650. T: Copy,
  651. {
  652. match self {
  653. COption::Some(some_value) => {
  654. output[*cursor] = 1;
  655. *cursor += mem::size_of::<u8>();
  656. #[allow(clippy::cast_ptr_alignment)]
  657. let value = unsafe { &mut *(&mut output[*cursor] as *mut u8 as *mut T) };
  658. *value = *some_value;
  659. *cursor += mem::size_of::<T>();
  660. }
  661. COption::None => {
  662. output[*cursor] = 0;
  663. *cursor += mem::size_of::<u8>();
  664. }
  665. }
  666. }
  667. /// Unpacks a COption from a compact slice
  668. #[inline]
  669. pub fn unpack_or<E>(input: &[u8], cursor: &mut usize, error: E) -> Result<COption<T>, E>
  670. where
  671. T: Copy,
  672. {
  673. match input[*cursor] {
  674. 0 => {
  675. *cursor += mem::size_of::<u8>();
  676. Ok(COption::None)
  677. }
  678. 1 => {
  679. *cursor += mem::size_of::<u8>();
  680. #[allow(clippy::cast_ptr_alignment)]
  681. let result = unsafe { *(&input[*cursor] as *const u8 as *const T) };
  682. *cursor += mem::size_of::<T>();
  683. Ok(COption::Some(result))
  684. }
  685. _ => Err(error),
  686. }
  687. }
  688. }
  689. impl<T: Copy> COption<&T> {
  690. /// Maps an `COption<&T>` to an `COption<T>` by copying the contents of the
  691. /// option.
  692. ///
  693. /// # Examples
  694. ///
  695. /// ```ignore
  696. /// let x = 12;
  697. /// let opt_x = COption::Some(&x);
  698. /// assert_eq!(opt_x, COption::Some(&12));
  699. /// let copied = opt_x.copied();
  700. /// assert_eq!(copied, COption::Some(12));
  701. /// ```
  702. pub fn copied(self) -> COption<T> {
  703. self.map(|&t| t)
  704. }
  705. }
  706. impl<T: Copy> COption<&mut T> {
  707. /// Maps an `COption<&mut T>` to an `COption<T>` by copying the contents of the
  708. /// option.
  709. ///
  710. /// # Examples
  711. ///
  712. /// ```ignore
  713. /// let mut x = 12;
  714. /// let opt_x = COption::Some(&mut x);
  715. /// assert_eq!(opt_x, COption::Some(&mut 12));
  716. /// let copied = opt_x.copied();
  717. /// assert_eq!(copied, COption::Some(12));
  718. /// ```
  719. pub fn copied(self) -> COption<T> {
  720. self.map(|&mut t| t)
  721. }
  722. }
  723. impl<T: Clone> COption<&T> {
  724. /// Maps an `COption<&T>` to an `COption<T>` by cloning the contents of the
  725. /// option.
  726. ///
  727. /// # Examples
  728. ///
  729. /// ```ignore
  730. /// let x = 12;
  731. /// let opt_x = COption::Some(&x);
  732. /// assert_eq!(opt_x, COption::Some(&12));
  733. /// let cloned = opt_x.cloned();
  734. /// assert_eq!(cloned, COption::Some(12));
  735. /// ```
  736. pub fn cloned(self) -> COption<T> {
  737. self.map(|t| t.clone())
  738. }
  739. }
  740. impl<T: Clone> COption<&mut T> {
  741. /// Maps an `COption<&mut T>` to an `COption<T>` by cloning the contents of the
  742. /// option.
  743. ///
  744. /// # Examples
  745. ///
  746. /// ```ignore
  747. /// let mut x = 12;
  748. /// let opt_x = COption::Some(&mut x);
  749. /// assert_eq!(opt_x, COption::Some(&mut 12));
  750. /// let cloned = opt_x.cloned();
  751. /// assert_eq!(cloned, COption::Some(12));
  752. /// ```
  753. pub fn cloned(self) -> COption<T> {
  754. self.map(|t| t.clone())
  755. }
  756. }
  757. impl<T: Default> COption<T> {
  758. /// Returns the contained value or a default
  759. ///
  760. /// Consumes the `self` argument then, if [`COption::Some`], returns the contained
  761. /// value, otherwise if [`COption::None`], returns the [default value] for that
  762. /// type.
  763. ///
  764. /// # Examples
  765. ///
  766. /// Converts a string to an integer, turning poorly-formed strings
  767. /// into 0 (the default value for integers). [`parse`] converts
  768. /// a string to any other type that implements [`FromStr`], returning
  769. /// [`COption::None`] on error.
  770. ///
  771. /// ```ignore
  772. /// let good_year_from_input = "1909";
  773. /// let bad_year_from_input = "190blarg";
  774. /// let good_year = good_year_from_input.parse().ok().unwrap_or_default();
  775. /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();
  776. ///
  777. /// assert_eq!(1909, good_year);
  778. /// assert_eq!(0, bad_year);
  779. /// ```
  780. ///
  781. /// [`COption::Some`]: #variant.COption::Some
  782. /// [`COption::None`]: #variant.COption::None
  783. /// [default value]: ../default/trait.Default.html#tymethod.default
  784. /// [`parse`]: ../../std/primitive.str.html#method.parse
  785. /// [`FromStr`]: ../../std/str/trait.FromStr.html
  786. #[inline]
  787. pub fn unwrap_or_default(self) -> T {
  788. match self {
  789. COption::Some(x) => x,
  790. COption::None => Default::default(),
  791. }
  792. }
  793. }
  794. impl<T: Deref> COption<T> {
  795. /// Converts from `COption<T>` (or `&COption<T>`) to `COption<&T::Target>`.
  796. ///
  797. /// Leaves the original COption in-place, creating a new one with a reference
  798. /// to the original one, additionally coercing the contents via [`Deref`].
  799. ///
  800. /// [`Deref`]: ../../std/ops/trait.Deref.html
  801. ///
  802. /// # Examples
  803. ///
  804. /// ```ignore
  805. /// #![feature(inner_deref)]
  806. ///
  807. /// let x: COption<String> = COption::Some("hey".to_owned());
  808. /// assert_eq!(x.as_deref(), COption::Some("hey"));
  809. ///
  810. /// let x: COption<String> = COption::None;
  811. /// assert_eq!(x.as_deref(), COption::None);
  812. /// ```
  813. pub fn as_deref(&self) -> COption<&T::Target> {
  814. self.as_ref().map(|t| t.deref())
  815. }
  816. }
  817. impl<T: DerefMut> COption<T> {
  818. /// Converts from `COption<T>` (or `&mut COption<T>`) to `COption<&mut T::Target>`.
  819. ///
  820. /// Leaves the original `COption` in-place, creating a new one containing a mutable reference to
  821. /// the inner type's `Deref::Target` type.
  822. ///
  823. /// # Examples
  824. ///
  825. /// ```ignore
  826. /// #![feature(inner_deref)]
  827. ///
  828. /// let mut x: COption<String> = COption::Some("hey".to_owned());
  829. /// assert_eq!(x.as_deref_mut().map(|x| {
  830. /// x.make_ascii_uppercase();
  831. /// x
  832. /// }), COption::Some("HEY".to_owned().as_mut_str()));
  833. /// ```
  834. pub fn as_deref_mut(&mut self) -> COption<&mut T::Target> {
  835. self.as_mut().map(|t| t.deref_mut())
  836. }
  837. }
  838. impl<T, E> COption<Result<T, E>> {
  839. /// Transposes an `COption` of a [`Result`] into a [`Result`] of an `COption`.
  840. ///
  841. /// [`COption::None`] will be mapped to [`Ok`]`(`[`COption::None`]`)`.
  842. /// [`COption::Some`]`(`[`Ok`]`(_))` and [`COption::Some`]`(`[`Err`]`(_))` will be mapped to
  843. /// [`Ok`]`(`[`COption::Some`]`(_))` and [`Err`]`(_)`.
  844. ///
  845. /// [`COption::None`]: #variant.COption::None
  846. /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
  847. /// [`COption::Some`]: #variant.COption::Some
  848. /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
  849. ///
  850. /// # Examples
  851. ///
  852. /// ```ignore
  853. /// #[derive(Debug, Eq, PartialEq)]
  854. /// struct COption::SomeErr;
  855. ///
  856. /// let x: Result<COption<i32>, COption::SomeErr> = Ok(COption::Some(5));
  857. /// let y: COption<Result<i32, COption::SomeErr>> = COption::Some(Ok(5));
  858. /// assert_eq!(x, y.transpose());
  859. /// ```
  860. #[inline]
  861. pub fn transpose(self) -> Result<COption<T>, E> {
  862. match self {
  863. COption::Some(Ok(x)) => Ok(COption::Some(x)),
  864. COption::Some(Err(e)) => Err(e),
  865. COption::None => Ok(COption::None),
  866. }
  867. }
  868. }
  869. // This is a separate function to reduce the code size of .expect() itself.
  870. #[inline(never)]
  871. #[cold]
  872. fn expect_failed(msg: &str) -> ! {
  873. panic!("{}", msg)
  874. }
  875. // // This is a separate function to reduce the code size of .expect_none() itself.
  876. // #[inline(never)]
  877. // #[cold]
  878. // fn expect_none_failed(msg: &str, value: &dyn fmt::Debug) -> ! {
  879. // panic!("{}: {:?}", msg, value)
  880. // }
  881. /////////////////////////////////////////////////////////////////////////////
  882. // Trait implementations
  883. /////////////////////////////////////////////////////////////////////////////
  884. impl<T: Clone> Clone for COption<T> {
  885. #[inline]
  886. fn clone(&self) -> Self {
  887. match self {
  888. COption::Some(x) => COption::Some(x.clone()),
  889. COption::None => COption::None,
  890. }
  891. }
  892. #[inline]
  893. fn clone_from(&mut self, source: &Self) {
  894. match (self, source) {
  895. (COption::Some(to), COption::Some(from)) => to.clone_from(from),
  896. (to, from) => *to = from.clone(),
  897. }
  898. }
  899. }
  900. impl<T> Default for COption<T> {
  901. /// Returns [`COption::None`][COption::COption::None].
  902. ///
  903. /// # Examples
  904. ///
  905. /// ```ignore
  906. /// let opt: COption<u32> = COption::default();
  907. /// assert!(opt.is_none());
  908. /// ```
  909. #[inline]
  910. fn default() -> COption<T> {
  911. COption::None
  912. }
  913. }
  914. impl<T> From<T> for COption<T> {
  915. fn from(val: T) -> COption<T> {
  916. COption::Some(val)
  917. }
  918. }
  919. impl<'a, T> From<&'a COption<T>> for COption<&'a T> {
  920. fn from(o: &'a COption<T>) -> COption<&'a T> {
  921. o.as_ref()
  922. }
  923. }
  924. impl<'a, T> From<&'a mut COption<T>> for COption<&'a mut T> {
  925. fn from(o: &'a mut COption<T>) -> COption<&'a mut T> {
  926. o.as_mut()
  927. }
  928. }
  929. impl<T> COption<COption<T>> {
  930. /// Converts from `COption<COption<T>>` to `COption<T>`
  931. ///
  932. /// # Examples
  933. /// Basic usage:
  934. /// ```ignore
  935. /// #![feature(option_flattening)]
  936. /// let x: COption<COption<u32>> = COption::Some(COption::Some(6));
  937. /// assert_eq!(COption::Some(6), x.flatten());
  938. ///
  939. /// let x: COption<COption<u32>> = COption::Some(COption::None);
  940. /// assert_eq!(COption::None, x.flatten());
  941. ///
  942. /// let x: COption<COption<u32>> = COption::None;
  943. /// assert_eq!(COption::None, x.flatten());
  944. /// ```
  945. /// Flattening once only removes one level of nesting:
  946. /// ```ignore
  947. /// #![feature(option_flattening)]
  948. /// let x: COption<COption<COption<u32>>> = COption::Some(COption::Some(COption::Some(6)));
  949. /// assert_eq!(COption::Some(COption::Some(6)), x.flatten());
  950. /// assert_eq!(COption::Some(6), x.flatten().flatten());
  951. /// ```
  952. #[inline]
  953. pub fn flatten(self) -> COption<T> {
  954. self.and_then(convert::identity)
  955. }
  956. }
  957. impl<T> From<Option<T>> for COption<T> {
  958. fn from(option: Option<T>) -> Self {
  959. match option {
  960. Some(value) => COption::Some(value),
  961. None => COption::None,
  962. }
  963. }
  964. }
  965. impl<T> Into<Option<T>> for COption<T> {
  966. fn into(self) -> Option<T> {
  967. match self {
  968. COption::Some(value) => Some(value),
  969. COption::None => None,
  970. }
  971. }
  972. }
  973. #[cfg(test)]
  974. mod test {
  975. use super::*;
  976. use solana_sdk::pubkey::Pubkey;
  977. #[test]
  978. fn test_from_rust_option() {
  979. let option = Some(99u64);
  980. let c_option: COption<u64> = option.into();
  981. assert_eq!(c_option, COption::Some(99u64));
  982. let expected = c_option.into();
  983. assert_eq!(option, expected);
  984. let option = None;
  985. let c_option: COption<u64> = option.into();
  986. assert_eq!(c_option, COption::None);
  987. let expected = c_option.into();
  988. assert_eq!(option, expected);
  989. }
  990. #[test]
  991. fn test_coption_packing() {
  992. // Solana Pubkey
  993. let option_pubkey = COption::Some(Pubkey::new(&[2u8; 32]));
  994. let expected_size = mem::size_of::<u8>() + mem::size_of::<Pubkey>();
  995. let mut output = vec![0u8; expected_size];
  996. let mut cursor = 0;
  997. option_pubkey.pack(&mut output, &mut cursor);
  998. let mut expected = vec![1u8];
  999. expected.extend_from_slice(&[2u8; 32]);
  1000. assert_eq!(output, expected);
  1001. let mut cursor = 0;
  1002. let unpacked = COption::unpack_or(&expected, &mut cursor, "Error".to_string()).unwrap();
  1003. assert_eq!(unpacked, option_pubkey);
  1004. let option_pubkey: COption<Pubkey> = COption::None;
  1005. let expected_size = mem::size_of::<u8>();
  1006. let mut output = vec![0u8; expected_size];
  1007. let mut cursor = 0;
  1008. option_pubkey.pack(&mut output, &mut cursor);
  1009. let expected = vec![0u8];
  1010. assert_eq!(output, expected);
  1011. let mut cursor = 0;
  1012. let unpacked = COption::unpack_or(&expected, &mut cursor, "Error".to_string()).unwrap();
  1013. assert_eq!(unpacked, option_pubkey);
  1014. // u64
  1015. let option_pubkey = COption::Some(99u64);
  1016. let expected_size = mem::size_of::<u8>() + mem::size_of::<u64>();
  1017. let mut output = vec![0u8; expected_size];
  1018. let mut cursor = 0;
  1019. option_pubkey.pack(&mut output, &mut cursor);
  1020. let mut expected = vec![1u8];
  1021. expected.extend_from_slice(&[99, 0, 0, 0, 0, 0, 0, 0]);
  1022. assert_eq!(output, expected);
  1023. let mut cursor = 0;
  1024. let unpacked = COption::unpack_or(&expected, &mut cursor, "Error".to_string()).unwrap();
  1025. assert_eq!(unpacked, option_pubkey);
  1026. let option_pubkey: COption<u64> = COption::None;
  1027. let expected_size = mem::size_of::<u8>();
  1028. let mut output = vec![0u8; expected_size];
  1029. let mut cursor = 0;
  1030. option_pubkey.pack(&mut output, &mut cursor);
  1031. let expected = vec![0u8];
  1032. assert_eq!(output, expected);
  1033. let mut cursor = 0;
  1034. let unpacked = COption::unpack_or(&expected, &mut cursor, "Error".to_string()).unwrap();
  1035. assert_eq!(unpacked, option_pubkey);
  1036. }
  1037. }