utilities.hpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // Copyright (c) rAthena Dev Teams - Licensed under GNU GPL
  2. // For more information, see LICENCE in the main folder
  3. #ifndef UTILILITIES_HPP
  4. #define UTILILITIES_HPP
  5. #include <map>
  6. #include <memory>
  7. #include <string>
  8. #include <unordered_map>
  9. #include "cbasetypes.hpp"
  10. // Class used to perform time measurement
  11. class cScopeTimer {
  12. struct sPimpl; //this is to avoid long compilation time
  13. std::unique_ptr<sPimpl> aPimpl;
  14. cScopeTimer();
  15. };
  16. int levenshtein( const std::string &s1, const std::string &s2 );
  17. namespace rathena {
  18. namespace util {
  19. template <typename K, typename V> bool map_exists( std::map<K,V>& map, K key ){
  20. return map.find( key ) != map.end();
  21. }
  22. /**
  23. * Find a key-value pair and return the key value as a reference
  24. * @param map: Map to search through
  25. * @param key: Key wanted
  26. * @return Key value on success or nullptr on failure
  27. */
  28. template <typename K, typename V> V* map_find( std::map<K,V>& map, K key ){
  29. auto it = map.find( key );
  30. if( it != map.end() ){
  31. return &it->second;
  32. }else{
  33. return nullptr;
  34. }
  35. }
  36. /**
  37. * Get a key-value pair and return the key value
  38. * @param map: Map to search through
  39. * @param key: Key wanted
  40. * @param defaultValue: Value returned if key doesn't exist
  41. * @return Key value on success or defaultValue on failure
  42. */
  43. template <typename K, typename V> V map_get(std::map<K, V>& map, K key, V defaultValue) {
  44. auto it = map.find(key);
  45. if (it != map.end())
  46. return it->second;
  47. else
  48. return defaultValue;
  49. }
  50. /**
  51. * Find a key-value pair and return the key value as a reference
  52. * @param map: Unordered Map to search through
  53. * @param key: Key wanted
  54. * @return Key value on success or nullptr on failure
  55. */
  56. template <typename K, typename V> V* umap_find(std::unordered_map<K, V>& map, K key) {
  57. auto it = map.find(key);
  58. if (it != map.end())
  59. return &it->second;
  60. else
  61. return nullptr;
  62. }
  63. /**
  64. * Get a key-value pair and return the key value
  65. * @param map: Unordered Map to search through
  66. * @param key: Key wanted
  67. * @param defaultValue: Value returned if key doesn't exist
  68. * @return Key value on success or defaultValue on failure
  69. */
  70. template <typename K, typename V> V umap_get(std::unordered_map<K, V>& map, K key, V defaultValue) {
  71. auto it = map.find(key);
  72. if (it != map.end())
  73. return it->second;
  74. else
  75. return defaultValue;
  76. }
  77. }
  78. }
  79. #endif /* UTILILITIES_HPP */