blob: d344f81fc3997e26fc9a508fb9abf5d7433fb937 [file] [log] [blame]
Joel Scherpelzf3fa5cc2017-05-22 12:30:03 +09001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef NETUTILS_MISC_H
18#define NETUTILS_MISC_H
19
20#include <map>
21
22namespace android {
23namespace netdutils {
24
25// Lookup key in map, returing a default value if key is not found
26template <typename U, typename V>
27inline const V& findWithDefault(const std::map<U, V>& map, const U& key, const V& dflt) {
28 auto it = map.find(key);
29 return (it == map.end()) ? dflt : it->second;
30}
31
32// Movable, copiable, scoped lambda (or std::function) runner. Useful
33// for running arbitrary cleanup or logging code when exiting a scope.
34//
35// Compare to defer in golang.
36template <typename FnT>
37class Cleanup {
38 public:
39 Cleanup() = delete;
Bernie Innocenti835f0df2018-11-20 17:13:54 +090040 explicit Cleanup(FnT fn) : mFn(fn) {}
Erik Kline85890042018-05-25 19:19:11 +090041 ~Cleanup() { if (!mReleased) mFn(); }
Joel Scherpelzf3fa5cc2017-05-22 12:30:03 +090042
Erik Kline85890042018-05-25 19:19:11 +090043 void release() { mReleased = true; }
Joel Scherpelzf3fa5cc2017-05-22 12:30:03 +090044
45 private:
Erik Kline85890042018-05-25 19:19:11 +090046 bool mReleased{false};
Joel Scherpelzf3fa5cc2017-05-22 12:30:03 +090047 FnT mFn;
48};
49
50// Helper to make a new Cleanup. Avoids complex or impossible syntax
51// when wrapping lambdas.
52//
53// Usage:
54// auto cleanup = makeCleanup([](){ your_code_here; });
55template <typename FnT>
56Cleanup<FnT> makeCleanup(FnT fn) {
57 return Cleanup<FnT>(fn);
58}
59
60} // namespace netdutils
61} // namespace android
62
63#endif /* NETUTILS_MISC_H */