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