utilities.h 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098
  1. /*
  2. * SRT - Secure, Reliable, Transport
  3. * Copyright (c) 2018 Haivision Systems Inc.
  4. *
  5. * This Source Code Form is subject to the terms of the Mozilla Public
  6. * License, v. 2.0. If a copy of the MPL was not distributed with this
  7. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  8. *
  9. */
  10. /*****************************************************************************
  11. written by
  12. Haivision Systems Inc.
  13. *****************************************************************************/
  14. #ifndef INC_SRT_UTILITIES_H
  15. #define INC_SRT_UTILITIES_H
  16. // Windows warning disabler
  17. #define _CRT_SECURE_NO_WARNINGS 1
  18. #include "platform_sys.h"
  19. #include "srt_attr_defs.h" // defines HAVE_CXX11
  20. // Happens that these are defined, undefine them in advance
  21. #undef min
  22. #undef max
  23. #include <string>
  24. #include <algorithm>
  25. #include <bitset>
  26. #include <map>
  27. #include <vector>
  28. #include <functional>
  29. #include <memory>
  30. #include <iomanip>
  31. #include <sstream>
  32. #if HAVE_CXX11
  33. #include <type_traits>
  34. #endif
  35. #include <cstdlib>
  36. #include <cerrno>
  37. #include <cstring>
  38. #include <stdexcept>
  39. // -------------- UTILITIES ------------------------
  40. // --- ENDIAN ---
  41. // Copied from: https://gist.github.com/panzi/6856583
  42. // License: Public Domain.
  43. #if (defined(_WIN16) || defined(_WIN32) || defined(_WIN64)) && !defined(__WINDOWS__)
  44. # define __WINDOWS__
  45. #endif
  46. #if defined(__linux__) || defined(__CYGWIN__) || defined(__GNU__) || defined(__GLIBC__)
  47. # include <endian.h>
  48. // GLIBC-2.8 and earlier does not provide these macros.
  49. // See http://linux.die.net/man/3/endian
  50. // From https://gist.github.com/panzi/6856583
  51. # if defined(__GLIBC__) \
  52. && ( !defined(__GLIBC_MINOR__) \
  53. || ((__GLIBC__ < 2) \
  54. || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ < 9))) )
  55. # include <arpa/inet.h>
  56. # if defined(__BYTE_ORDER) && (__BYTE_ORDER == __LITTLE_ENDIAN)
  57. # define htole32(x) (x)
  58. # define le32toh(x) (x)
  59. # elif defined(__BYTE_ORDER) && (__BYTE_ORDER == __BIG_ENDIAN)
  60. # define htole16(x) ((((((uint16_t)(x)) >> 8))|((((uint16_t)(x)) << 8)))
  61. # define le16toh(x) ((((((uint16_t)(x)) >> 8))|((((uint16_t)(x)) << 8)))
  62. # define htole32(x) (((uint32_t)htole16(((uint16_t)(((uint32_t)(x)) >> 16)))) | (((uint32_t)htole16(((uint16_t)(x)))) << 16))
  63. # define le32toh(x) (((uint32_t)le16toh(((uint16_t)(((uint32_t)(x)) >> 16)))) | (((uint32_t)le16toh(((uint16_t)(x)))) << 16))
  64. # else
  65. # error Byte Order not supported or not defined.
  66. # endif
  67. # endif
  68. #elif defined(__APPLE__)
  69. # include <libkern/OSByteOrder.h>
  70. # define htobe16(x) OSSwapHostToBigInt16(x)
  71. # define htole16(x) OSSwapHostToLittleInt16(x)
  72. # define be16toh(x) OSSwapBigToHostInt16(x)
  73. # define le16toh(x) OSSwapLittleToHostInt16(x)
  74. # define htobe32(x) OSSwapHostToBigInt32(x)
  75. # define htole32(x) OSSwapHostToLittleInt32(x)
  76. # define be32toh(x) OSSwapBigToHostInt32(x)
  77. # define le32toh(x) OSSwapLittleToHostInt32(x)
  78. # define htobe64(x) OSSwapHostToBigInt64(x)
  79. # define htole64(x) OSSwapHostToLittleInt64(x)
  80. # define be64toh(x) OSSwapBigToHostInt64(x)
  81. # define le64toh(x) OSSwapLittleToHostInt64(x)
  82. # define __BYTE_ORDER BYTE_ORDER
  83. # define __BIG_ENDIAN BIG_ENDIAN
  84. # define __LITTLE_ENDIAN LITTLE_ENDIAN
  85. # define __PDP_ENDIAN PDP_ENDIAN
  86. #elif defined(__OpenBSD__)
  87. # include <sys/endian.h>
  88. #elif defined(__NetBSD__) || defined(__FreeBSD__) || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
  89. # include <sys/endian.h>
  90. #ifndef be16toh
  91. # define be16toh(x) betoh16(x)
  92. #endif
  93. #ifndef le16toh
  94. # define le16toh(x) letoh16(x)
  95. #endif
  96. #ifndef be32toh
  97. # define be32toh(x) betoh32(x)
  98. #endif
  99. #ifndef le32toh
  100. # define le32toh(x) letoh32(x)
  101. #endif
  102. #ifndef be64toh
  103. # define be64toh(x) betoh64(x)
  104. #endif
  105. #ifndef le64toh
  106. # define le64toh(x) letoh64(x)
  107. #endif
  108. #elif defined(SUNOS)
  109. // SunOS/Solaris
  110. #include <sys/byteorder.h>
  111. #include <sys/isa_defs.h>
  112. #define __LITTLE_ENDIAN 1234
  113. #define __BIG_ENDIAN 4321
  114. # if defined(_BIG_ENDIAN)
  115. #define __BYTE_ORDER __BIG_ENDIAN
  116. #define be64toh(x) (x)
  117. #define be32toh(x) (x)
  118. #define be16toh(x) (x)
  119. #define le16toh(x) ((uint16_t)BSWAP_16(x))
  120. #define le32toh(x) BSWAP_32(x)
  121. #define le64toh(x) BSWAP_64(x)
  122. #define htobe16(x) (x)
  123. #define htole16(x) ((uint16_t)BSWAP_16(x))
  124. #define htobe32(x) (x)
  125. #define htole32(x) BSWAP_32(x)
  126. #define htobe64(x) (x)
  127. #define htole64(x) BSWAP_64(x)
  128. # else
  129. #define __BYTE_ORDER __LITTLE_ENDIAN
  130. #define be64toh(x) BSWAP_64(x)
  131. #define be32toh(x) ntohl(x)
  132. #define be16toh(x) ntohs(x)
  133. #define le16toh(x) (x)
  134. #define le32toh(x) (x)
  135. #define le64toh(x) (x)
  136. #define htobe16(x) htons(x)
  137. #define htole16(x) (x)
  138. #define htobe32(x) htonl(x)
  139. #define htole32(x) (x)
  140. #define htobe64(x) BSWAP_64(x)
  141. #define htole64(x) (x)
  142. # endif
  143. #elif defined(__WINDOWS__)
  144. # include <winsock2.h>
  145. # if BYTE_ORDER == LITTLE_ENDIAN
  146. # define htobe16(x) htons(x)
  147. # define htole16(x) (x)
  148. # define be16toh(x) ntohs(x)
  149. # define le16toh(x) (x)
  150. # define htobe32(x) htonl(x)
  151. # define htole32(x) (x)
  152. # define be32toh(x) ntohl(x)
  153. # define le32toh(x) (x)
  154. # define htobe64(x) htonll(x)
  155. # define htole64(x) (x)
  156. # define be64toh(x) ntohll(x)
  157. # define le64toh(x) (x)
  158. # elif BYTE_ORDER == BIG_ENDIAN
  159. /* that would be xbox 360 */
  160. # define htobe16(x) (x)
  161. # define htole16(x) __builtin_bswap16(x)
  162. # define be16toh(x) (x)
  163. # define le16toh(x) __builtin_bswap16(x)
  164. # define htobe32(x) (x)
  165. # define htole32(x) __builtin_bswap32(x)
  166. # define be32toh(x) (x)
  167. # define le32toh(x) __builtin_bswap32(x)
  168. # define htobe64(x) (x)
  169. # define htole64(x) __builtin_bswap64(x)
  170. # define be64toh(x) (x)
  171. # define le64toh(x) __builtin_bswap64(x)
  172. # else
  173. # error byte order not supported
  174. # endif
  175. # define __BYTE_ORDER BYTE_ORDER
  176. # define __BIG_ENDIAN BIG_ENDIAN
  177. # define __LITTLE_ENDIAN LITTLE_ENDIAN
  178. # define __PDP_ENDIAN PDP_ENDIAN
  179. #else
  180. # error Endian: platform not supported
  181. #endif
  182. // Hardware <--> Network (big endian) convention
  183. inline void HtoNLA(uint32_t* dst, const uint32_t* src, size_t size)
  184. {
  185. for (size_t i = 0; i < size; ++ i)
  186. dst[i] = htonl(src[i]);
  187. }
  188. inline void NtoHLA(uint32_t* dst, const uint32_t* src, size_t size)
  189. {
  190. for (size_t i = 0; i < size; ++ i)
  191. dst[i] = ntohl(src[i]);
  192. }
  193. // Hardware <--> Intel (little endian) convention
  194. inline void HtoILA(uint32_t* dst, const uint32_t* src, size_t size)
  195. {
  196. for (size_t i = 0; i < size; ++ i)
  197. dst[i] = htole32(src[i]);
  198. }
  199. inline void ItoHLA(uint32_t* dst, const uint32_t* src, size_t size)
  200. {
  201. for (size_t i = 0; i < size; ++ i)
  202. dst[i] = le32toh(src[i]);
  203. }
  204. // Bit numbering utility.
  205. //
  206. // This is something that allows you to turn 32-bit integers into bit fields.
  207. // Although bitfields are part of C++ language, they are not designed to be
  208. // interchanged with 32-bit numbers, and any attempt to doing it (by placing
  209. // inside a union, for example) is nonportable (order of bitfields inside
  210. // same-covering 32-bit integer number is dependent on the endian), so they are
  211. // popularly disregarded as useless. Instead the 32-bit numbers with bits
  212. // individually selected is preferred, with usually manual playing around with
  213. // & and | operators, as well as << and >>. This tool is designed to simplify
  214. // the use of them. This can be used to qualify a range of bits inside a 32-bit
  215. // number to be a separate number, you can "wrap" it by placing the integer
  216. // value in the range of these bits, as well as "unwrap" (extract) it from
  217. // the given place. For your own safety, use one prefix to all constants that
  218. // concern bit ranges intended to be inside the same "bit container".
  219. //
  220. // Usage: typedef Bits<leftmost, rightmost> MASKTYPE; // MASKTYPE is a name of your choice.
  221. //
  222. // With this defined, you can use the following members:
  223. // - MASKTYPE::mask - to get the int32_t value with bimask (used bits set to 1, others to 0)
  224. // - MASKTYPE::offset - to get the lowermost bit number, or number of bits to shift
  225. // - MASKTYPE::wrap(int value) - to create a bitset where given value is encoded in given bits
  226. // - MASKTYPE::unwrap(int bitset) - to extract an integer value from the bitset basing on mask definition
  227. // (rightmost defaults to leftmost)
  228. // REMEMBER: leftmost > rightmost because bit 0 is the LEAST significant one!
  229. template <size_t L, size_t R, bool parent_correct = true>
  230. struct BitsetMask
  231. {
  232. static const bool correct = L >= R;
  233. static const uint32_t value = (1u << L) | BitsetMask<L-1, R, correct>::value;
  234. };
  235. // This is kind-of functional programming. This describes a special case that is
  236. // a "terminal case" in case when decreased L-1 (see above) reached == R.
  237. template<size_t R>
  238. struct BitsetMask<R, R, true>
  239. {
  240. static const bool correct = true;
  241. static const uint32_t value = 1u << R;
  242. };
  243. // This is a trap for a case that BitsetMask::correct in the master template definition
  244. // evaluates to false. This trap causes compile error and prevents from continuing
  245. // recursive unwinding in wrong direction (and challenging the compiler's resistiveness
  246. // for infinite loops).
  247. template <size_t L, size_t R>
  248. struct BitsetMask<L, R, false>
  249. {
  250. };
  251. template <size_t L, size_t R = L>
  252. struct Bits
  253. {
  254. // DID YOU GET a kind-of error: 'mask' is not a member of 'Bits<3u, 5u, false>'?
  255. // See the the above declaration of 'correct'!
  256. static const uint32_t mask = BitsetMask<L, R>::value;
  257. static const uint32_t offset = R;
  258. static const size_t size = L - R + 1;
  259. // Example: if our bitset mask is 00111100, this checks if given value fits in
  260. // 00001111 mask (that is, does not exceed <0, 15>.
  261. static bool fit(uint32_t value) { return (BitsetMask<L-R, 0>::value & value) == value; }
  262. /// 'wrap' gets some given value that should be placed in appropriate bit range and
  263. /// returns a whole 32-bit word that has the value already at specified place.
  264. /// To create a 32-bit container that contains already all values destined for different
  265. /// bit ranges, simply use wrap() for each of them and bind them with | operator.
  266. static uint32_t wrap(uint32_t baseval) { return (baseval << offset) & mask; }
  267. /// Extracts appropriate bit range and returns them as normal integer value.
  268. static uint32_t unwrap(uint32_t bitset) { return (bitset & mask) >> offset; }
  269. template<class T>
  270. static T unwrapt(uint32_t bitset) { return static_cast<T>(unwrap(bitset)); }
  271. };
  272. //inline int32_t Bit(size_t b) { return 1 << b; }
  273. // XXX This would work only with 'constexpr', but this is
  274. // available only in C++11. In C++03 this can be only done
  275. // using a macro.
  276. //
  277. // Actually this can be expressed in C++11 using a better technique,
  278. // such as user-defined literals:
  279. // 2_bit --> 1 >> 2
  280. #ifdef BIT
  281. #undef BIT
  282. #endif
  283. #define BIT(x) (1 << (x))
  284. // ------------------------------------------------------------
  285. // This is something that reminds a structure consisting of fields
  286. // of the same type, implemented as an array. It's parametrized
  287. // by the type of fields and the type, which's values should be
  288. // used for indexing (preferably an enum type). Whatever type is
  289. // used for indexing, it is converted to size_t for indexing the
  290. // actual array.
  291. //
  292. // The user should use it as an array: ds[DS_NAME], stating
  293. // that DS_NAME is of enum type passed as 3rd parameter.
  294. // However trying to do ds[0] would cause a compile error.
  295. template <typename FieldType, size_t NoOfFields, typename IndexerType>
  296. struct DynamicStruct
  297. {
  298. FieldType inarray[NoOfFields];
  299. void clear()
  300. {
  301. // As a standard library, it can be believed that this call
  302. // can be optimized when FieldType is some integer.
  303. std::fill(inarray, inarray + NoOfFields, FieldType());
  304. }
  305. FieldType operator[](IndexerType ix) const { return inarray[size_t(ix)]; }
  306. FieldType& operator[](IndexerType ix) { return inarray[size_t(ix)]; }
  307. template<class AnyOther>
  308. FieldType operator[](AnyOther ix) const
  309. {
  310. // If you can see a compile error here ('int' is not a class or struct, or
  311. // that there's no definition of 'type' in given type), it means that you
  312. // have used invalid data type passed to [] operator. See the definition
  313. // of this type as DynamicStruct and see which type is required for indexing.
  314. typename AnyOther::type wrong_usage_of_operator_index = AnyOther::type;
  315. return inarray[size_t(ix)];
  316. }
  317. template<class AnyOther>
  318. FieldType& operator[](AnyOther ix)
  319. {
  320. // If you can see a compile error here ('int' is not a class or struct, or
  321. // that there's no definition of 'type' in given type), it means that you
  322. // have used invalid data type passed to [] operator. See the definition
  323. // of this type as DynamicStruct and see which type is required for indexing.
  324. typename AnyOther::type wrong_usage_of_operator_index = AnyOther::type;
  325. return inarray[size_t(ix)];
  326. }
  327. operator FieldType* () { return inarray; }
  328. operator const FieldType* () const { return inarray; }
  329. char* raw() { return (char*)inarray; }
  330. };
  331. /// Fixed-size array template class.
  332. namespace srt {
  333. template <class T>
  334. class FixedArray
  335. {
  336. public:
  337. FixedArray(size_t size)
  338. : m_size(size)
  339. , m_entries(new T[size])
  340. {
  341. }
  342. ~FixedArray()
  343. {
  344. delete [] m_entries;
  345. }
  346. public:
  347. const T& operator[](size_t index) const
  348. {
  349. if (index >= m_size)
  350. raise_expection(index);
  351. return m_entries[index];
  352. }
  353. T& operator[](size_t index)
  354. {
  355. if (index >= m_size)
  356. raise_expection(index);
  357. return m_entries[index];
  358. }
  359. const T& operator[](int index) const
  360. {
  361. if (index < 0 || static_cast<size_t>(index) >= m_size)
  362. raise_expection(index);
  363. return m_entries[index];
  364. }
  365. T& operator[](int index)
  366. {
  367. if (index < 0 || static_cast<size_t>(index) >= m_size)
  368. raise_expection(index);
  369. return m_entries[index];
  370. }
  371. size_t size() const { return m_size; }
  372. typedef T* iterator;
  373. typedef const T* const_iterator;
  374. iterator begin() { return m_entries; }
  375. iterator end() { return m_entries + m_size; }
  376. const_iterator cbegin() const { return m_entries; }
  377. const_iterator cend() const { return m_entries + m_size; }
  378. T* data() { return m_entries; }
  379. private:
  380. FixedArray(const FixedArray<T>& );
  381. FixedArray<T>& operator=(const FixedArray<T>&);
  382. void raise_expection(int i) const
  383. {
  384. std::stringstream ss;
  385. ss << "Index " << i << "out of range";
  386. throw std::runtime_error(ss.str());
  387. }
  388. private:
  389. size_t m_size;
  390. T* const m_entries;
  391. };
  392. } // namespace srt
  393. // ------------------------------------------------------------
  394. inline bool IsSet(int32_t bitset, int32_t flagset)
  395. {
  396. return (bitset & flagset) == flagset;
  397. }
  398. // std::addressof in C++11,
  399. // needs to be provided for C++03
  400. template <class RefType>
  401. inline RefType* AddressOf(RefType& r)
  402. {
  403. return (RefType*)(&(unsigned char&)(r));
  404. }
  405. template <class T>
  406. struct explicit_t
  407. {
  408. T inobject;
  409. explicit_t(const T& uo): inobject(uo) {}
  410. operator T() const { return inobject; }
  411. private:
  412. template <class X>
  413. explicit_t(const X& another);
  414. };
  415. // This is required for Printable function if you have a container of pairs,
  416. // but this function has a different definition for C++11 and C++03.
  417. namespace srt_pair_op
  418. {
  419. template <class Value1, class Value2>
  420. std::ostream& operator<<(std::ostream& s, const std::pair<Value1, Value2>& v)
  421. {
  422. s << "{" << v.first << " " << v.second << "}";
  423. return s;
  424. }
  425. }
  426. #if HAVE_CXX11
  427. template <class In>
  428. inline auto Move(In& i) -> decltype(std::move(i)) { return std::move(i); }
  429. // Gluing string of any type, wrapper for operator <<
  430. template <class Stream>
  431. inline Stream& Print(Stream& in) { return in;}
  432. template <class Stream, class Arg1, class... Args>
  433. inline Stream& Print(Stream& sout, Arg1&& arg1, Args&&... args)
  434. {
  435. sout << arg1;
  436. return Print(sout, args...);
  437. }
  438. template <class... Args>
  439. inline std::string Sprint(Args&&... args)
  440. {
  441. std::ostringstream sout;
  442. Print(sout, args...);
  443. return sout.str();
  444. }
  445. // We need to use UniquePtr, in the form of C++03 it will be a #define.
  446. // Naturally will be used std::move() so that it can later painlessly
  447. // switch to C++11.
  448. template <class T>
  449. using UniquePtr = std::unique_ptr<T>;
  450. template <class Container, class Value = typename Container::value_type, typename... Args> inline
  451. std::string Printable(const Container& in, Value /*pseudoargument*/, Args&&... args)
  452. {
  453. using namespace srt_pair_op;
  454. std::ostringstream os;
  455. Print(os, args...);
  456. os << "[ ";
  457. for (auto i: in)
  458. os << Value(i) << " ";
  459. os << "]";
  460. return os.str();
  461. }
  462. template <class Container> inline
  463. std::string Printable(const Container& in)
  464. {
  465. using namespace srt_pair_op;
  466. using Value = typename Container::value_type;
  467. return Printable(in, Value());
  468. }
  469. template<typename Map, typename Key>
  470. auto map_get(Map& m, const Key& key, typename Map::mapped_type def = typename Map::mapped_type()) -> typename Map::mapped_type
  471. {
  472. auto it = m.find(key);
  473. return it == m.end() ? def : it->second;
  474. }
  475. template<typename Map, typename Key>
  476. auto map_getp(Map& m, const Key& key) -> typename Map::mapped_type*
  477. {
  478. auto it = m.find(key);
  479. return it == m.end() ? nullptr : std::addressof(it->second);
  480. }
  481. template<typename Map, typename Key>
  482. auto map_getp(const Map& m, const Key& key) -> typename Map::mapped_type const*
  483. {
  484. auto it = m.find(key);
  485. return it == m.end() ? nullptr : std::addressof(it->second);
  486. }
  487. #else
  488. // The unique_ptr requires C++11, and the rvalue-reference feature,
  489. // so here we're simulate the behavior using the old std::auto_ptr.
  490. // This is only to make a "move" call transparent and look ok towards
  491. // the C++11 code.
  492. template <class T>
  493. std::auto_ptr_ref<T> Move(const std::auto_ptr_ref<T>& in) { return in; }
  494. // We need to provide also some fixes for this type that were not present in auto_ptr,
  495. // but they are present in unique_ptr.
  496. // C++03 doesn't have a templated typedef, but still we need some things
  497. // that can only function as a class.
  498. template <class T>
  499. class UniquePtr: public std::auto_ptr<T>
  500. {
  501. typedef std::auto_ptr<T> Base;
  502. public:
  503. // This is a template - so method names must be declared explicitly
  504. typedef typename Base::element_type element_type;
  505. using Base::get;
  506. using Base::reset;
  507. // All constructor declarations must be repeated.
  508. // "Constructor delegation" is also only C++11 feature.
  509. explicit UniquePtr(element_type* p = 0) throw() : Base(p) {}
  510. UniquePtr(UniquePtr& a) throw() : Base(a) { }
  511. template<typename Type1>
  512. UniquePtr(UniquePtr<Type1>& a) throw() : Base(a) {}
  513. UniquePtr& operator=(UniquePtr& a) throw() { return Base::operator=(a); }
  514. template<typename Type1>
  515. UniquePtr& operator=(UniquePtr<Type1>& a) throw() { return Base::operator=(a); }
  516. // Good, now we need to add some parts of the API of unique_ptr.
  517. bool operator==(const UniquePtr& two) const { return get() == two.get(); }
  518. bool operator!=(const UniquePtr& two) const { return get() != two.get(); }
  519. bool operator==(const element_type* two) const { return get() == two; }
  520. bool operator!=(const element_type* two) const { return get() != two; }
  521. operator bool () { return 0!= get(); }
  522. };
  523. // A primitive one-argument versions of Sprint and Printable
  524. template <class Arg1>
  525. inline std::string Sprint(const Arg1& arg)
  526. {
  527. std::ostringstream sout;
  528. sout << arg;
  529. return sout.str();
  530. }
  531. template <class Container> inline
  532. std::string Printable(const Container& in)
  533. {
  534. using namespace srt_pair_op;
  535. typedef typename Container::value_type Value;
  536. std::ostringstream os;
  537. os << "[ ";
  538. for (typename Container::const_iterator i = in.begin(); i != in.end(); ++i)
  539. os << Value(*i) << " ";
  540. os << "]";
  541. return os.str();
  542. }
  543. template<typename Map, typename Key>
  544. typename Map::mapped_type map_get(Map& m, const Key& key, typename Map::mapped_type def = typename Map::mapped_type())
  545. {
  546. typename Map::iterator it = m.find(key);
  547. return it == m.end() ? def : it->second;
  548. }
  549. template<typename Map, typename Key>
  550. typename Map::mapped_type map_get(const Map& m, const Key& key, typename Map::mapped_type def = typename Map::mapped_type())
  551. {
  552. typename Map::const_iterator it = m.find(key);
  553. return it == m.end() ? def : it->second;
  554. }
  555. template<typename Map, typename Key>
  556. typename Map::mapped_type* map_getp(Map& m, const Key& key)
  557. {
  558. typename Map::iterator it = m.find(key);
  559. return it == m.end() ? (typename Map::mapped_type*)0 : &(it->second);
  560. }
  561. template<typename Map, typename Key>
  562. typename Map::mapped_type const* map_getp(const Map& m, const Key& key)
  563. {
  564. typename Map::const_iterator it = m.find(key);
  565. return it == m.end() ? (typename Map::mapped_type*)0 : &(it->second);
  566. }
  567. #endif
  568. // Printable with prefix added for every element.
  569. // Useful when printing a container of sockets or sequence numbers.
  570. template <class Container> inline
  571. std::string PrintableMod(const Container& in, const std::string& prefix)
  572. {
  573. using namespace srt_pair_op;
  574. typedef typename Container::value_type Value;
  575. std::ostringstream os;
  576. os << "[ ";
  577. for (typename Container::const_iterator y = in.begin(); y != in.end(); ++y)
  578. os << prefix << Value(*y) << " ";
  579. os << "]";
  580. return os.str();
  581. }
  582. template<typename InputIterator, typename OutputIterator, typename TransFunction>
  583. inline void FilterIf(InputIterator bg, InputIterator nd,
  584. OutputIterator out, TransFunction fn)
  585. {
  586. for (InputIterator i = bg; i != nd; ++i)
  587. {
  588. std::pair<typename TransFunction::result_type, bool> result = fn(*i);
  589. if (!result.second)
  590. continue;
  591. *out++ = result.first;
  592. }
  593. }
  594. template <class Value, class ArgValue>
  595. inline void insert_uniq(std::vector<Value>& v, const ArgValue& val)
  596. {
  597. typename std::vector<Value>::iterator i = std::find(v.begin(), v.end(), val);
  598. if (i != v.end())
  599. return;
  600. v.push_back(val);
  601. }
  602. template <class Signature>
  603. struct CallbackHolder
  604. {
  605. void* opaque;
  606. Signature* fn;
  607. CallbackHolder(): opaque(NULL), fn(NULL) {}
  608. void set(void* o, Signature* f)
  609. {
  610. // Test if the pointer is a pointer to function. Don't let
  611. // other type of pointers here.
  612. #if HAVE_CXX11
  613. static_assert(std::is_function<Signature>::value, "CallbackHolder is for functions only!");
  614. #else
  615. // This is a poor-man's replacement, which should in most compilers
  616. // generate a warning, if `Signature` resolves to a value type.
  617. // This would make an illegal pointer cast from a value to a function type.
  618. // Casting function-to-function, however, should not. Unfortunately
  619. // newer compilers disallow that, too (when a signature differs), but
  620. // then they should better use the C++11 way, much more reliable and safer.
  621. void* (*testfn)(void*) = (void*(*)(void*))f;
  622. (void)(testfn);
  623. #endif
  624. opaque = o;
  625. fn = f;
  626. }
  627. operator bool() { return fn != NULL; }
  628. };
  629. #define CALLBACK_CALL(holder,...) (*holder.fn)(holder.opaque, __VA_ARGS__)
  630. inline std::string FormatBinaryString(const uint8_t* bytes, size_t size)
  631. {
  632. if ( size == 0 )
  633. return "";
  634. //char buf[256];
  635. using namespace std;
  636. ostringstream os;
  637. // I know, it's funny to use sprintf and ostringstream simultaneously,
  638. // but " %02X" in iostream is: << " " << hex << uppercase << setw(2) << setfill('0') << VALUE << setw(1)
  639. // Too noisy. OTOH ostringstream solves the problem of memory allocation
  640. // for a string of unpredictable size.
  641. //sprintf(buf, "%02X", int(bytes[0]));
  642. os.fill('0');
  643. os.width(2);
  644. os.setf(ios::basefield, ios::hex);
  645. os.setf(ios::uppercase);
  646. //os << buf;
  647. os << int(bytes[0]);
  648. for (size_t i = 1; i < size; ++i)
  649. {
  650. //sprintf(buf, " %02X", int(bytes[i]));
  651. //os << buf;
  652. os << int(bytes[i]);
  653. }
  654. return os.str();
  655. }
  656. /// This class is useful in every place where
  657. /// the time drift should be traced. It's currently in use in every
  658. /// solution that implements any kind of TSBPD.
  659. template<unsigned MAX_SPAN, int MAX_DRIFT, bool CLEAR_ON_UPDATE = true>
  660. class DriftTracer
  661. {
  662. int64_t m_qDrift;
  663. int64_t m_qOverdrift;
  664. int64_t m_qDriftSum;
  665. unsigned m_uDriftSpan;
  666. public:
  667. DriftTracer()
  668. : m_qDrift(0)
  669. , m_qOverdrift(0)
  670. , m_qDriftSum(0)
  671. , m_uDriftSpan(0)
  672. {}
  673. bool update(int64_t driftval)
  674. {
  675. m_qDriftSum += driftval;
  676. ++m_uDriftSpan;
  677. // I moved it here to calculate accumulated overdrift.
  678. if (CLEAR_ON_UPDATE)
  679. m_qOverdrift = 0;
  680. if (m_uDriftSpan < MAX_SPAN)
  681. return false;
  682. // Calculate the median of all drift values.
  683. // In most cases, the divisor should be == MAX_SPAN.
  684. m_qDrift = m_qDriftSum / m_uDriftSpan;
  685. // And clear the collection
  686. m_qDriftSum = 0;
  687. m_uDriftSpan = 0;
  688. // In case of "overdrift", save the overdriven value in 'm_qOverdrift'.
  689. // In clear mode, you should add this value to the time base when update()
  690. // returns true. The drift value will be since now measured with the
  691. // overdrift assumed to be added to the base.
  692. if (std::abs(m_qDrift) > MAX_DRIFT)
  693. {
  694. m_qOverdrift = m_qDrift < 0 ? -MAX_DRIFT : MAX_DRIFT;
  695. m_qDrift -= m_qOverdrift;
  696. }
  697. // printDriftOffset(m_qOverdrift, m_qDrift);
  698. // Timebase is separate
  699. // m_qTimeBase += m_qOverdrift;
  700. return true;
  701. }
  702. // For group overrides
  703. void forceDrift(int64_t driftval)
  704. {
  705. m_qDrift = driftval;
  706. }
  707. // These values can be read at any time, however if you want
  708. // to depend on the fact that they have been changed lately,
  709. // you have to check the return value from update().
  710. //
  711. // IMPORTANT: drift() can be called at any time, just remember
  712. // that this value may look different than before only if the
  713. // last update() returned true, which need not be important for you.
  714. //
  715. // CASE: CLEAR_ON_UPDATE = true
  716. // overdrift() should be read only immediately after update() returned
  717. // true. It will stay available with this value until the next time when
  718. // update() returns true, in which case the value will be cleared.
  719. // Therefore, after calling update() if it retuns true, you should read
  720. // overdrift() immediately an make some use of it. Next valid overdrift
  721. // will be then relative to every previous overdrift.
  722. //
  723. // CASE: CLEAR_ON_UPDATE = false
  724. // overdrift() will start from 0, but it will always keep track on
  725. // any changes in overdrift. By manipulating the MAX_DRIFT parameter
  726. // you can decide how high the drift can go relatively to stay below
  727. // overdrift.
  728. int64_t drift() const { return m_qDrift; }
  729. int64_t overdrift() const { return m_qOverdrift; }
  730. };
  731. template <class KeyType, class ValueType>
  732. struct MapProxy
  733. {
  734. std::map<KeyType, ValueType>& mp;
  735. const KeyType& key;
  736. MapProxy(std::map<KeyType, ValueType>& m, const KeyType& k): mp(m), key(k) {}
  737. void operator=(const ValueType& val)
  738. {
  739. mp[key] = val;
  740. }
  741. typename std::map<KeyType, ValueType>::iterator find()
  742. {
  743. return mp.find(key);
  744. }
  745. typename std::map<KeyType, ValueType>::const_iterator find() const
  746. {
  747. return mp.find(key);
  748. }
  749. operator ValueType() const
  750. {
  751. typename std::map<KeyType, ValueType>::const_iterator p = find();
  752. if (p == mp.end())
  753. return "";
  754. return p->second;
  755. }
  756. ValueType deflt(const ValueType& defval) const
  757. {
  758. typename std::map<KeyType, ValueType>::const_iterator p = find();
  759. if (p == mp.end())
  760. return defval;
  761. return p->second;
  762. }
  763. bool exists() const
  764. {
  765. return find() != mp.end();
  766. }
  767. };
  768. /// Print some hash-based stamp of the first 16 bytes in the buffer
  769. inline std::string BufferStamp(const char* mem, size_t size)
  770. {
  771. using namespace std;
  772. char spread[16];
  773. if (size < 16)
  774. memset((spread + size), 0, 16 - size);
  775. memcpy((spread), mem, min(size_t(16), size));
  776. // Now prepare 4 cells for uint32_t.
  777. union
  778. {
  779. uint32_t sum;
  780. char cells[4];
  781. };
  782. memset((cells), 0, 4);
  783. for (size_t x = 0; x < 4; ++x)
  784. for (size_t y = 0; y < 4; ++y)
  785. {
  786. cells[x] += spread[x+4*y];
  787. }
  788. // Convert to hex string
  789. ostringstream os;
  790. os << hex << uppercase << setfill('0') << setw(8) << sum;
  791. return os.str();
  792. }
  793. template <class OutputIterator>
  794. inline void Split(const std::string & str, char delimiter, OutputIterator tokens)
  795. {
  796. if ( str.empty() )
  797. return; // May cause crash and won't extract anything anyway
  798. std::size_t start;
  799. std::size_t end = -1;
  800. do
  801. {
  802. start = end + 1;
  803. end = str.find(delimiter, start);
  804. *tokens = str.substr(
  805. start,
  806. (end == std::string::npos) ? std::string::npos : end - start);
  807. ++tokens;
  808. } while (end != std::string::npos);
  809. }
  810. inline std::string SelectNot(const std::string& unwanted, const std::string& s1, const std::string& s2)
  811. {
  812. if (s1 == unwanted)
  813. return s2; // might be unwanted, too, but then, there's nothing you can do anyway
  814. if (s2 == unwanted)
  815. return s1;
  816. // Both have wanted values, so now compare if they are same
  817. if (s1 == s2)
  818. return s1; // occasionally there's a winner
  819. // Irresolvable situation.
  820. return std::string();
  821. }
  822. inline std::string SelectDefault(const std::string& checked, const std::string& def)
  823. {
  824. if (checked == "")
  825. return def;
  826. return checked;
  827. }
  828. template <class It>
  829. inline size_t safe_advance(It& it, size_t num, It end)
  830. {
  831. while ( it != end && num )
  832. {
  833. --num;
  834. ++it;
  835. }
  836. return num; // will be effectively 0, if reached the required point, or >0, if end was by that number earlier
  837. }
  838. // This is available only in C++17, dunno why not C++11 as it's pretty useful.
  839. template <class V, size_t N> inline
  840. ATR_CONSTEXPR size_t Size(const V (&)[N]) ATR_NOEXCEPT { return N; }
  841. template <size_t DEPRLEN, typename ValueType>
  842. inline ValueType avg_iir(ValueType old_value, ValueType new_value)
  843. {
  844. return (old_value * (DEPRLEN - 1) + new_value) / DEPRLEN;
  845. }
  846. template <size_t DEPRLEN, typename ValueType>
  847. inline ValueType avg_iir_w(ValueType old_value, ValueType new_value, size_t new_val_weight)
  848. {
  849. return (old_value * (DEPRLEN - new_val_weight) + new_value * new_val_weight) / DEPRLEN;
  850. }
  851. // Property accessor definitions
  852. //
  853. // "Property" is a special method that accesses given field.
  854. // This relies only on a convention, which is the following:
  855. //
  856. // V x = object.prop(); <-- get the property's value
  857. // object.prop(x); <-- set the property a value
  858. //
  859. // Properties might be also chained when setting:
  860. //
  861. // object.prop1(v1).prop2(v2).prop3(v3);
  862. //
  863. // Properties may be defined various even very complicated
  864. // ways, which is simply providing a method with body. In order
  865. // to define a property simplest possible way, that is, refer
  866. // directly to the field that keeps it, here are the following macros:
  867. //
  868. // Prefix: SRTU_PROPERTY_
  869. // Followed by:
  870. // - access type: RO, WO, RW, RR, RRW
  871. // - chain flag: optional _CHAIN
  872. // Where access type is:
  873. // - RO - read only. Defines reader accessor. The accessor method will be const.
  874. // - RR - read reference. The accessor isn't const to allow reference passthrough.
  875. // - WO - write only. Defines writer accessor.
  876. // - RW - combines RO and WO.
  877. // - RRW - combines RR and WO.
  878. //
  879. // The _CHAIN marker is optional for macros providing writable accessors
  880. // for properties. The difference is that while simple write accessors return
  881. // void, the chaining accessors return the reference to the object for which
  882. // the write accessor was called so that you can call the next accessor (or
  883. // any other method as well) for the result.
  884. #define SRTU_PROPERTY_RR(type, name, field) type name() { return field; }
  885. #define SRTU_PROPERTY_RO(type, name, field) type name() const { return field; }
  886. #define SRTU_PROPERTY_WO(type, name, field) void set_##name(type arg) { field = arg; }
  887. #define SRTU_PROPERTY_WO_CHAIN(otype, type, name, field) otype& set_##name(type arg) { field = arg; return *this; }
  888. #define SRTU_PROPERTY_RW(type, name, field) SRTU_PROPERTY_RO(type, name, field); SRTU_PROPERTY_WO(type, name, field)
  889. #define SRTU_PROPERTY_RRW(type, name, field) SRTU_PROPERTY_RR(type, name, field); SRTU_PROPERTY_WO(type, name, field)
  890. #define SRTU_PROPERTY_RW_CHAIN(otype, type, name, field) SRTU_PROPERTY_RO(type, name, field); SRTU_PROPERTY_WO_CHAIN(otype, type, name, field)
  891. #define SRTU_PROPERTY_RRW_CHAIN(otype, type, name, field) SRTU_PROPERTY_RR(type, name, field); SRTU_PROPERTY_WO_CHAIN(otype, type, name, field)
  892. #endif