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