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> 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; 40 Cleanup(FnT fn) : mFn(fn) {} 41 ~Cleanup() { mFn(); } 42 43 void release() { mFn = {}; } 44 45 private: 46 FnT mFn; 47 }; 48 49 // Helper to make a new Cleanup. Avoids complex or impossible syntax 50 // when wrapping lambdas. 51 // 52 // Usage: 53 // auto cleanup = makeCleanup([](){ your_code_here; }); 54 template <typename FnT> 55 Cleanup<FnT> makeCleanup(FnT fn) { 56 return Cleanup<FnT>(fn); 57 } 58 59 } // namespace netdutils 60 } // namespace android 61 62 #endif /* NETUTILS_MISC_H */ 63