diff --git a/core/src/lib.rs b/core/src/lib.rs index aac31a71..ad78de81 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -473,3 +473,4 @@ mod test { } pub mod intern_set; +pub mod util; diff --git a/core/src/util.rs b/core/src/util.rs new file mode 100644 index 00000000..cd2205d2 --- /dev/null +++ b/core/src/util.rs @@ -0,0 +1,60 @@ + +// Copyright 2016 Mozilla +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may not use +// this file except in compliance with the License. You may obtain a copy of the +// License at http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +/// Side-effect chaining on `Result`. +pub trait ResultEffect { + /// Invoke `f` if `self` is `Ok`, returning `self`. + fn when_ok(self, f: F) -> Self; + + /// Invoke `f` if `self` is `Err`, returning `self`. + fn when_err(self, f: F) -> Self; +} + +impl ResultEffect for Result { + fn when_ok(self, f: F) -> Self { + if self.is_ok() { + f(); + } + self + } + + fn when_err(self, f: F) -> Self { + if self.is_err() { + f(); + } + self + } +} + +/// Side-effect chaining on `Option`. +pub trait OptionEffect { + /// Invoke `f` if `self` is `None`, returning `self`. + fn when_none(self, f: F) -> Self; + + /// Invoke `f` if `self` is `Some`, returning `self`. + fn when_some(self, f: F) -> Self; +} + +impl OptionEffect for Option { + fn when_none(self, f: F) -> Self { + if self.is_none() { + f(); + } + self + } + + fn when_some(self, f: F) -> Self { + if self.is_some() { + f(); + } + self + } +} \ No newline at end of file