1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
 * Copyright (c) 2020 Jens Reimann and others.
 *
 * See the NOTICE file(s) distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0
 *
 * SPDX-License-Identifier: EPL-2.0
 */
use anyhow::Result;

/// Use the value of something optional, or create it first.
pub trait UseOrCreate<T> {
    fn use_or_create<F, R>(&mut self, f: F) -> R
    where
        F: FnOnce(&mut T) -> R;

    fn use_or_create_err<F>(&mut self, f: F) -> Result<()>
    where
        F: FnOnce(&mut T) -> Result<()>,
    {
        self.use_or_create(|value| f(value))
    }
}

/// Implementation for `Option`s which wrap `Default`s.
impl<T> UseOrCreate<T> for Option<T>
where
    T: Default,
{
    fn use_or_create<F, R>(&mut self, f: F) -> R
    where
        F: FnOnce(&mut T) -> R,
    {
        match self {
            Some(value) => f(value),
            None => {
                let mut value = Default::default();
                let result = f(&mut value);
                self.replace(value);
                result
            }
        }
    }
}

#[cfg(test)]
mod tests {

    use super::*;

    #[derive(Default, Debug)]
    struct Example {
        foo: String,
    }

    #[test]
    fn test_with_none() {
        let mut v: Option<Example> = None;
        v.use_or_create(|v| {
            v.foo = "bar".to_string();
        });

        assert!(v.is_some());
        assert_eq!(v.unwrap().foo, "bar");
    }

    #[test]
    fn test_with_some() {
        let mut v: Option<Example> = Some(Example { foo: "foo".into() });
        v.use_or_create(|v| {
            assert_eq!(v.foo, "foo");
            v.foo = "bar".to_string();
        });

        assert!(v.is_some());
        assert_eq!(v.unwrap().foo, "bar");
    }
}