1 /*
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 
22 namespace android {
23 namespace netdutils {
24 
25 // Lookup key in map, returing a default value if key is not found
26 template <typename U, typename V>
findWithDefault(const std::map<U,V> & map,const U & key,const V & dflt)27 inline 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.
36 template <typename FnT>
37 class Cleanup {
38   public:
39     Cleanup() = delete;
Cleanup(FnT fn)40     explicit Cleanup(FnT fn) : mFn(fn) {}
~Cleanup()41     ~Cleanup() { if (!mReleased) mFn(); }
42 
release()43     void release() { mReleased = true; }
44 
45   private:
46     bool mReleased{false};
47     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; });
55 template <typename FnT>
makeCleanup(FnT fn)56 Cleanup<FnT> makeCleanup(FnT fn) {
57     return Cleanup<FnT>(fn);
58 }
59 
60 }  // namespace netdutils
61 }  // namespace android
62 
63 #endif /* NETUTILS_MISC_H */
64