util.h 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. /*
  2. * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  3. *
  4. * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
  5. *
  6. * Use of this source code is governed by MIT license that can be found in the
  7. * LICENSE file in the root of the source tree. All contributing project authors
  8. * may be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #ifndef UTIL_UTIL_H_
  11. #define UTIL_UTIL_H_
  12. #include <ctime>
  13. #include <stdio.h>
  14. #include <string.h>
  15. #include <memory>
  16. #include <string>
  17. #include <sstream>
  18. #include <vector>
  19. #include <atomic>
  20. #include <unordered_map>
  21. #if defined(_WIN32)
  22. #undef FD_SETSIZE
  23. //修改默认64为1024路
  24. #define FD_SETSIZE 1024
  25. #include <WinSock2.h>
  26. #pragma comment (lib,"WS2_32")
  27. #else
  28. #include <unistd.h>
  29. #include <sys/time.h>
  30. #include <sys/types.h>
  31. #include <stddef.h>
  32. #endif // defined(_WIN32)
  33. #if defined(__APPLE__)
  34. #include "TargetConditionals.h"
  35. #if TARGET_IPHONE_SIMULATOR
  36. #define OS_IPHONE
  37. #elif TARGET_OS_IPHONE
  38. #define OS_IPHONE
  39. #endif
  40. #endif //__APPLE__
  41. #define INSTANCE_IMP(class_name, ...) \
  42. class_name &class_name::Instance() { \
  43. static std::shared_ptr<class_name> s_instance(new class_name(__VA_ARGS__)); \
  44. static class_name &s_insteanc_ref = *s_instance; \
  45. return s_insteanc_ref; \
  46. }
  47. using namespace std;
  48. namespace toolkit {
  49. #define StrPrinter _StrPrinter()
  50. class _StrPrinter : public string {
  51. public:
  52. _StrPrinter() {}
  53. template<typename T>
  54. _StrPrinter& operator <<(T && data) {
  55. _stream << std::forward<T>(data);
  56. this->string::operator=(_stream.str());
  57. return *this;
  58. }
  59. string operator <<(std::ostream&(*f)(std::ostream&)) const {
  60. return *this;
  61. }
  62. private:
  63. stringstream _stream;
  64. };
  65. //禁止拷贝基类
  66. class noncopyable {
  67. protected:
  68. noncopyable() {}
  69. ~noncopyable() {}
  70. private:
  71. //禁止拷贝
  72. noncopyable(const noncopyable &that) = delete;
  73. noncopyable(noncopyable &&that) = delete;
  74. noncopyable &operator=(const noncopyable &that) = delete;
  75. noncopyable &operator=(noncopyable &&that) = delete;
  76. };
  77. //可以保存任意的对象
  78. class Any{
  79. public:
  80. typedef std::shared_ptr<Any> Ptr;
  81. Any() = default;
  82. ~Any() = default;
  83. template <typename C,typename ...ArgsType>
  84. void set(ArgsType &&...args){
  85. _data.reset(new C(std::forward<ArgsType>(args)...),[](void *ptr){
  86. delete (C*) ptr;
  87. });
  88. }
  89. template <typename C>
  90. C& get(){
  91. if(!_data){
  92. throw std::invalid_argument("Any is empty");
  93. }
  94. C *ptr = (C *)_data.get();
  95. return *ptr;
  96. }
  97. operator bool() {
  98. return _data.operator bool ();
  99. }
  100. bool empty(){
  101. return !bool();
  102. }
  103. private:
  104. std::shared_ptr<void> _data;
  105. };
  106. //用于保存一些外加属性
  107. class AnyStorage : public unordered_map<string,Any>{
  108. public:
  109. AnyStorage() = default;
  110. ~AnyStorage() = default;
  111. typedef std::shared_ptr<AnyStorage> Ptr;
  112. };
  113. //对象安全的构建和析构
  114. //构建后执行onCreate函数
  115. //析构前执行onDestory函数
  116. //在函数onCreate和onDestory中可以执行构造或析构中不能调用的方法,比如说shared_from_this或者虚函数
  117. class Creator {
  118. public:
  119. template<typename C,typename ...ArgsType>
  120. static std::shared_ptr<C> create(ArgsType &&...args){
  121. std::shared_ptr<C> ret(new C(std::forward<ArgsType>(args)...),[](C *ptr){
  122. ptr->onDestory();
  123. delete ptr;
  124. });
  125. ret->onCreate();
  126. return ret;
  127. }
  128. private:
  129. Creator() = default;
  130. ~Creator() = default;
  131. };
  132. template <class C>
  133. class ObjectStatistic{
  134. public:
  135. ObjectStatistic(){
  136. ++getCounter();
  137. }
  138. ~ObjectStatistic(){
  139. --getCounter();
  140. }
  141. static size_t count(){
  142. return getCounter().load();
  143. }
  144. private:
  145. static atomic<size_t> & getCounter();
  146. };
  147. #define StatisticImp(Type) \
  148. template<> \
  149. atomic<size_t>& ObjectStatistic<Type>::getCounter(){ \
  150. static atomic<size_t> instance(0); \
  151. return instance; \
  152. }
  153. string makeRandStr(int sz, bool printable = true);
  154. string hexdump(const void *buf, size_t len);
  155. string hexmem(const void* buf, size_t len);
  156. string exePath();
  157. string exeDir();
  158. string exeName();
  159. vector<string> split(const string& s, const char *delim);
  160. //去除前后的空格、回车符、制表符...
  161. std::string& trim(std::string &s,const string &chars=" \r\n\t");
  162. std::string trim(std::string &&s,const string &chars=" \r\n\t");
  163. // string转小写
  164. std::string &strToLower(std::string &str);
  165. std::string strToLower(std::string &&str);
  166. // string转大写
  167. std::string &strToUpper(std::string &str);
  168. std::string strToUpper(std::string &&str);
  169. //替换子字符串
  170. void replace(string &str, const string &old_str, const string &new_str) ;
  171. //判断是否为ip
  172. bool isIP(const char *str);
  173. //字符串是否以xx开头
  174. bool start_with(const string &str, const string &substr);
  175. //字符串是否以xx结尾
  176. bool end_with(const string &str, const string &substr);
  177. #ifndef bzero
  178. #define bzero(ptr,size) memset((ptr),0,(size));
  179. #endif //bzero
  180. #if defined(ANDROID)
  181. template <typename T>
  182. std::string to_string(T value){
  183. std::ostringstream os ;
  184. os << std::forward<T>(value);
  185. return os.str() ;
  186. }
  187. #endif//ANDROID
  188. #if defined(_WIN32)
  189. int gettimeofday(struct timeval *tp, void *tzp);
  190. void usleep(int micro_seconds);
  191. void sleep(int second);
  192. int asprintf(char **strp, const char *fmt, ...);
  193. const char *strcasestr(const char *big, const char *little);
  194. #if !defined(strcasecmp)
  195. #define strcasecmp _stricmp
  196. #endif
  197. #ifndef ssize_t
  198. #ifdef _WIN64
  199. #define ssize_t int64_t
  200. #else
  201. #define ssize_t int32_t
  202. #endif
  203. #endif
  204. #endif //WIN32
  205. /**
  206. * 获取1970年至今的毫秒数
  207. * @param system_time 是否为系统时间(系统时间可以回退),否则为程序启动时间(不可回退)
  208. */
  209. uint64_t getCurrentMillisecond(bool system_time = false);
  210. /**
  211. * 获取1970年至今的微秒数
  212. * @param system_time 是否为系统时间(系统时间可以回退),否则为程序启动时间(不可回退)
  213. */
  214. uint64_t getCurrentMicrosecond(bool system_time = false);
  215. /**
  216. * 获取时间字符串
  217. * @param fmt 时间格式,譬如%Y-%m-%d %H:%M:%S
  218. * @return 时间字符串
  219. */
  220. string getTimeStr(const char *fmt,time_t time = 0);
  221. /**
  222. * 根据unix时间戳获取本地时间
  223. * @param sec unix时间戳
  224. * @return tm结构体
  225. */
  226. struct tm getLocalTime(time_t sec);
  227. /**
  228. * 设置线程名
  229. */
  230. void setThreadName(const char *name);
  231. /**
  232. * 获取线程名
  233. */
  234. string getThreadName();
  235. } // namespace toolkit
  236. #endif /* UTIL_UTIL_H_ */