derive_insert/lib.rs
1// Copyright 2021 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15pub use ::derive_insert_impl::GetOrInsert;
16
17#[cfg_attr(not(doctest), doc = include_str!("../README.md"))]
18pub trait GetOrInsert<T> {
19 // Required methods
20 fn insert(&mut self, value: T) -> &mut T;
21 fn get_or_insert_with<F: FnOnce() -> T>(&mut self, f: F) -> &mut T;
22
23 // Provided methods
24 fn get_or_insert(&mut self, value: T) -> &mut T {
25 self.get_or_insert_with(|| value)
26 }
27 fn get_or_insert_default(&mut self) -> &mut T
28 where
29 T: Default,
30 {
31 self.get_or_insert_with(Default::default)
32 }
33}
34
35/// Provides a default implementation for `Option<T>`.
36impl<T> GetOrInsert<T> for Option<T> {
37 fn insert(&mut self, value: T) -> &mut T {
38 <Option<T>>::insert(self, value)
39 }
40
41 fn get_or_insert_with<F: FnOnce() -> T>(&mut self, f: F) -> &mut T {
42 <Option<T>>::get_or_insert_with(self, f)
43 }
44}