for_sure/lib.rs
1#![doc = include_str!("../README.md")]
2#![cfg_attr(not(feature = "std"), no_std)]
3
4use Almost::{Nil, Value};
5use core::{
6 fmt,
7 iter::FusedIterator,
8 mem,
9 ops::{Deref, DerefMut},
10 pin::Pin,
11 slice,
12};
13
14pub mod prelude {
15 pub use super::Almost::{self, Nil, Value};
16}
17
18/// A type similar to [`Option`] but with [`Deref<Target = T>`] implementation.
19/// See crate-level documentation for more info.
20#[derive(PartialEq, Default, PartialOrd, Eq, Ord, Copy, Hash)]
21pub enum Almost<T> {
22 #[default]
23 Nil,
24 Value(T),
25}
26
27impl<T> Almost<T> {
28 /// Returns `true` if the almost is a [`Value`] value.
29 ///
30 /// # Examples
31 ///
32 /// ```
33 /// # use for_sure::prelude::*;
34 /// let x: Almost<u32> = Value(2);
35 /// assert!(Almost::is_value(&x));
36 ///
37 /// let x: Almost<u32> = Nil;
38 /// assert!(Almost::is_nil(&x));
39 /// ```
40 #[must_use = "if you intended to assert that this has a value, consider `Almost::unwrap()` instead"]
41 #[inline]
42 pub const fn is_value(this: &Self) -> bool {
43 matches!(this, Value(..))
44 }
45
46 /// Returns `true` if the almost is a [`Value`] and the value inside of it matches a predicate.
47 ///
48 /// # Examples
49 ///
50 /// ```
51 /// # use for_sure::prelude::*;
52 /// let x: Almost<u32> = Value(2);
53 /// assert!(Almost::is_value_and(x, |x| x > 1));
54 ///
55 /// let x: Almost<u32> = Value(0);
56 /// assert!(!Almost::is_value_and(x, |x| x > 1));
57 ///
58 /// let x: Almost<u32> = Nil;
59 /// assert!(!Almost::is_value_and(x, |x| x > 1));
60 ///
61 /// let x: Almost<String> = Value("ownership".to_string());
62 /// assert!(Almost::is_value_and(Almost::as_ref(&x), |x| x.len() > 1));
63 /// println!("still alive {:?}", x);
64 /// ```
65 #[must_use]
66 #[inline]
67 pub fn is_value_and(this: Self, f: impl FnOnce(T) -> bool) -> bool {
68 match this {
69 Nil => false,
70 Value(x) => f(x),
71 }
72 }
73
74 /// Returns `true` if the almost is a [`Value`] value.
75 ///
76 /// # Examples
77 ///
78 /// ```
79 /// # use for_sure::prelude::*;
80 /// let x: Almost<u32> = Value(2);
81 /// assert!(!Almost::is_nil(&x));
82 ///
83 /// let x: Almost<u32> = Nil;
84 /// assert!(Almost::is_nil(&x));
85 /// ```
86 #[must_use = "if you intended to assert that this doesn't have a value, consider \
87 wrapping this in an `assert!()` instead"]
88 #[inline]
89 pub const fn is_nil(this: &Self) -> bool {
90 matches!(this, Nil)
91 }
92
93 /// Returns `true` if the almost is a [`Value`] or the value inside of it matches a predicate.
94 ///
95 /// # Examples
96 ///
97 /// ```
98 /// # use for_sure::prelude::*;
99 /// let x: Almost<u32> = Value(2);
100 /// assert!(Almost::is_nil_or(x, |x| x > 1));
101 ///
102 /// let x: Almost<u32> = Value(0);
103 /// assert!(!Almost::is_nil_or(x, |x| x > 1));
104 ///
105 /// let x: Almost<u32> = Nil;
106 /// assert!(Almost::is_nil_or(x, |x| x > 1));
107 ///
108 /// let x: Almost<String> = Value("ownership".to_string());
109 /// assert!(Almost::is_nil_or(Almost::as_ref(&x), |x| x.len() > 1));
110 /// println!("still alive {:?}", x);
111 /// ```
112 #[must_use]
113 #[inline]
114 pub fn is_nil_or(this: Self, f: impl FnOnce(T) -> bool) -> bool {
115 match this {
116 Nil => true,
117 Value(x) => f(x),
118 }
119 }
120
121 /// Converts from `&Almost<T>` to `Almost<&T>`
122 #[inline]
123 pub const fn as_ref(this: &Self) -> Almost<&T> {
124 match this {
125 Nil => Nil,
126 Value(x) => Value(x),
127 }
128 }
129
130 /// Converts from `&mut Almost<T>` to `Almost<&mut T>`
131 ///
132 /// # Examples
133 ///
134 /// ```
135 /// # use for_sure::prelude::*;
136 /// let mut x = Value(2);
137 /// match Almost::as_mut(&mut x) {
138 /// Value(v) => *v = 42,
139 /// Nil => {},
140 /// }
141 /// assert_eq!(x, Value(42));
142 /// ```
143 #[inline]
144 pub const fn as_mut(this: &mut Self) -> Almost<&mut T> {
145 match this {
146 Nil => Nil,
147 Value(x) => Value(x),
148 }
149 }
150
151 /// Converts from `Pin<&Almost<T>>` to `Almost<Pin<&T>>`
152 #[inline]
153 pub const fn as_pin_ref(this: Pin<&Self>) -> Almost<Pin<&T>> {
154 match Self::as_ref(Pin::get_ref(this)) {
155 Value(x) => Value(unsafe { Pin::new_unchecked(x) }),
156 Nil => Nil,
157 }
158 }
159
160 /// Converts from `Pin<&mut Almost<T>>` to `Almost<Pin<&mut T>>`
161 #[inline]
162 pub const fn as_pin_mut(this: Pin<&mut Self>) -> Almost<Pin<&mut T>> {
163 match Self::as_mut(unsafe { Pin::get_unchecked_mut(this) }) {
164 Value(x) => Value(unsafe { Pin::new_unchecked(x) }),
165 Nil => Nil,
166 }
167 }
168
169 /// Returns a slice of the contained value, if any. If this is [`Nil`], an
170 /// empty slice is returned. This can be useful to have a single type of
171 /// iterator over an [`Almost`] or slice.
172 ///
173 /// Note: Should you have an `Almost<&T>` and wish to get a slice of `T`,
174 /// you can unpack it via `Almost::map_or(opt, &[], std::slice::from_ref)`.
175 ///
176 /// # Examples
177 ///
178 /// ```
179 /// # use for_sure::prelude::*;
180 /// assert_eq!(Almost::as_slice(&Value(1234)), &[1234][..]);
181 /// assert_eq!(Almost::as_slice(&Nil::<i32>), &[][..]);
182 /// ```
183 #[inline]
184 #[must_use]
185 pub const fn as_slice(this: &Self) -> &[T] {
186 match this {
187 Value(value) => unsafe { slice::from_raw_parts(&raw const *value, 1) },
188 Nil => &[],
189 }
190 }
191
192 /// Returns a mutable slice of the contained value, if any. If this is [`Nil`], an
193 /// empty slice is returned. This can be useful to have a single type of
194 /// iterator over an [`Almost`] or slice.
195 ///
196 /// # Examples
197 ///
198 /// ```
199 /// # use for_sure::prelude::*;
200 /// assert_eq!(Almost::as_slice_mut(&mut Value(1234)), &mut [1234][..]);
201 /// assert_eq!(Almost::as_slice_mut(&mut Nil::<i32>), &mut [][..]);
202 /// ```
203 #[inline]
204 #[must_use]
205 pub const fn as_slice_mut(this: &mut Self) -> &mut [T] {
206 match this {
207 Value(value) => unsafe { slice::from_raw_parts_mut(&raw mut *value, 1) },
208 Nil => &mut [],
209 }
210 }
211
212 /// Returns the contained [`Value`] value, consuming the `self` value.
213 ///
214 /// # Panics
215 ///
216 /// Panics if the value is a [`Nil`] with a custom panic message provided by
217 /// `msg`.
218 ///
219 /// # Examples
220 ///
221 /// ```
222 /// # use for_sure::prelude::*;
223 /// let x = Value("value");
224 /// assert_eq!(Almost::expect(x, "fruits are healthy"), "value");
225 /// ```
226 ///
227 /// ```should_panic
228 /// # use for_sure::prelude::*;
229 /// let x: Almost<&str> = Nil;
230 /// Almost::expect(x, "fruits are healthy"); // panics with `fruits are healthy`
231 /// ```
232 ///
233 /// # Recommended Message Style
234 ///
235 /// We recommend that `expect` messages are used to describe the reason you
236 /// _expect_ the `Almost` should be `Value`.
237 ///
238 /// ```should_panic
239 /// # use for_sure::prelude::*;
240 /// # let slice: &[u8] = &[];
241 /// let maybe_item = Almost::from_option(slice.get(0));
242 /// let item = Almost::expect(maybe_item, "slice should not be empty");
243 /// ```
244 #[inline]
245 #[track_caller]
246 pub fn expect(this: Self, msg: &str) -> T {
247 match this {
248 Value(x) => x,
249 Nil => panic!("{}", msg),
250 }
251 }
252
253 /// Returns the contained [`Value`] value, consuming the `self` value.
254 ///
255 /// Because this function may panic, its use is generally discouraged.
256 /// Panics are meant for unrecoverable errors, and may abort the entire program.
257 ///
258 /// Instead, prefer to use pattern matching and handle the [`Nil`]
259 /// case explicitly, or call [`Almost::unwrap_or`], [`Almost::unwrap_or_else`], or
260 /// [`Almost::unwrap_or_default`].
261 ///
262 /// # Panics
263 ///
264 /// Panics if the self value equals [`Nil`].
265 ///
266 /// # Examples
267 ///
268 /// ```
269 /// # use for_sure::prelude::*;
270 /// let x = Value("air");
271 /// assert_eq!(Almost::unwrap(x), "air");
272 /// ```
273 ///
274 /// ```should_panic
275 /// # use for_sure::prelude::*;
276 /// let x: Almost<&str> = Nil;
277 /// assert_eq!(Almost::unwrap(x), "air"); // fails
278 /// ```
279 #[inline(always)]
280 #[track_caller]
281 pub fn unwrap(this: Self) -> T {
282 match this {
283 Value(x) => x,
284 Nil => panic!("called `Almost::unwrap()` on a `Nil` value"),
285 }
286 }
287
288 /// Returns the contained [`Value`] value or a provided default.
289 ///
290 /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
291 /// the result of a function call, it is recommended to use [`Almost::unwrap_or_else`],
292 /// which is lazily evaluated.
293 ///
294 /// # Examples
295 ///
296 /// ```
297 /// # use for_sure::prelude::*;
298 /// assert_eq!(Almost::unwrap_or(Value("car"), "bike"), "car");
299 /// assert_eq!(Almost::unwrap_or(Nil, "bike"), "bike");
300 /// ```
301 #[inline]
302 pub fn unwrap_or(this: Self, default: T) -> T {
303 match this {
304 Value(x) => x,
305 Nil => default,
306 }
307 }
308
309 /// Returns the contained [`Value`] value or computes it from a closure.
310 ///
311 /// # Examples
312 ///
313 /// ```
314 /// # use for_sure::prelude::*;
315 /// let k = 10;
316 /// assert_eq!(Almost::unwrap_or_else(Value(4), || 2 * k), 4);
317 /// assert_eq!(Almost::unwrap_or_else(Nil, || 2 * k), 20);
318 /// ```
319 #[inline]
320 #[track_caller]
321 pub fn unwrap_or_else(this: Self, f: impl FnOnce() -> T) -> T {
322 match this {
323 Value(x) => x,
324 Nil => f(),
325 }
326 }
327
328 /// Returns the contained [`Value`] value or a default.
329 ///
330 /// Consumes the `self` argument then, if [`Value`], returns the contained
331 /// value, otherwise if [`Nil`], returns the [default value] for that
332 /// type.
333 ///
334 /// # Examples
335 ///
336 /// ```
337 /// # use for_sure::prelude::*;
338 /// let x: Almost<u32> = Nil;
339 /// let y: Almost<u32> = Value(12);
340 ///
341 /// assert_eq!(Almost::unwrap_or_default(x), 0);
342 /// assert_eq!(Almost::unwrap_or_default(y), 12);
343 /// ```
344 ///
345 /// [default value]: Default::default
346 #[inline]
347 pub fn unwrap_or_default(this: Self) -> T
348 where
349 T: Default,
350 {
351 match this {
352 Value(x) => x,
353 Nil => T::default(),
354 }
355 }
356
357 /// Returns the contained [`Value`] value, consuming the `self` value,
358 /// without checking that the value is not [`Value`].
359 ///
360 /// # Safety
361 ///
362 /// Calling this method on [`Nil`] is *[undefined behavior]*.
363 ///
364 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
365 ///
366 /// # Examples
367 ///
368 /// ```
369 /// # use for_sure::prelude::*;
370 /// let x = Value("air");
371 /// assert_eq!(unsafe { Almost::unwrap_unchecked(x) }, "air");
372 /// ```
373 ///
374 /// ```no_run
375 /// # use for_sure::prelude::*;
376 /// let x: Almost<&str> = Nil;
377 /// assert_eq!(unsafe { Almost::unwrap_unchecked(x) }, "air"); // Undefined behavior!
378 /// ```
379 #[inline]
380 #[track_caller]
381 pub unsafe fn unwrap_unchecked(this: Self) -> T {
382 match this {
383 Value(x) => x,
384 Nil => unsafe { core::hint::unreachable_unchecked() },
385 }
386 }
387
388 /// Maps an `Almost<T>` to `Almost<U>` by applying a function to a contained value (if `Value`) or returns `Nil` (if `Nil`).
389 ///
390 /// # Examples
391 ///
392 /// Calculates the length of an `Almost<String>` as an `Almost<usize>` consuming the original:
393 ///
394 /// ```
395 /// # use for_sure::prelude::*;
396 /// let maybe_some_string = Value(String::from("Hello, World!"));
397 /// // `Almost::map` takes self *by value*, consuming `maybe_some_string`
398 /// let maybe_some_len = Almost::map(maybe_some_string, |s| s.len());
399 /// assert_eq!(maybe_some_len, Value(13));
400 ///
401 /// let x: Almost<&str> = Nil;
402 /// assert_eq!(Almost::map(x, |s| s.len()), Nil);
403 /// ```
404 #[inline]
405 pub fn map<U>(this: Self, f: impl FnOnce(T) -> U) -> Almost<U> {
406 match this {
407 Value(x) => Value(f(x)),
408 Nil => Nil,
409 }
410 }
411
412 /// Calls a function with a reference to the contained value if Value.
413 ///
414 /// Returns the original almost.
415 #[inline]
416 pub fn inspect(this: Self, f: impl FnOnce(&T)) -> Self {
417 match this {
418 Value(x) => {
419 f(&x);
420 Value(x)
421 }
422 Nil => Nil,
423 }
424 }
425
426 /// Returns the provided default result (if nil),
427 /// or applies a function to the contained value (if any).
428 ///
429 /// Arguments passed to `map_or` are eagerly evaluated; if you are passing
430 /// the result of a function call, it is recommended to use [`Almost::map_or_else`],
431 /// which is lazily evaluated.
432 ///
433 /// # Examples
434 ///
435 /// ```
436 /// # use for_sure::prelude::*;
437 /// let x = Value("foo");
438 /// assert_eq!(Almost::map_or(x, 42, |v| v.len()), 3);
439 ///
440 /// let x: Almost<&str> = Nil;
441 /// assert_eq!(Almost::map_or(x, 42, |v| v.len()), 42);
442 /// ```
443 #[inline]
444 pub fn map_or<U>(this: Self, default: U, f: impl FnOnce(T) -> U) -> U {
445 match this {
446 Value(x) => f(x),
447 Nil => default,
448 }
449 }
450
451 /// Computes a default function result (if nill), or
452 /// applies a different function to the contained value (if any).
453 ///
454 /// # Examples
455 ///
456 /// ```
457 /// # use for_sure::prelude::*;
458 /// let k = 21;
459 ///
460 /// let x = Value("foo");
461 /// assert_eq!(Almost::map_or_else(x, || 2 * k, |v| v.len()), 3);
462 ///
463 /// let x: Almost<&str> = Nil;
464 /// assert_eq!(Almost::map_or_else(x, || 2 * k, |v| v.len()), 42);
465 /// ```
466 #[inline]
467 pub fn map_or_else<U>(this: Self, default: impl FnOnce() -> U, f: impl FnOnce(T) -> U) -> U {
468 match this {
469 Value(x) => f(x),
470 Nil => default(),
471 }
472 }
473
474 /// Transforms the `Almost<T>` into a [`Result<T, E>`], mapping [`Value(v)`] to
475 /// [`Ok(v)`] and [`Nil`] to [`Err(err)`].
476 ///
477 /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the
478 /// result of a function call, it is recommended to use [`ok_or_else`], which is
479 /// lazily evaluated.
480 ///
481 /// [`Ok(v)`]: Ok
482 /// [`Err(err)`]: Err
483 /// [`Value(v)`]: Value
484 /// [`ok_or_else`]: Almost::ok_or_else
485 ///
486 /// # Examples
487 ///
488 /// ```
489 /// # use for_sure::prelude::*;
490 /// let x = Value("foo");
491 /// assert_eq!(Almost::ok_or(x, 0), Ok("foo"));
492 ///
493 /// let x: Almost<&str> = Nil;
494 /// assert_eq!(Almost::ok_or(x, 0), Err(0));
495 /// ```
496 #[inline]
497 pub fn ok_or<E>(this: Self, error: E) -> Result<T, E> {
498 match this {
499 Value(x) => Ok(x),
500 Nil => Err(error),
501 }
502 }
503
504 /// Transforms the `Almost<T>` into a [`Result<T, E>`], mapping [`Value(v)`] to
505 /// [`Ok(v)`] and [`Nil`] to [`Err(err())`].
506 ///
507 /// [`Ok(v)`]: Ok
508 /// [`Err(err())`]: Err
509 /// [`Value(v)`]: Value
510 ///
511 /// # Examples
512 ///
513 /// ```
514 /// # use for_sure::prelude::*;
515 /// let x = Value("foo");
516 /// assert_eq!(Almost::ok_or_else(x, || 0), Ok("foo"));
517 ///
518 /// let x: Almost<&str> = Nil;
519 /// assert_eq!(Almost::ok_or_else(x, || 0), Err(0));
520 /// ```
521 #[inline]
522 pub fn ok_or_else<E>(this: Self, error: impl FnOnce() -> E) -> Result<T, E> {
523 match this {
524 Value(x) => Ok(x),
525 Nil => Err(error()),
526 }
527 }
528
529 /// Converts from `Almost<T>` (or `&Almost<T>`) to `Almost<&T::Target>`.
530 ///
531 /// Leaves the original [`Almost`] in-place, creating a new one with a reference
532 /// to the original one, additionally coercing the contents via [`Deref`].
533 ///
534 /// # Examples
535 ///
536 /// ```
537 /// # use for_sure::prelude::*;
538 /// let x: Almost<String> = Value("hey".to_owned());
539 /// assert_eq!(Almost::as_deref(&x), Value("hey"));
540 ///
541 /// let x: Almost<String> = Nil;
542 /// assert_eq!(Almost::as_deref(&x), Nil);
543 /// ```
544 #[inline]
545 pub fn as_deref(this: &Self) -> Almost<&<T as Deref>::Target>
546 where
547 T: Deref,
548 {
549 match this {
550 Value(x) => Value(x.deref()),
551 Nil => Nil,
552 }
553 }
554
555 /// Converts from `Almost<T>` (or `&mut Almost<T>`) to `Almost<&mut T::Target>`.
556 ///
557 /// Leaves the original `Almost` in-place, creating a new one containing a mutable reference to
558 /// the inner type's [`Deref::Target`] type.
559 ///
560 /// # Examples
561 ///
562 /// ```
563 /// # use for_sure::prelude::*;
564 /// let mut x: Almost<String> = Nil;
565 /// assert_eq!(Almost::as_deref_mut(&mut x), Nil);
566 /// ```
567 #[inline]
568 pub fn as_deref_mut(this: &mut Self) -> Almost<&mut <T as Deref>::Target>
569 where
570 T: DerefMut,
571 {
572 match this {
573 Value(x) => Value(x.deref_mut()),
574 Nil => Nil,
575 }
576 }
577
578 /// Converts `Almost<T>` into an `Option<T>`
579 ///
580 /// # Examples
581 ///
582 /// ```
583 /// # use for_sure::prelude::*;
584 /// let x: Almost<i32> = Value(42);
585 /// let x: Option<i32> = Almost::into_option(x);
586 /// assert_eq!(x, Some(42));
587 ///
588 /// let y = Nil::<i32>;
589 /// let y: Option<i32> = Almost::into_option(y);
590 /// assert_eq!(y, None);
591 /// ```
592 #[inline]
593 pub fn into_option(this: Self) -> Option<T> {
594 match this {
595 Value(x) => Some(x),
596 Nil => None,
597 }
598 }
599
600 /// Returns an iterator over the possibly contained value.
601 ///
602 /// # Examples
603 ///
604 /// ```
605 /// # use for_sure::prelude::*;
606 /// let x = Value(4);
607 /// assert_eq!(Almost::iter(&x).next(), Some(&4));
608 ///
609 /// let x: Almost<u32> = Nil;
610 /// assert_eq!(Almost::iter(&x).next(), None);
611 /// ```
612 #[inline]
613 pub fn iter(this: &Self) -> Iter<'_, T> {
614 Iter {
615 value: Almost::into_option(Self::as_ref(this)),
616 }
617 }
618
619 /// Returns a mutable iterator over the possibly contained value.
620 ///
621 /// # Examples
622 ///
623 /// ```
624 /// # use for_sure::prelude::*;
625 /// let mut x = Value(4);
626 /// match Almost::iter_mut(&mut x).next() {
627 /// Some(v) => *v = 42,
628 /// None => {},
629 /// }
630 /// assert_eq!(x, Value(42));
631 ///
632 /// let mut x: Almost<u32> = Nil;
633 /// assert_eq!(Almost::iter_mut(&mut x).next(), None);
634 /// ```
635 #[inline]
636 pub fn iter_mut(this: &mut Self) -> IterMut<'_, T> {
637 IterMut {
638 value: Almost::into_option(Self::as_mut(this)),
639 }
640 }
641
642 /// Returns [`Nil`] if the option is [`Nil`], otherwise returns `other`.
643 ///
644 /// Arguments passed to `and` are eagerly evaluated; if you are passing the
645 /// result of a function call, it is recommended to use [`and_then`], which is
646 /// lazily evaluated.
647 ///
648 /// [`and_then`]: Almost::and_then
649 ///
650 /// # Examples
651 ///
652 /// ```
653 /// # use for_sure::prelude::*;
654 /// let x = Value(2);
655 /// let y: Almost<&str> = Nil;
656 /// assert_eq!(Almost::and(x, y), Nil);
657 ///
658 /// let x: Almost<u32> = Nil;
659 /// let y = Value("foo");
660 /// assert_eq!(Almost::and(x, y), Nil);
661 ///
662 /// let x = Value(2);
663 /// let y = Value("foo");
664 /// assert_eq!(Almost::and(x, y), Value("foo"));
665 ///
666 /// let x: Almost<u32> = Nil;
667 /// let y: Almost<&str> = Nil;
668 /// assert_eq!(Almost::and(x, y), Nil);
669 /// ```
670 #[inline]
671 pub fn and<U>(this: Self, other: Almost<U>) -> Almost<U> {
672 match this {
673 Nil => Nil,
674 Value(_) => other,
675 }
676 }
677
678 /// Returns [`Nil`] if the option is [`Nil`], otherwise calls `f` with the
679 /// wrapped value and returns the result.
680 ///
681 /// Some languages call this operation flatmap.
682 ///
683 /// # Examples
684 ///
685 /// ```
686 /// # use for_sure::prelude::*;
687 /// fn sq_then_to_string(x: u32) -> Almost<String> {
688 /// x.checked_mul(x).map(|sq| sq.to_string()).into()
689 /// }
690 ///
691 /// assert_eq!(Almost::and_then(Value(2), sq_then_to_string), Value(4.to_string()));
692 /// assert_eq!(Almost::and_then(Value(1_000_000), sq_then_to_string), Nil); // overflowed!
693 /// assert_eq!(Almost::and_then(Nil, sq_then_to_string), Nil);
694 /// ```
695 #[doc(alias = "flatmap")]
696 #[inline]
697 pub fn and_then<U>(this: Self, other: impl FnOnce(T) -> Almost<U>) -> Almost<U> {
698 match this {
699 Nil => Nil,
700 Value(x) => other(x),
701 }
702 }
703
704 /// Returns [`Nil`] if the option is [`Nil`], otherwise calls `predicate`
705 /// with the wrapped value and returns:
706 ///
707 /// - [`Value(t)`] if `predicate` returns `true` (where `t` is the wrapped
708 /// value), and
709 /// - [`Nil`] if `predicate` returns `false`.
710 ///
711 /// This function works similar to [`Iterator::filter()`]. You can imagine
712 /// the `Almost<T>` being an iterator over one or zero elements. `filter()`
713 /// lets you decide which elements to keep.
714 ///
715 /// # Examples
716 ///
717 /// ```
718 /// # use for_sure::prelude::*;
719 /// fn is_even(n: &i32) -> bool {
720 /// n % 2 == 0
721 /// }
722 ///
723 /// assert_eq!(Almost::filter(Nil, is_even), Nil);
724 /// assert_eq!(Almost::filter(Value(3), is_even), Nil);
725 /// assert_eq!(Almost::filter(Value(4), is_even), Value(4));
726 /// ```
727 ///
728 /// [`Value(t)`]: Value
729 #[inline]
730 pub fn filter(this: Self, do_get: impl FnOnce(&T) -> bool) -> Self {
731 if let Value(x) = this
732 && do_get(&x)
733 {
734 return Value(x);
735 }
736
737 Nil
738 }
739
740 /// Returns the almost if it contains a value, otherwise returns `other`.
741 ///
742 /// Arguments passed to `or` are eagerly evaluated; if you are passing the
743 /// result of a function call, it is recommended to use [`or_else`], which is
744 /// lazily evaluated.
745 ///
746 /// [`or_else`]: Almost::or_else
747 ///
748 /// # Examples
749 ///
750 /// ```
751 /// # use for_sure::prelude::*;
752 /// let x = Value(2);
753 /// let y = Nil;
754 /// assert_eq!(Almost::or(x, y), Value(2));
755 ///
756 /// let x = Nil;
757 /// let y = Value(100);
758 /// assert_eq!(Almost::or(x, y), Value(100));
759 ///
760 /// let x = Value(2);
761 /// let y = Value(100);
762 /// assert_eq!(Almost::or(x, y), Value(2));
763 ///
764 /// let x: Almost<u32> = Nil;
765 /// let y = Nil;
766 /// assert_eq!(Almost::or(x, y), Nil);
767 /// ```
768 #[inline]
769 pub fn or(this: Self, other: Self) -> Self {
770 match this {
771 Nil => other,
772 Value(x) => Value(x),
773 }
774 }
775
776 /// Returns the almost if it contains a value, otherwise calls `f` and
777 /// returns the result.
778 ///
779 /// # Examples
780 ///
781 /// ```
782 /// # use for_sure::prelude::*;
783 /// fn nobody() -> Almost<&'static str> { Nil }
784 /// fn vikings() -> Almost<&'static str> { Value("vikings") }
785 ///
786 /// assert_eq!(Almost::or_else(Value("barbarians"), vikings), Value("barbarians"));
787 /// assert_eq!(Almost::or_else(Nil, vikings), Value("vikings"));
788 /// assert_eq!(Almost::or_else(Nil, nobody), Nil);
789 /// ```
790 #[inline]
791 pub fn or_else(this: Self, f: impl FnOnce() -> Self) -> Self {
792 match this {
793 Nil => f(),
794 Value(x) => Value(x),
795 }
796 }
797
798 /// Returns [`Value`] if exactly one of `self`, `other` is [`Value`], otherwise returns [`Nil`].
799 ///
800 /// # Examples
801 ///
802 /// ```
803 /// # use for_sure::prelude::*;
804 /// let x = Value(2);
805 /// let y: Almost<u32> = Nil;
806 /// assert_eq!(Almost::xor(x, y), Value(2));
807 ///
808 /// let x: Almost<u32> = Nil;
809 /// let y = Value(2);
810 /// assert_eq!(Almost::xor(x, y), Value(2));
811 ///
812 /// let x = Value(2);
813 /// let y = Value(2);
814 /// assert_eq!(Almost::xor(x, y), Nil);
815 ///
816 /// let x: Almost<u32> = Nil;
817 /// let y: Almost<u32> = Nil;
818 /// assert_eq!(Almost::xor(x, y), Nil);
819 /// ```
820 #[inline]
821 pub fn xor(this: Self, other: Self) -> Self {
822 match (this, other) {
823 (Value(x), Nil) | (Nil, Value(x)) => Value(x),
824 (Value(_), Value(_)) | (Nil, Nil) => Nil,
825 }
826 }
827
828 /// Inserts `value` into the almost, then returns a mutable reference to it.
829 ///
830 /// If the almost already contains a value, the old value is dropped.
831 ///
832 /// See also [`Almost::get_or_insert`], which doesn't update the value if
833 /// the option already contains [`Value`].
834 ///
835 /// # Example
836 ///
837 /// ```
838 /// # use for_sure::prelude::*;
839 /// let mut almost = Nil;
840 /// let val = Almost::insert(&mut almost, 1);
841 /// assert_eq!(*val, 1);
842 /// assert_eq!(Almost::unwrap(almost), 1);
843 ///
844 /// let val = Almost::insert(&mut almost, 2);
845 /// assert_eq!(*val, 2);
846 /// *val = 3;
847 /// assert_eq!(Almost::unwrap(almost), 3);
848 /// ```
849 #[must_use = "if you intended to set a value, consider assignment instead"]
850 #[inline]
851 pub fn insert(this: &mut Self, value: T) -> &mut T {
852 *this = Value(value);
853 // Safety: the code above just filled the option
854 unsafe { Almost::unwrap_unchecked(Almost::as_mut(this)) }
855 }
856
857 /// Inserts `value` into the almost if it is [`Nil`], then
858 /// returns a mutable reference to the contained value.
859 ///
860 /// See also [`Almost::insert`], which updates the value even if
861 /// the option already contains [`Almost`].
862 ///
863 /// # Examples
864 ///
865 /// ```
866 /// # use for_sure::prelude::*;
867 /// let mut x = Nil;
868 ///
869 /// {
870 /// let y: &mut u32 = Almost::get_or_insert(&mut x, 5);
871 /// assert_eq!(y, &5);
872 ///
873 /// *y = 7;
874 /// }
875 ///
876 /// assert_eq!(x, Value(7));
877 /// ```
878 #[inline]
879 pub fn get_or_insert(this: &mut Self, value: T) -> &mut T {
880 Almost::get_or_insert_with(this, || value)
881 }
882
883 /// Inserts the default value into the almost if it is [`Nil`], then
884 /// returns a mutable reference to the contained value.
885 ///
886 /// # Examples
887 ///
888 /// ```
889 /// # use for_sure::prelude::*;
890 /// let mut x = Nil;
891 ///
892 /// {
893 /// let y: &mut u32 = Almost::get_or_insert_default(&mut x);
894 /// assert_eq!(y, &0);
895 ///
896 /// *y = 7;
897 /// }
898 ///
899 /// assert_eq!(x, Value(7));
900 /// ```
901 #[inline]
902 pub fn get_or_insert_default(this: &mut Self) -> &mut T
903 where
904 T: Default,
905 {
906 Almost::get_or_insert_with(this, T::default)
907 }
908
909 /// Inserts a value computed from `f` into the almost if it is [`Nil`],
910 /// then returns a mutable reference to the contained value.
911 ///
912 /// # Examples
913 ///
914 /// ```
915 /// # use for_sure::prelude::*;
916 /// let mut x = Nil;
917 ///
918 /// {
919 /// let y: &mut u32 = Almost::get_or_insert_with(&mut x, || 5);
920 /// assert_eq!(y, &5);
921 ///
922 /// *y = 7;
923 /// }
924 ///
925 /// assert_eq!(x, Value(7));
926 /// ```
927 #[inline]
928 pub fn get_or_insert_with(this: &mut Self, f: impl FnOnce() -> T) -> &mut T {
929 if let Nil = this {
930 *this = Value(f());
931 }
932
933 // Safety: the code above just filled the option
934 unsafe { Almost::unwrap_unchecked(Almost::as_mut(this)) }
935 }
936
937 /// Takes the value out of the almost, leaving a [`Nil`] in its place.
938 ///
939 /// # Examples
940 ///
941 /// ```
942 /// # use for_sure::prelude::*;
943 /// let mut x = Value(2);
944 /// let y = Almost::take(&mut x);
945 /// assert_eq!(x, Nil);
946 /// assert_eq!(y, Value(2));
947 ///
948 /// let mut x: Almost<u32> = Nil;
949 /// let y = Almost::take(&mut x);
950 /// assert_eq!(x, Nil);
951 /// assert_eq!(y, Nil);
952 /// ```
953 #[inline]
954 pub const fn take(this: &mut Self) -> Self {
955 mem::replace(this, Nil)
956 }
957
958 /// Takes the value out of the almost, leaving a [`Nil`] in its place, then
959 /// unwraps the underlying value.
960 ///
961 /// # Panic
962 ///
963 /// Panics if `this` was [`Nil`].
964 ///
965 /// # Examples
966 ///
967 /// ```
968 /// # use for_sure::prelude::*;
969 /// let mut x = Value(2);
970 /// let y = Almost::take_unwrap(&mut x);
971 /// assert_eq!(x, Nil);
972 /// assert_eq!(y, 2);
973 /// ```
974 ///
975 /// This panics:
976 ///
977 /// ```should_panic
978 /// # use for_sure::prelude::*;
979 /// let mut x: Almost<u32> = Nil;
980 /// let y = Almost::take_unwrap(&mut x);
981 /// ```
982 #[inline]
983 #[track_caller]
984 pub fn take_unwrap(this: &mut Self) -> T {
985 Self::unwrap(Self::take(this))
986 }
987
988 /// Takes the value out of the almost, leaving a [`Nil`] in its place, then
989 /// unwraps the underlying value.
990 ///
991 /// # Panic
992 ///
993 /// Panics with `message` if `this` was [`Nil`].
994 ///
995 /// # Examples
996 ///
997 /// ```
998 /// # use for_sure::prelude::*;
999 /// let mut x = Value(2);
1000 /// let y = Almost::take_expect(&mut x, "x cannot be Nil");
1001 /// assert_eq!(x, Nil);
1002 /// assert_eq!(y, 2);
1003 /// ```
1004 ///
1005 /// This panics:
1006 ///
1007 /// ```should_panic
1008 /// # use for_sure::prelude::*;
1009 /// let mut x: Almost<u32> = Nil;
1010 /// let y = Almost::take_expect(&mut x, "oops");
1011 /// ```
1012 #[inline]
1013 #[track_caller]
1014 pub fn take_expect(this: &mut Self, message: &str) -> T {
1015 Self::expect(Self::take(this), message)
1016 }
1017
1018 /// Takes the value out of the almost, but only if the predicate evaluates to
1019 /// `true` on a mutable reference to the value.
1020 ///
1021 /// In other words, replaces `self` with `Nil` if the predicate returns `true`.
1022 /// This method operates similar to [`Almost::take`] but conditional.
1023 ///
1024 /// # Examples
1025 ///
1026 /// ```
1027 /// # use for_sure::prelude::*;
1028 /// let mut x = Value(42);
1029 ///
1030 /// let prev = Almost::take_if(&mut x, |v| if *v == 42 {
1031 /// *v += 1;
1032 /// false
1033 /// } else {
1034 /// false
1035 /// });
1036 /// assert_eq!(x, Value(43));
1037 /// assert_eq!(prev, Nil);
1038 ///
1039 /// let prev = Almost::take_if(&mut x, |v| *v == 43);
1040 /// assert_eq!(x, Nil);
1041 /// assert_eq!(prev, Value(43));
1042 /// ```
1043 #[inline]
1044 pub fn take_if(this: &mut Self, f: impl FnOnce(&mut T) -> bool) -> Self {
1045 if Almost::map_or(Almost::as_mut(this), false, f) {
1046 Almost::take(this)
1047 } else {
1048 Nil
1049 }
1050 }
1051
1052 /// Replaces the actual value in the almost by the value given in parameter,
1053 /// returning the old value if present,
1054 /// leaving a [`Value`] in its place without deinitializing either one.
1055 ///
1056 /// # Examples
1057 ///
1058 /// ```
1059 /// # use for_sure::prelude::*;
1060 /// let mut x = Value(2);
1061 /// let old = Almost::replace(&mut x, 5);
1062 /// assert_eq!(x, Value(5));
1063 /// assert_eq!(old, Value(2));
1064 ///
1065 /// let mut x = Nil;
1066 /// let old = Almost::replace(&mut x, 3);
1067 /// assert_eq!(x, Value(3));
1068 /// assert_eq!(old, Nil);
1069 /// ```
1070 #[inline]
1071 pub const fn replace(this: &mut Self, value: T) -> Self {
1072 mem::replace(this, Value(value))
1073 }
1074
1075 /// Zips `self` with another `Almost`.
1076 ///
1077 /// If `self` is `Value(s)` and `other` is `Value(o)`, this method returns `Value((s, o))`.
1078 /// Otherwise, `Nil` is returned.
1079 ///
1080 /// # Examples
1081 ///
1082 /// ```
1083 /// # use for_sure::prelude::*;
1084 /// let x = Value(1);
1085 /// let y = Value("hi");
1086 /// let z = Nil::<u8>;
1087 ///
1088 /// assert_eq!(Almost::zip(x, y), Value((1, "hi")));
1089 /// assert_eq!(Almost::zip(x, z), Nil);
1090 /// ```
1091 #[inline]
1092 pub fn zip<U>(this: Self, other: Almost<U>) -> Almost<(T, U)> {
1093 match (this, other) {
1094 (Value(x), Value(y)) => Value((x, y)),
1095 _ => Nil,
1096 }
1097 }
1098
1099 /// Zips `self` and another `Almost` with function `f`.
1100 ///
1101 /// If `self` is `Value(s)` and `other` is `Value(o)`, this method returns `Value(f(s, o))`.
1102 /// Otherwise, `Nil` is returned.
1103 ///
1104 /// # Examples
1105 ///
1106 /// ```
1107 /// # use for_sure::prelude::*;
1108 /// #[derive(Debug, PartialEq)]
1109 /// struct Point {
1110 /// x: f64,
1111 /// y: f64,
1112 /// }
1113 ///
1114 /// impl Point {
1115 /// fn new(x: f64, y: f64) -> Self {
1116 /// Self { x, y }
1117 /// }
1118 /// }
1119 ///
1120 /// let x = Value(17.5);
1121 /// let y = Value(42.7);
1122 ///
1123 /// assert_eq!(Almost::zip_with(x, y, Point::new), Value(Point { x: 17.5, y: 42.7 }));
1124 /// assert_eq!(Almost::zip_with(x, Nil, Point::new), Nil);
1125 /// ```
1126 #[inline]
1127 pub fn zip_with<U, R>(this: Self, other: Almost<U>, f: impl FnOnce(T, U) -> R) -> Almost<R> {
1128 match (this, other) {
1129 (Value(x), Value(y)) => Value(f(x, y)),
1130 _ => Nil,
1131 }
1132 }
1133
1134 /// Return a reference the underlying value.
1135 ///
1136 /// # Panic
1137 ///
1138 /// Panics if `this` is `Nil`
1139 #[track_caller]
1140 pub const fn get_ref(this: &Self) -> &T {
1141 match this {
1142 Value(value) => value,
1143 Nil => panic!("Almost<T> was uninit"),
1144 }
1145 }
1146
1147 /// Return a mutable reference the underlying value.
1148 ///
1149 /// # Panic
1150 ///
1151 /// Panics if `this` is `Nil`
1152 #[track_caller]
1153 pub const fn get_mut(this: &mut Self) -> &mut T {
1154 match this {
1155 Value(value) => value,
1156 Nil => panic!("Almost<T> was uninit"),
1157 }
1158 }
1159
1160 /// Construct [`Almost<T>`] from [`Option<T>`].
1161 pub fn from_option(value: Option<T>) -> Self {
1162 match value {
1163 Some(x) => Value(x),
1164 None => Nil,
1165 }
1166 }
1167}
1168
1169impl<T, U> Almost<(T, U)> {
1170 /// Unzips an almost containing a tuple of two almosts.
1171 ///
1172 /// If `self` is `Value((a, b))` this method returns `(Value(a), Value(b))`.
1173 /// Otherwise, `(Nil, Nil)` is returned.
1174 ///
1175 /// # Examples
1176 ///
1177 /// ```
1178 /// # use for_sure::prelude::*;
1179 /// let x = Value((1, "hi"));
1180 /// let y = Nil::<(u8, u32)>;
1181 ///
1182 /// assert_eq!(Almost::unzip(x), (Value(1), Value("hi")));
1183 /// assert_eq!(Almost::unzip(y), (Nil, Nil));
1184 /// ```
1185 #[inline]
1186 pub fn unzip(this: Self) -> (Almost<T>, Almost<U>) {
1187 match this {
1188 Value((x, y)) => (Value(x), Value(y)),
1189 Nil => (Nil, Nil),
1190 }
1191 }
1192}
1193
1194impl<T> Almost<&'_ T> {
1195 /// Maps an `Almost<&T>` to an `Almost<T>` by copying the contents of the
1196 /// almost.
1197 ///
1198 /// # Examples
1199 ///
1200 /// ```
1201 /// # use for_sure::prelude::*;
1202 /// let x = 12;
1203 /// let opt_x = Value(&x);
1204 /// assert_eq!(opt_x, Value(&12));
1205 /// let copied = Almost::copied(opt_x);
1206 /// assert_eq!(copied, Value(12));
1207 /// ```
1208 #[must_use = "`self` will be dropped if the result is not used"]
1209 pub const fn copied(this: Self) -> Almost<T>
1210 where
1211 T: Copy,
1212 {
1213 match this {
1214 Value(&x) => Value(x),
1215 Nil => Nil,
1216 }
1217 }
1218
1219 /// Maps an `Almost<&T>` to an `Almost<T>` by cloning the contents of the
1220 /// almost.
1221 ///
1222 /// # Examples
1223 ///
1224 /// ```
1225 /// # use for_sure::prelude::*;
1226 /// let x = 12;
1227 /// let opt_x = Value(&x);
1228 /// assert_eq!(opt_x, Value(&12));
1229 /// let cloned = Almost::cloned(opt_x);
1230 /// assert_eq!(cloned, Value(12));
1231 /// ```
1232 pub fn cloned(this: Self) -> Almost<T>
1233 where
1234 T: Clone,
1235 {
1236 match this {
1237 Value(x) => Value(x.clone()),
1238 Nil => Nil,
1239 }
1240 }
1241}
1242
1243impl<T, E> Almost<Result<T, E>> {
1244 /// Transposes an `Almost` of a [`Result`] into a [`Result`] of an `Almost`.
1245 ///
1246 /// [`Nil`] will be mapped to <code>[Ok]\([Nil])</code>.
1247 /// <code>[Value]\([Ok]\(\_))</code> and <code>[Value]\([Err]\(\_))</code> will be mapped to
1248 /// <code>[Ok]\([Value]\(\_))</code> and <code>[Err]\(\_)</code>.
1249 ///
1250 /// # Examples
1251 ///
1252 /// ```
1253 /// # use for_sure::prelude::*;
1254 /// #[derive(Debug, Eq, PartialEq)]
1255 /// struct SomeErr;
1256 ///
1257 /// let x: Result<Almost<i32>, SomeErr> = Ok(Value(5));
1258 /// let y: Almost<Result<i32, SomeErr>> = Value(Ok(5));
1259 /// assert_eq!(x, Almost::transpose(y));
1260 /// ```
1261 #[inline]
1262 pub fn transpose(this: Self) -> Result<Almost<T>, E> {
1263 match this {
1264 Value(Ok(x)) => Ok(Value(x)),
1265 Nil => Ok(Nil),
1266 Value(Err(e)) => Err(e),
1267 }
1268 }
1269}
1270
1271impl<T> Almost<Almost<T>> {
1272 /// Converts from `Almost<Almost<T>>` to `Almost<T>`.
1273 ///
1274 /// # Examples
1275 ///
1276 /// Basic usage:
1277 ///
1278 /// ```
1279 /// # use for_sure::prelude::*;
1280 /// let x: Almost<Almost<u32>> = Value(Value(6));
1281 /// assert_eq!(Value(6), Almost::flatten(x));
1282 ///
1283 /// let x: Almost<Almost<u32>> = Value(Nil);
1284 /// assert_eq!(Nil, Almost::flatten(x));
1285 ///
1286 /// let x: Almost<Almost<u32>> = Nil;
1287 /// assert_eq!(Nil, Almost::flatten(x));
1288 /// ```
1289 ///
1290 /// Flattening only removes one level of nesting at a time:
1291 ///
1292 /// ```
1293 /// # use for_sure::prelude::*;
1294 /// let x: Almost<Almost<Almost<u32>>> = Value(Value(Value(6)));
1295 /// assert_eq!(Value(Value(6)), Almost::flatten(x));
1296 /// assert_eq!(Value(6), Almost::flatten(Almost::flatten(x)));
1297 /// ```
1298 #[inline]
1299 pub fn flatten(this: Self) -> Almost<T> {
1300 match this {
1301 Value(Value(x)) => Value(x),
1302 Value(Nil) | Nil => Nil,
1303 }
1304 }
1305}
1306
1307impl<T: fmt::Debug> fmt::Debug for Almost<T> {
1308 #[inline]
1309 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1310 match &self {
1311 Value(value) => fmt::Debug::fmt(&value, f),
1312 Nil => f.write_str("nil"),
1313 }
1314 }
1315}
1316
1317impl<T> Deref for Almost<T> {
1318 type Target = T;
1319
1320 /// Get a reference to the underlying data.
1321 ///
1322 /// # Panic
1323 ///
1324 /// Panics if self is `Nil`.
1325 #[track_caller]
1326 #[inline]
1327 fn deref(&self) -> &Self::Target {
1328 Self::get_ref(self)
1329 }
1330}
1331
1332impl<T> DerefMut for Almost<T> {
1333 /// Get a mutable reference to the underlying data.
1334 ///
1335 /// # Panic
1336 ///
1337 /// Panics if self is `Nil`.
1338 #[track_caller]
1339 #[inline]
1340 fn deref_mut(&mut self) -> &mut Self::Target {
1341 Self::get_mut(self)
1342 }
1343}
1344
1345impl<U: ?Sized, T: AsRef<U>> AsRef<U> for Almost<T> {
1346 #[inline]
1347 fn as_ref(&self) -> &U {
1348 Self::get_ref(self).as_ref()
1349 }
1350}
1351
1352impl<'a, T> From<&'a Almost<T>> for Almost<&'a T> {
1353 #[inline]
1354 fn from(value: &'a Almost<T>) -> Self {
1355 Almost::as_ref(value)
1356 }
1357}
1358
1359impl<'a, T> From<&'a mut Almost<T>> for Almost<&'a mut T> {
1360 #[inline]
1361 fn from(value: &'a mut Almost<T>) -> Self {
1362 Almost::as_mut(value)
1363 }
1364}
1365
1366impl<T> From<T> for Almost<T> {
1367 #[inline]
1368 fn from(value: T) -> Self {
1369 Value(value)
1370 }
1371}
1372
1373impl<T> From<Option<T>> for Almost<T> {
1374 #[inline]
1375 fn from(value: Option<T>) -> Self {
1376 match value {
1377 Some(x) => Value(x),
1378 None => Nil,
1379 }
1380 }
1381}
1382
1383impl<T> From<Almost<T>> for Option<T> {
1384 #[inline]
1385 fn from(value: Almost<T>) -> Self {
1386 match value {
1387 Value(x) => Some(x),
1388 Nil => None,
1389 }
1390 }
1391}
1392
1393impl<T: Clone> Clone for Almost<T> {
1394 #[inline]
1395 fn clone(&self) -> Self {
1396 match self {
1397 Value(x) => Value(x.clone()),
1398 Nil => Nil,
1399 }
1400 }
1401
1402 #[inline]
1403 fn clone_from(&mut self, source: &Self) {
1404 match (self, source) {
1405 (Value(to), Value(from)) => to.clone_from(from),
1406 (to, from) => *to = from.clone(),
1407 }
1408 }
1409}
1410
1411impl<T> IntoIterator for Almost<T> {
1412 type Item = T;
1413 type IntoIter = IntoIter<T>;
1414
1415 #[inline]
1416 fn into_iter(self) -> Self::IntoIter {
1417 IntoIter {
1418 value: Almost::into_option(self),
1419 }
1420 }
1421}
1422
1423impl<'a, T> IntoIterator for &'a Almost<T> {
1424 type Item = &'a T;
1425 type IntoIter = Iter<'a, T>;
1426
1427 #[inline]
1428 fn into_iter(self) -> Self::IntoIter {
1429 Almost::iter(self)
1430 }
1431}
1432
1433impl<'a, T> IntoIterator for &'a mut Almost<T> {
1434 type Item = &'a mut T;
1435 type IntoIter = IterMut<'a, T>;
1436
1437 #[inline]
1438 fn into_iter(self) -> Self::IntoIter {
1439 Almost::iter_mut(self)
1440 }
1441}
1442
1443#[derive(Debug, Clone)]
1444pub struct IntoIter<T> {
1445 pub(crate) value: Option<T>,
1446}
1447
1448impl<T> Iterator for IntoIter<T> {
1449 type Item = T;
1450
1451 #[inline]
1452 fn next(&mut self) -> Option<Self::Item> {
1453 self.value.take()
1454 }
1455
1456 #[inline]
1457 fn size_hint(&self) -> (usize, Option<usize>) {
1458 (self.len(), Some(self.len()))
1459 }
1460}
1461
1462impl<T> DoubleEndedIterator for IntoIter<T> {
1463 #[inline]
1464 fn next_back(&mut self) -> Option<Self::Item> {
1465 self.value.take()
1466 }
1467}
1468
1469impl<T> FusedIterator for IntoIter<T> {}
1470
1471impl<T> ExactSizeIterator for IntoIter<T> {
1472 #[inline]
1473 fn len(&self) -> usize {
1474 match &self.value {
1475 Some(_) => 1,
1476 None => 0,
1477 }
1478 }
1479}
1480
1481pub struct Iter<'a, T> {
1482 pub(crate) value: Option<&'a T>,
1483}
1484
1485impl<T> Clone for Iter<'_, T> {
1486 fn clone(&self) -> Self {
1487 Self { value: self.value }
1488 }
1489}
1490
1491impl<'a, T> Iterator for Iter<'a, T> {
1492 type Item = &'a T;
1493
1494 #[inline]
1495 fn next(&mut self) -> Option<Self::Item> {
1496 self.value.take()
1497 }
1498
1499 #[inline]
1500 fn size_hint(&self) -> (usize, Option<usize>) {
1501 (self.len(), Some(self.len()))
1502 }
1503}
1504
1505impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1506 #[inline]
1507 fn next_back(&mut self) -> Option<Self::Item> {
1508 self.value.take()
1509 }
1510}
1511
1512impl<T> FusedIterator for Iter<'_, T> {}
1513
1514impl<T> ExactSizeIterator for Iter<'_, T> {
1515 #[inline]
1516 fn len(&self) -> usize {
1517 match self.value {
1518 None => 0,
1519 Some(_) => 1,
1520 }
1521 }
1522}
1523
1524pub struct IterMut<'a, T> {
1525 pub(crate) value: Option<&'a mut T>,
1526}
1527
1528impl<'a, T> Iterator for IterMut<'a, T> {
1529 type Item = &'a mut T;
1530
1531 #[inline]
1532 fn next(&mut self) -> Option<Self::Item> {
1533 self.value.take()
1534 }
1535
1536 #[inline]
1537 fn size_hint(&self) -> (usize, Option<usize>) {
1538 (self.len(), Some(self.len()))
1539 }
1540}
1541
1542impl<T> FusedIterator for IterMut<'_, T> {}
1543
1544impl<T> ExactSizeIterator for IterMut<'_, T> {
1545 #[inline]
1546 fn len(&self) -> usize {
1547 match self.value {
1548 Some(_) => 1,
1549 None => 0,
1550 }
1551 }
1552}
1553
1554#[cfg(test)]
1555mod tests {
1556 use super::*;
1557
1558 #[test]
1559 fn test_as_ref() {
1560 let string = Value(String::from("a little string"));
1561 let s: &str = string.as_ref();
1562 assert_eq!(s, "a little string")
1563 }
1564}