foyer_common/utils/scope.rs
1// Copyright 2025 foyer Project Authors
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
15/// Scoped functional programming extensions.
16pub trait Scope {
17 /// Scoped with ownership.
18 fn with<F, R>(self, f: F) -> R
19 where
20 Self: Sized,
21 F: FnOnce(Self) -> R,
22 {
23 f(self)
24 }
25
26 /// Scoped with reference.
27 fn with_ref<F, R>(&self, f: F) -> R
28 where
29 F: FnOnce(&Self) -> R,
30 {
31 f(self)
32 }
33
34 /// Scoped with mutable reference.
35 fn with_mut<F, R>(&mut self, f: F) -> R
36 where
37 F: FnOnce(&mut Self) -> R,
38 {
39 f(self)
40 }
41}
42impl<T> Scope for T {}