Debian Codegraph @

srtcore/utilities.h

raw
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 /*****************************************************************************
12 written by
13 Haivision Systems Inc.
14 *****************************************************************************/
15
16 #ifndef INC_SRT_UTILITIES_H
17 #define INC_SRT_UTILITIES_H
18
19 // Windows warning disabler
20 #define _CRT_SECURE_NO_WARNINGS 1
21
22 #include "platform_sys.h"
23 #include "srt_attr_defs.h" // defines HAVE_CXX11
24
25 // Happens that these are defined, undefine them in advance
26 #undef min
27 #undef max
28
29 #include <string>
30 #include <algorithm>
31 #include <bitset>
32 #include <map>
33 #include <vector>
34 #include <functional>
35 #include <memory>
36 #include <iomanip>
37 #include <sstream>
38 #include <utility>
39
40 #if HAVE_CXX11
41 #include <type_traits>
42 #endif
43
44 #include <cstdlib>
45 #include <cerrno>
46 #include <cstring>
47 #include <stdexcept>
48
49 // -------------- UTILITIES ------------------------
50
51 // --- ENDIAN ---
52 // Copied from: https://gist.github.com/panzi/6856583
53 // License: Public Domain.
54
55 #if (defined(_WIN16) || defined(_WIN32) || defined(_WIN64)) && !defined(__WINDOWS__)
56
57 # define __WINDOWS__
58
59 #endif
60
61 #if defined(__linux__) || defined(__CYGWIN__) || defined(__GNU__) || defined(__GLIBC__)
62
63 # include <endian.h>
64
65 // GLIBC-2.8 and earlier does not provide these macros.
66 // See http://linux.die.net/man/3/endian
67 // From https://gist.github.com/panzi/6856583
68 # if defined(__GLIBC__) \
69 && ( !defined(__GLIBC_MINOR__) \
70 || ((__GLIBC__ < 2) \
71 || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ < 9))) )
72 # include <arpa/inet.h>
73 # if defined(__BYTE_ORDER) && (__BYTE_ORDER == __LITTLE_ENDIAN)
74
75 # define htole32(x) (x)
76 # define le32toh(x) (x)
77
78 # elif defined(__BYTE_ORDER) && (__BYTE_ORDER == __BIG_ENDIAN)
79
80 # define htole16(x) ((((((uint16_t)(x)) >> 8))|((((uint16_t)(x)) << 8)))
81 # define le16toh(x) ((((((uint16_t)(x)) >> 8))|((((uint16_t)(x)) << 8)))
82
83 # define htole32(x) (((uint32_t)htole16(((uint16_t)(((uint32_t)(x)) >> 16)))) | (((uint32_t)htole16(((uint16_t)(x)))) << 16))
84 # define le32toh(x) (((uint32_t)le16toh(((uint16_t)(((uint32_t)(x)) >> 16)))) | (((uint32_t)le16toh(((uint16_t)(x)))) << 16))
85
86 # else
87 # error Byte Order not supported or not defined.
88 # endif
89 # endif
90
91 #elif defined(__APPLE__)
92
93 # include <libkern/OSByteOrder.h>
94
95 # define htobe16(x) OSSwapHostToBigInt16(x)
96 # define htole16(x) OSSwapHostToLittleInt16(x)
97 # define be16toh(x) OSSwapBigToHostInt16(x)
98 # define le16toh(x) OSSwapLittleToHostInt16(x)
99
100 # define htobe32(x) OSSwapHostToBigInt32(x)
101 # define htole32(x) OSSwapHostToLittleInt32(x)
102 # define be32toh(x) OSSwapBigToHostInt32(x)
103 # define le32toh(x) OSSwapLittleToHostInt32(x)
104
105 # define htobe64(x) OSSwapHostToBigInt64(x)
106 # define htole64(x) OSSwapHostToLittleInt64(x)
107 # define be64toh(x) OSSwapBigToHostInt64(x)
108 # define le64toh(x) OSSwapLittleToHostInt64(x)
109
110 # define __BYTE_ORDER BYTE_ORDER
111 # define __BIG_ENDIAN BIG_ENDIAN
112 # define __LITTLE_ENDIAN LITTLE_ENDIAN
113 # define __PDP_ENDIAN PDP_ENDIAN
114
115 #elif defined(__OpenBSD__)
116
117 # include <sys/endian.h>
118
119 #elif defined(__NetBSD__) || defined(__FreeBSD__) || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
120
121 # include <sys/endian.h>
122
123 #ifndef be16toh
124 # define be16toh(x) betoh16(x)
125 #endif
126 #ifndef le16toh
127 # define le16toh(x) letoh16(x)
128 #endif
129
130 #ifndef be32toh
131 # define be32toh(x) betoh32(x)
132 #endif
133 #ifndef le32toh
134 # define le32toh(x) letoh32(x)
135 #endif
136
137 #ifndef be64toh
138 # define be64toh(x) betoh64(x)
139 #endif
140 #ifndef le64toh
141 # define le64toh(x) letoh64(x)
142 #endif
143
144 #elif defined(SUNOS)
145
146 // SunOS/Solaris
147
148 #include <sys/byteorder.h>
149 #include <sys/isa_defs.h>
150
151 #define __LITTLE_ENDIAN 1234
152 #define __BIG_ENDIAN 4321
153
154 # if defined(_BIG_ENDIAN)
155 #define __BYTE_ORDER __BIG_ENDIAN
156 #define be64toh(x) (x)
157 #define be32toh(x) (x)
158 #define be16toh(x) (x)
159 #define le16toh(x) ((uint16_t)BSWAP_16(x))
160 #define le32toh(x) BSWAP_32(x)
161 #define le64toh(x) BSWAP_64(x)
162 #define htobe16(x) (x)
163 #define htole16(x) ((uint16_t)BSWAP_16(x))
164 #define htobe32(x) (x)
165 #define htole32(x) BSWAP_32(x)
166 #define htobe64(x) (x)
167 #define htole64(x) BSWAP_64(x)
168 # else
169 #define __BYTE_ORDER __LITTLE_ENDIAN
170 #define be64toh(x) BSWAP_64(x)
171 #define be32toh(x) ntohl(x)
172 #define be16toh(x) ntohs(x)
173 #define le16toh(x) (x)
174 #define le32toh(x) (x)
175 #define le64toh(x) (x)
176 #define htobe16(x) htons(x)
177 #define htole16(x) (x)
178 #define htobe32(x) htonl(x)
179 #define htole32(x) (x)
180 #define htobe64(x) BSWAP_64(x)
181 #define htole64(x) (x)
182 # endif
183
184 #elif defined(__WINDOWS__)
185
186 # include <winsock2.h>
187
188 # if BYTE_ORDER == LITTLE_ENDIAN
189
190 # define htobe16(x) htons(x)
191 # define htole16(x) (x)
192 # define be16toh(x) ntohs(x)
193 # define le16toh(x) (x)
194
195 # define htobe32(x) htonl(x)
196 # define htole32(x) (x)
197 # define be32toh(x) ntohl(x)
198 # define le32toh(x) (x)
199
200 # define htobe64(x) htonll(x)
201 # define htole64(x) (x)
202 # define be64toh(x) ntohll(x)
203 # define le64toh(x) (x)
204
205 # elif BYTE_ORDER == BIG_ENDIAN
206
207 /* that would be xbox 360 */
208 # define htobe16(x) (x)
209 # define htole16(x) __builtin_bswap16(x)
210 # define be16toh(x) (x)
211 # define le16toh(x) __builtin_bswap16(x)
212
213 # define htobe32(x) (x)
214 # define htole32(x) __builtin_bswap32(x)
215 # define be32toh(x) (x)
216 # define le32toh(x) __builtin_bswap32(x)
217
218 # define htobe64(x) (x)
219 # define htole64(x) __builtin_bswap64(x)
220 # define be64toh(x) (x)
221 # define le64toh(x) __builtin_bswap64(x)
222
223 # else
224
225 # error byte order not supported
226
227 # endif
228
229 # define __BYTE_ORDER BYTE_ORDER
230 # define __BIG_ENDIAN BIG_ENDIAN
231 # define __LITTLE_ENDIAN LITTLE_ENDIAN
232 # define __PDP_ENDIAN PDP_ENDIAN
233
234 #else
235
236 # error Endian: platform not supported
237
238 #endif
239
240 /// Hardware --> Network (big-endian) byte order conversion
241 /// @param size source length in four octets
242 inline void HtoNLA(uint32_t* dst, const uint32_t* src, size_t size)
243 {
244 for (size_t i = 0; i < size; ++ i)
245 dst[i] = htobe32(src[i]);
246 }
247
248 /// Network (big-endian) --> Hardware byte order conversion
249 /// @param size source length in four octets
250 inline void NtoHLA(uint32_t* dst, const uint32_t* src, size_t size)
251 {
252 for (size_t i = 0; i < size; ++ i)
253 dst[i] = be32toh(src[i]);
254 }
255
256 // Hardware <--> Intel (little endian) convention
257 inline void HtoILA(uint32_t* dst, const uint32_t* src, size_t size)
258 {
259 for (size_t i = 0; i < size; ++ i)
260 dst[i] = htole32(src[i]);
261 }
262
263 inline void ItoHLA(uint32_t* dst, const uint32_t* src, size_t size)
264 {
265 for (size_t i = 0; i < size; ++ i)
266 dst[i] = le32toh(src[i]);
267 }
268
269 // Bit numbering utility.
270 //
271 // This is something that allows you to turn 32-bit integers into bit fields.
272 // Although bitfields are part of C++ language, they are not designed to be
273 // interchanged with 32-bit numbers, and any attempt to doing it (by placing
274 // inside a union, for example) is nonportable (order of bitfields inside
275 // same-covering 32-bit integer number is dependent on the endian), so they are
276 // popularly disregarded as useless. Instead the 32-bit numbers with bits
277 // individually selected is preferred, with usually manual playing around with
278 // & and | operators, as well as << and >>. This tool is designed to simplify
279 // the use of them. This can be used to qualify a range of bits inside a 32-bit
280 // number to be a separate number, you can "wrap" it by placing the integer
281 // value in the range of these bits, as well as "unwrap" (extract) it from
282 // the given place. For your own safety, use one prefix to all constants that
283 // concern bit ranges intended to be inside the same "bit container".
284 //
285 // Usage: typedef Bits<leftmost, rightmost> MASKTYPE; // MASKTYPE is a name of your choice.
286 //
287 // With this defined, you can use the following members:
288 // - MASKTYPE::mask - to get the int32_t value with bitmask (used bits set to 1, others to 0)
289 // - MASKTYPE::offset - to get the lowermost bit number, or number of bits to shift
290 // - MASKTYPE::wrap(int value) - to create a bitset where given value is encoded in given bits
291 // - MASKTYPE::unwrap(int bitset) - to extract an integer value from the bitset basing on mask definition
292 // (rightmost defaults to leftmost)
293 // REMEMBER: leftmost > rightmost because bit 0 is the LEAST significant one!
294
295 template <size_t L, size_t R, bool parent_correct = true>
296 struct BitsetMask
297 {
298 static const bool correct = L >= R;
299 static const uint32_t value = (1u << L) | BitsetMask<L-1, R, correct>::value;
300 };
301
302 // This is kind-of functional programming. This describes a special case that is
303 // a "terminal case" in case when decreased L-1 (see above) reached == R.
304 template<size_t R>
305 struct BitsetMask<R, R, true>
306 {
307 static const bool correct = true;
308 static const uint32_t value = 1u << R;
309 };
310
311 // This is a trap for a case that BitsetMask::correct in the master template definition
312 // evaluates to false. This trap causes compile error and prevents from continuing
313 // recursive unwinding in wrong direction (and challenging the compiler's resistiveness
314 // for infinite loops).
315 template <size_t L, size_t R>
316 struct BitsetMask<L, R, false>
317 {
318 };
319
320 template <size_t L, size_t R = L>
321 struct Bits
322 {
323 // DID YOU GET a kind-of error: 'mask' is not a member of 'Bits<3u, 5u, false>'?
324 // See the the above declaration of 'correct'!
325 static const uint32_t mask = BitsetMask<L, R>::value;
326 static const uint32_t offset = R;
327 static const size_t size = L - R + 1;
328
329 // Example: if our bitset mask is 00111100, this checks if given value fits in
330 // 00001111 mask (that is, does not exceed <0, 15>.
331 static bool fit(uint32_t value) { return (BitsetMask<L-R, 0>::value & value) == value; }
332
333 /// 'wrap' gets some given value that should be placed in appropriate bit range and
334 /// returns a whole 32-bit word that has the value already at specified place.
335 /// To create a 32-bit container that contains already all values destined for different
336 /// bit ranges, simply use wrap() for each of them and bind them with | operator.
337 static uint32_t wrap(uint32_t baseval) { return (baseval << offset) & mask; }
338
339 /// Extracts appropriate bit range and returns them as normal integer value.
340 static uint32_t unwrap(uint32_t bitset) { return (bitset & mask) >> offset; }
341
342 template<class T>
343 static T unwrapt(uint32_t bitset) { return static_cast<T>(unwrap(bitset)); }
344 };
345
346
347 //inline int32_t Bit(size_t b) { return 1 << b; }
348 // XXX This would work only with 'constexpr', but this is
349 // available only in C++11. In C++03 this can be only done
350 // using a macro.
351 //
352 // Actually this can be expressed in C++11 using a better technique,
353 // such as user-defined literals:
354 // 2_bit --> 1 >> 2
355
356 #ifdef BIT
357 #undef BIT
358 #endif
359 #define BIT(x) (1 << (x))
360
361
362 // ------------------------------------------------------------
363 // This is something that reminds a structure consisting of fields
364 // of the same type, implemented as an array. It's parametrized
365 // by the type of fields and the type, which's values should be
366 // used for indexing (preferably an enum type). Whatever type is
367 // used for indexing, it is converted to size_t for indexing the
368 // actual array.
369 //
370 // The user should use it as an array: ds[DS_NAME], stating
371 // that DS_NAME is of enum type passed as 3rd parameter.
372 // However trying to do ds[0] would cause a compile error.
373 template <typename FieldType, size_t NoOfFields, typename IndexerType>
374 struct DynamicStruct
375 {
376 FieldType inarray[NoOfFields];
377
378 void clear()
379 {
380 // As a standard library, it can be believed that this call
381 // can be optimized when FieldType is some integer.
382 std::fill(inarray, inarray + NoOfFields, FieldType());
383 }
384
385 FieldType operator[](IndexerType ix) const { return inarray[size_t(ix)]; }
386 FieldType& operator[](IndexerType ix) { return inarray[size_t(ix)]; }
387
388 template<class AnyOther>
389 FieldType operator[](AnyOther ix) const
390 {
391 // If you can see a compile error here ('int' is not a class or struct, or
392 // that there's no definition of 'type' in given type), it means that you
393 // have used invalid data type passed to [] operator. See the definition
394 // of this type as DynamicStruct and see which type is required for indexing.
395 typename AnyOther::type wrong_usage_of_operator_index = AnyOther::type;
396 return inarray[size_t(ix)];
397 }
398
399 template<class AnyOther>
400 FieldType& operator[](AnyOther ix)
401 {
402 // If you can see a compile error here ('int' is not a class or struct, or
403 // that there's no definition of 'type' in given type), it means that you
404 // have used invalid data type passed to [] operator. See the definition
405 // of this type as DynamicStruct and see which type is required for indexing.
406 typename AnyOther::type wrong_usage_of_operator_index = AnyOther::type;
407 return inarray[size_t(ix)];
408 }
409
410 operator FieldType* () { return inarray; }
411 operator const FieldType* () const { return inarray; }
412
413 char* raw() { return (char*)inarray; }
414 };
415
416
417 /// Fixed-size array template class.
418 namespace srt {
419
420 template <class T>
421 class FixedArray
422 {
423 public:
424 FixedArray(size_t size)
425 : m_size(size)
426 , m_entries(new T[size])
427 {
428 }
429
430 ~FixedArray()
431 {
432 delete [] m_entries;
433 }
434
435 public:
436 const T& operator[](size_t index) const
437 {
438 if (index >= m_size)
439 throw_invalid_index(index);
440
441 return m_entries[index];
442 }
443
444 T& operator[](size_t index)
445 {
446 if (index >= m_size)
447 throw_invalid_index(index);
448
449 return m_entries[index];
450 }
451
452 const T& operator[](int index) const
453 {
454 if (index < 0 || static_cast<size_t>(index) >= m_size)
455 throw_invalid_index(index);
456
457 return m_entries[index];
458 }
459
460 T& operator[](int index)
461 {
462 if (index < 0 || static_cast<size_t>(index) >= m_size)
463 throw_invalid_index(index);
464
465 return m_entries[index];
466 }
467
468 size_t size() const { return m_size; }
469
470 typedef T* iterator;
471 typedef const T* const_iterator;
472
473 iterator begin() { return m_entries; }
474 iterator end() { return m_entries + m_size; }
475
476 const_iterator cbegin() const { return m_entries; }
477 const_iterator cend() const { return m_entries + m_size; }
478
479 T* data() { return m_entries; }
480
481 private:
482 FixedArray(const FixedArray<T>& );
483 FixedArray<T>& operator=(const FixedArray<T>&);
484
485 void throw_invalid_index(int i) const
486 {
487 std::stringstream ss;
488 ss << "Index " << i << "out of range";
489 throw std::runtime_error(ss.str());
490 }
491
492 private:
493 size_t m_size;
494 T* const m_entries;
495 };
496
497 } // namespace srt
498
499 // ------------------------------------------------------------
500
501
502
503 inline bool IsSet(int32_t bitset, int32_t flagset)
504 {
505 return (bitset & flagset) == flagset;
506 }
507
508 // std::addressof in C++11,
509 // needs to be provided for C++03
510 template <class RefType>
511 inline RefType* AddressOf(RefType& r)
512 {
513 return (RefType*)(&(unsigned char&)(r));
514 }
515
516 template <class T>
517 struct explicit_t
518 {
519 T inobject;
520 explicit_t(const T& uo): inobject(uo) {}
521
522 operator T() const { return inobject; }
523
524 private:
525 template <class X>
526 explicit_t(const X& another);
527 };
528
529 // This is required for Printable function if you have a container of pairs,
530 // but this function has a different definition for C++11 and C++03.
531 namespace srt_pair_op
532 {
533 template <class Value1, class Value2>
534 std::ostream& operator<<(std::ostream& s, const std::pair<Value1, Value2>& v)
535 {
536 s << "{" << v.first << " " << v.second << "}";
537 return s;
538 }
539 }
540
541 namespace any_op
542 {
543 template <class T>
544 struct AnyProxy
545 {
546 const T& value;
547 bool result;
548
549 AnyProxy(const T& x, bool res): value(x), result(res) {}
550
551 AnyProxy<T>& operator,(const T& val)
552 {
553 if (result)
554 return *this;
555 result = value == val;
556 return *this;
557 }
558
559 operator bool() { return result; }
560 };
561
562 template <class T> inline
563 AnyProxy<T> EqualAny(const T& checked_val)
564 {
565 return AnyProxy<T>(checked_val, false);
566 }
567 }
568
569 #if HAVE_CXX11
570
571 template <class In>
572 inline auto Move(In& i) -> decltype(std::move(i)) { return std::move(i); }
573
574 // Gluing string of any type, wrapper for operator <<
575
576 template <class Stream>
577 inline Stream& Print(Stream& in) { return in;}
578
579 template <class Stream, class Arg1, class... Args>
580 inline Stream& Print(Stream& sout, Arg1&& arg1, Args&&... args)
581 {
582 sout << std::forward<Arg1>(arg1);
583 return Print(sout, args...);
584 }
585
586 template <class... Args>
587 inline std::string Sprint(Args&&... args)
588 {
589 std::ostringstream sout;
590 Print(sout, args...);
591 return sout.str();
592 }
593
594 // We need to use UniquePtr, in the form of C++03 it will be a #define.
595 // Naturally will be used std::move() so that it can later painlessly
596 // switch to C++11.
597 template <class T>
598 using UniquePtr = std::unique_ptr<T>;
599
600 template <class Container, class Value = typename Container::value_type, typename... Args> inline
601 std::string Printable(const Container& in, Value /*pseudoargument*/, Args&&... args)
602 {
603 using namespace srt_pair_op;
604 std::ostringstream os;
605 Print(os, args...);
606 os << "[ ";
607 for (auto i: in)
608 os << Value(i) << " ";
609 os << "]";
610 return os.str();
611 }
612
613 template <class Container> inline
614 std::string Printable(const Container& in)
615 {
616 using namespace srt_pair_op;
617 using Value = typename Container::value_type;
618 return Printable(in, Value());
619 }
620
621 template<typename Map, typename Key>
622 auto map_get(Map& m, const Key& key, typename Map::mapped_type def = typename Map::mapped_type()) -> typename Map::mapped_type
623 {
624 auto it = m.find(key);
625 return it == m.end() ? def : it->second;
626 }
627
628 template<typename Map, typename Key>
629 auto map_getp(Map& m, const Key& key) -> typename Map::mapped_type*
630 {
631 auto it = m.find(key);
632 return it == m.end() ? nullptr : std::addressof(it->second);
633 }
634
635 template<typename Map, typename Key>
636 auto map_getp(const Map& m, const Key& key) -> typename Map::mapped_type const*
637 {
638 auto it = m.find(key);
639 return it == m.end() ? nullptr : std::addressof(it->second);
640 }
641
642
643 #else
644
645 // The unique_ptr requires C++11, and the rvalue-reference feature,
646 // so here we're simulate the behavior using the old std::auto_ptr.
647
648 // This is only to make a "move" call transparent and look ok towards
649 // the C++11 code.
650 template <class T>
651 std::auto_ptr_ref<T> Move(const std::auto_ptr_ref<T>& in) { return in; }
652
653 // We need to provide also some fixes for this type that were not present in auto_ptr,
654 // but they are present in unique_ptr.
655
656 // C++03 doesn't have a templated typedef, but still we need some things
657 // that can only function as a class.
658 template <class T>
659 class UniquePtr: public std::auto_ptr<T>
660 {
661 typedef std::auto_ptr<T> Base;
662
663 public:
664
665 // This is a template - so method names must be declared explicitly
666 typedef typename Base::element_type element_type;
667 using Base::get;
668 using Base::reset;
669
670 // All constructor declarations must be repeated.
671 // "Constructor delegation" is also only C++11 feature.
672 explicit UniquePtr(element_type* p = 0) throw() : Base(p) {}
673 UniquePtr(UniquePtr& a) throw() : Base(a) { }
674 template<typename Type1>
675 UniquePtr(UniquePtr<Type1>& a) throw() : Base(a) {}
676
677 UniquePtr& operator=(UniquePtr& a) throw() { return Base::operator=(a); }
678 template<typename Type1>
679 UniquePtr& operator=(UniquePtr<Type1>& a) throw() { return Base::operator=(a); }
680
681 // Good, now we need to add some parts of the API of unique_ptr.
682
683 bool operator==(const UniquePtr& two) const { return get() == two.get(); }
684 bool operator!=(const UniquePtr& two) const { return get() != two.get(); }
685
686 bool operator==(const element_type* two) const { return get() == two; }
687 bool operator!=(const element_type* two) const { return get() != two; }
688
689 operator bool () const { return 0!= get(); }
690 };
691
692 // A primitive one-argument versions of Sprint and Printable
693 template <class Arg1>
694 inline std::string Sprint(const Arg1& arg)
695 {
696 std::ostringstream sout;
697 sout << arg;
698 return sout.str();
699 }
700
701 // Ok, let it be 2-arg, in case when a manipulator is needed
702 template <class Arg1, class Arg2>
703 inline std::string Sprint(const Arg1& arg1, const Arg2& arg2)
704 {
705 std::ostringstream sout;
706 sout << arg1 << arg2;
707 return sout.str();
708 }
709
710 template <class Container> inline
711 std::string Printable(const Container& in)
712 {
713 using namespace srt_pair_op;
714 typedef typename Container::value_type Value;
715 std::ostringstream os;
716 os << "[ ";
717 for (typename Container::const_iterator i = in.begin(); i != in.end(); ++i)
718 os << Value(*i) << " ";
719 os << "]";
720
721 return os.str();
722 }
723
724 template<typename Map, typename Key>
725 typename Map::mapped_type map_get(Map& m, const Key& key, typename Map::mapped_type def = typename Map::mapped_type())
726 {
727 typename Map::iterator it = m.find(key);
728 return it == m.end() ? def : it->second;
729 }
730
731 template<typename Map, typename Key>
732 typename Map::mapped_type map_get(const Map& m, const Key& key, typename Map::mapped_type def = typename Map::mapped_type())
733 {
734 typename Map::const_iterator it = m.find(key);
735 return it == m.end() ? def : it->second;
736 }
737
738 template<typename Map, typename Key>
739 typename Map::mapped_type* map_getp(Map& m, const Key& key)
740 {
741 typename Map::iterator it = m.find(key);
742 return it == m.end() ? (typename Map::mapped_type*)0 : &(it->second);
743 }
744
745 template<typename Map, typename Key>
746 typename Map::mapped_type const* map_getp(const Map& m, const Key& key)
747 {
748 typename Map::const_iterator it = m.find(key);
749 return it == m.end() ? (typename Map::mapped_type*)0 : &(it->second);
750 }
751
752 #endif
753
754 // Printable with prefix added for every element.
755 // Useful when printing a container of sockets or sequence numbers.
756 template <class Container> inline
757 std::string PrintableMod(const Container& in, const std::string& prefix)
758 {
759 using namespace srt_pair_op;
760 typedef typename Container::value_type Value;
761 std::ostringstream os;
762 os << "[ ";
763 for (typename Container::const_iterator y = in.begin(); y != in.end(); ++y)
764 os << prefix << Value(*y) << " ";
765 os << "]";
766 return os.str();
767 }
768
769 template<typename InputIterator, typename OutputIterator, typename TransFunction>
770 inline void FilterIf(InputIterator bg, InputIterator nd,
771 OutputIterator out, TransFunction fn)
772 {
773 for (InputIterator i = bg; i != nd; ++i)
774 {
775 std::pair<typename TransFunction::result_type, bool> result = fn(*i);
776 if (!result.second)
777 continue;
778 *out++ = result.first;
779 }
780 }
781
782 template <class Value, class ArgValue>
783 inline void insert_uniq(std::vector<Value>& v, const ArgValue& val)
784 {
785 typename std::vector<Value>::iterator i = std::find(v.begin(), v.end(), val);
786 if (i != v.end())
787 return;
788
789 v.push_back(val);
790 }
791
792 // This can be used in conjunction with Tie to simplify the code
793 // in loops around a whole container:
794 // list<string>::const_iterator it, end;
795 // Tie(it, end) = All(list_container);
796 template<class Container>
797 std::pair<typename Container::iterator, typename Container::iterator>
798 inline All(Container& c) { return std::make_pair(c.begin(), c.end()); }
799
800 template<class Container>
801 std::pair<typename Container::const_iterator, typename Container::const_iterator>
802 inline All(const Container& c) { return std::make_pair(c.begin(), c.end()); }
803
804
805 template <class Container, class Value>
806 inline void FringeValues(const Container& from, std::map<Value, size_t>& out)
807 {
808 for (typename Container::const_iterator i = from.begin(); i != from.end(); ++i)
809 ++out[*i];
810 }
811
812 template <class Signature>
813 struct CallbackHolder
814 {
815 void* opaque;
816 Signature* fn;
817
818 CallbackHolder(): opaque(NULL), fn(NULL) {}
819
820 void set(void* o, Signature* f)
821 {
822 // Test if the pointer is a pointer to function. Don't let
823 // other type of pointers here.
824 #if HAVE_CXX11
825 // NOTE: No poor-man's replacement can be done for C++03 because it's
826 // not possible to fake calling a function without calling it and no
827 // other operation can be done without extensive transformations on
828 // the Signature type, still in C++03 possible only on functions up to
829 // 2 arguments (callbacks in SRT usually have more).
830 static_assert(std::is_function<Signature>::value, "CallbackHolder is for functions only!");
831 #endif
832
833 opaque = o;
834 fn = f;
835 }
836
837 operator bool() { return fn != NULL; }
838 };
839
840 #define CALLBACK_CALL(holder,...) (*holder.fn)(holder.opaque, __VA_ARGS__)
841 // The version of std::tie from C++11, but for pairs only.
842 template <class T1, class T2>
843 struct PairProxy
844 {
845 T1& v1;
846 T2& v2;
847
848 PairProxy(T1& c1, T2& c2): v1(c1), v2(c2) {}
849
850 void operator=(const std::pair<T1, T2>& p)
851 {
852 v1 = p.first;
853 v2 = p.second;
854 }
855 };
856
857 template <class T1, class T2> inline
858 PairProxy<T1, T2> Tie2(T1& v1, T2& v2)
859 {
860 return PairProxy<T1, T2>(v1, v2);
861 }
862
863 template<class T>
864 struct PassFilter
865 {
866 T lower, median, upper;
867
868 bool encloses(const T& value)
869 {
870 // Throw away those that don't fit in the filter
871 return value > lower && value < upper;
872 }
873 };
874
875 // This utility is used in window.cpp where it is required to calculate
876 // the median value basing on the value in the very middle and filtered
877 // out values exceeding its range of 1/8 and 8 times. Returned is a structure
878 // that shows the median and also the lower and upper value used for filtering.
879 inline PassFilter<int> GetPeakRange(const int* window, int* replica, size_t size)
880 {
881 // This calculation does more-less the following:
882 //
883 // 1. Having example window:
884 // - 50, 51, 100, 55, 80, 1000, 600, 1500, 1200, 10, 90
885 // 2. This window is now sorted, but we only know the value in the middle:
886 // - 10, 50, 51, 55, 80, [[90]], 100, 600, 1000, 1200, 1500
887 // 3. Now calculate:
888 // - lower: 90/8 = 11.25
889 // - upper: 90*8 = 720
890 // 4. Now calculate the arithmetic median from all these values,
891 // but drop those from outside the <lower, upper> range:
892 // - 10, (11<) [ 50, 51, 55, 80, 90, 100, 600, ] (>720) 1000, 1200, 1500
893 // 5. Calculate the median from the extracted range,
894 // NOTE: the median is actually repeated once, so size is +1.
895 //
896 // values = { 50, 51, 55, 80, 90, 100, 600 };
897 // sum = 90 + accumulate(values); ==> 1026
898 // median = sum/(1 + values.size()); ==> 147
899 //
900 // For comparison: the overall arithmetic median from this window == 430
901 //
902 // 6. Returned value = 1M/median
903
904 // get median value, but cannot change the original value order in the window
905 std::copy(window, window + size, replica);
906 std::nth_element(replica, replica + (size / 2), replica + size);
907 //std::sort(replica, replica + psize); <--- was used for debug, just leave it as a mark
908
909 PassFilter<int> filter;
910 filter.median = replica[size / 2];
911 filter.upper = filter.median << 3; // median*8
912 filter.lower = filter.median >> 3; // median/8
913
914 return filter;
915 }
916
917 // This function sums up all values in the array (from p to end),
918 // except those that don't fit in the low- and high-pass filter.
919 // Returned is the sum and the number of elements taken into account.
920 inline std::pair<int, int> AccumulatePassFilter(const int* p, size_t size, PassFilter<int> filter)
921 {
922 int count = 0;
923 int sum = 0;
924 const int* const end = p + size;
925 for (; p != end; ++p)
926 {
927 // Throw away those that don't fit in the filter
928 if (!filter.encloses(*p))
929 continue;
930
931 sum += *p;
932 ++count;
933 }
934
935 return std::make_pair(sum, count);
936 }
937
938 // This function sums up all values in the array (from p to end)
939 // and simultaneously elements from `para`, stated it points to
940 // an array of the same size. The first array is used as a driver
941 // for which elements to include and which to skip, and this is done
942 // for both arrays at particular index position. Returner is the sum
943 // of the elements passed from the first array and from the `para`
944 // array, as well as the number of included elements.
945 template <class IntCount, class IntParaCount>
946 inline void AccumulatePassFilterParallel(const int* p, size_t size, PassFilter<int> filter,
947 const int* para,
948 int& w_sum, IntCount& w_count, IntParaCount& w_paracount)
949 {
950 IntCount count = 0;
951 int sum = 0;
952 IntParaCount parasum = 0;
953 const int* const end = p + size;
954 for (; p != end; ++p, ++para)
955 {
956 // Throw away those that don't fit in the filter
957 if (!filter.encloses(*p))
958 continue;
959
960 sum += *p;
961 parasum += *para;
962 ++count;
963 }
964 w_count = count;
965 w_sum = sum;
966 w_paracount = parasum;
967 }
968
969 template<class Type>
970 inline Type Bounds(Type lower, Type value, Type upper)
971 {
972 if (value < lower)
973 return lower;
974 if (value > upper)
975 return upper;
976 return value;
977 }
978
979
980 inline std::string FormatBinaryString(const uint8_t* bytes, size_t size)
981 {
982 if ( size == 0 )
983 return "";
984
985 using namespace std;
986
987 ostringstream os;
988 os << setfill('0') << setw(2) << hex << uppercase;
989
990 for (size_t i = 0; i < size; ++i)
991 {
992 os << int(bytes[i]);
993 }
994 return os.str();
995 }
996
997
998 /// This class is useful in every place where
999 /// the time drift should be traced. It's currently in use in every
1000 /// solution that implements any kind of TSBPD.
1001 template<unsigned MAX_SPAN, int MAX_DRIFT, bool CLEAR_ON_UPDATE = true>
1002 class DriftTracer
1003 {
1004 int64_t m_qDrift;
1005 int64_t m_qOverdrift;
1006
1007 int64_t m_qDriftSum;
1008 unsigned m_uDriftSpan;
1009
1010 public:
1011 DriftTracer()
1012 : m_qDrift(0)
1013 , m_qOverdrift(0)
1014 , m_qDriftSum(0)
1015 , m_uDriftSpan(0)
1016 {}
1017
1018 bool update(int64_t driftval)
1019 {
1020 m_qDriftSum += driftval;
1021 ++m_uDriftSpan;
1022
1023 // I moved it here to calculate accumulated overdrift.
1024 if (CLEAR_ON_UPDATE)
1025 m_qOverdrift = 0;
1026
1027 if (m_uDriftSpan < MAX_SPAN)
1028 return false;
1029
1030
1031 // Calculate the median of all drift values.
1032 // In most cases, the divisor should be == MAX_SPAN.
1033 m_qDrift = m_qDriftSum / m_uDriftSpan;
1034
1035 // And clear the collection
1036 m_qDriftSum = 0;
1037 m_uDriftSpan = 0;
1038
1039 // In case of "overdrift", save the overdriven value in 'm_qOverdrift'.
1040 // In clear mode, you should add this value to the time base when update()
1041 // returns true. The drift value will be since now measured with the
1042 // overdrift assumed to be added to the base.
1043 if (std::abs(m_qDrift) > MAX_DRIFT)
1044 {
1045 m_qOverdrift = m_qDrift < 0 ? -MAX_DRIFT : MAX_DRIFT;
1046 m_qDrift -= m_qOverdrift;
1047 }
1048
1049 // printDriftOffset(m_qOverdrift, m_qDrift);
1050
1051 // Timebase is separate
1052 // m_qTimeBase += m_qOverdrift;
1053
1054 return true;
1055 }
1056
1057 // For group overrides
1058 void forceDrift(int64_t driftval)
1059 {
1060 m_qDrift = driftval;
1061 }
1062
1063 // These values can be read at any time, however if you want
1064 // to depend on the fact that they have been changed lately,
1065 // you have to check the return value from update().
1066 //
1067 // IMPORTANT: drift() can be called at any time, just remember
1068 // that this value may look different than before only if the
1069 // last update() returned true, which need not be important for you.
1070 //
1071 // CASE: CLEAR_ON_UPDATE = true
1072 // overdrift() should be read only immediately after update() returned
1073 // true. It will stay available with this value until the next time when
1074 // update() returns true, in which case the value will be cleared.
1075 // Therefore, after calling update() if it returns true, you should read
1076 // overdrift() immediately an make some use of it. Next valid overdrift
1077 // will be then relative to every previous overdrift.
1078 //
1079 // CASE: CLEAR_ON_UPDATE = false
1080 // overdrift() will start from 0, but it will always keep track on
1081 // any changes in overdrift. By manipulating the MAX_DRIFT parameter
1082 // you can decide how high the drift can go relatively to stay below
1083 // overdrift.
1084 int64_t drift() const { return m_qDrift; }
1085 int64_t overdrift() const { return m_qOverdrift; }
1086 };
1087
1088 template <class KeyType, class ValueType>
1089 struct MapProxy
1090 {
1091 std::map<KeyType, ValueType>& mp;
1092 const KeyType& key;
1093
1094 MapProxy(std::map<KeyType, ValueType>& m, const KeyType& k): mp(m), key(k) {}
1095
1096 void operator=(const ValueType& val)
1097 {
1098 mp[key] = val;
1099 }
1100
1101 typename std::map<KeyType, ValueType>::iterator find()
1102 {
1103 return mp.find(key);
1104 }
1105
1106 typename std::map<KeyType, ValueType>::const_iterator find() const
1107 {
1108 return mp.find(key);
1109 }
1110
1111 operator ValueType() const
1112 {
1113 typename std::map<KeyType, ValueType>::const_iterator p = find();
1114 if (p == mp.end())
1115 return ValueType();
1116 return p->second;
1117 }
1118
1119 ValueType deflt(const ValueType& defval) const
1120 {
1121 typename std::map<KeyType, ValueType>::const_iterator p = find();
1122 if (p == mp.end())
1123 return defval;
1124 return p->second;
1125 }
1126
1127 bool exists() const
1128 {
1129 return find() != mp.end();
1130 }
1131 };
1132
1133 /// Print some hash-based stamp of the first 16 bytes in the buffer
1134 inline std::string BufferStamp(const char* mem, size_t size)
1135 {
1136 using namespace std;
1137 char spread[16];
1138
1139 if (size < 16)
1140 memset((spread + size), 0, 16 - size);
1141 memcpy((spread), mem, min(size_t(16), size));
1142
1143 // Now prepare 4 cells for uint32_t.
1144 union
1145 {
1146 uint32_t sum;
1147 char cells[4];
1148 };
1149 memset((cells), 0, 4);
1150
1151 for (size_t x = 0; x < 4; ++x)
1152 for (size_t y = 0; y < 4; ++y)
1153 {
1154 cells[x] += spread[x+4*y];
1155 }
1156
1157 // Convert to hex string
1158 ostringstream os;
1159 os << hex << uppercase << setfill('0') << setw(8) << sum;
1160
1161 return os.str();
1162 }
1163
1164 template <class OutputIterator>
1165 inline void Split(const std::string & str, char delimiter, OutputIterator tokens)
1166 {
1167 if ( str.empty() )
1168 return; // May cause crash and won't extract anything anyway
1169
1170 std::size_t start;
1171 std::size_t end = -1;
1172
1173 do
1174 {
1175 start = end + 1;
1176 end = str.find(delimiter, start);
1177 *tokens = str.substr(
1178 start,
1179 (end == std::string::npos) ? std::string::npos : end - start);
1180 ++tokens;
1181 } while (end != std::string::npos);
1182 }
1183
1184 inline std::string SelectNot(const std::string& unwanted, const std::string& s1, const std::string& s2)
1185 {
1186 if (s1 == unwanted)
1187 return s2; // might be unwanted, too, but then, there's nothing you can do anyway
1188 if (s2 == unwanted)
1189 return s1;
1190
1191 // Both have wanted values, so now compare if they are same
1192 if (s1 == s2)
1193 return s1; // occasionally there's a winner
1194
1195 // Irresolvable situation.
1196 return std::string();
1197 }
1198
1199 inline std::string SelectDefault(const std::string& checked, const std::string& def)
1200 {
1201 if (checked == "")
1202 return def;
1203 return checked;
1204 }
1205
1206 template <class It>
1207 inline size_t safe_advance(It& it, size_t num, It end)
1208 {
1209 while ( it != end && num )
1210 {
1211 --num;
1212 ++it;
1213 }
1214
1215 return num; // will be effectively 0, if reached the required point, or >0, if end was by that number earlier
1216 }
1217
1218 // This is available only in C++17, don't know why not C++11 as it's pretty useful.
1219 template <class V, size_t N> inline
1220 ATR_CONSTEXPR size_t Size(const V (&)[N]) ATR_NOEXCEPT { return N; }
1221
1222 template <size_t DEPRLEN, typename ValueType>
1223 inline ValueType avg_iir(ValueType old_value, ValueType new_value)
1224 {
1225 return (old_value * (DEPRLEN - 1) + new_value) / DEPRLEN;
1226 }
1227
1228 template <size_t DEPRLEN, typename ValueType>
1229 inline ValueType avg_iir_w(ValueType old_value, ValueType new_value, size_t new_val_weight)
1230 {
1231 return (old_value * (DEPRLEN - new_val_weight) + new_value * new_val_weight) / DEPRLEN;
1232 }
1233
1234 // Property accessor definitions
1235 //
1236 // "Property" is a special method that accesses given field.
1237 // This relies only on a convention, which is the following:
1238 //
1239 // V x = object.prop(); <-- get the property's value
1240 // object.set_prop(x); <-- set the property a value
1241 //
1242 // Properties might be also chained when setting:
1243 //
1244 // object.set_prop1(v1).set_prop2(v2).set_prop3(v3);
1245 //
1246 // Properties may be defined various even very complicated
1247 // ways, which is simply providing a method with body. In order
1248 // to define a property simplest possible way, that is, refer
1249 // directly to the field that keeps it, here are the following macros:
1250 //
1251 // Prefix: SRTU_PROPERTY_
1252 // Followed by:
1253 // - access type: RO, WO, RW, RR, RRW
1254 // - chain flag: optional _CHAIN
1255 // Where access type is:
1256 // - RO - read only. Defines reader accessor. The accessor method will be const.
1257 // - RR - read reference. The accessor isn't const to allow reference passthrough.
1258 // - WO - write only. Defines writer accessor.
1259 // - RW - combines RO and WO.
1260 // - RRW - combines RR and WO.
1261 //
1262 // The _CHAIN marker is optional for macros providing writable accessors
1263 // for properties. The difference is that while simple write accessors return
1264 // void, the chaining accessors return the reference to the object for which
1265 // the write accessor was called so that you can call the next accessor (or
1266 // any other method as well) for the result.
1267
1268 #define SRTU_PROPERTY_RR(type, name, field) type name() { return field; }
1269 #define SRTU_PROPERTY_RO(type, name, field) type name() const { return field; }
1270 #define SRTU_PROPERTY_WO(type, name, field) void set_##name(type arg) { field = arg; }
1271 #define SRTU_PROPERTY_WO_ARG(type, name, expr) void set_##name(type arg) { expr; }
1272 #define SRTU_PROPERTY_WO_CHAIN(otype, type, name, field) otype& set_##name(type arg) { field = arg; return *this; }
1273 #define SRTU_PROPERTY_RW(type, name, field) SRTU_PROPERTY_RO(type, name, field); SRTU_PROPERTY_WO(type, name, field)
1274 #define SRTU_PROPERTY_RRW(type, name, field) SRTU_PROPERTY_RR(type, name, field); SRTU_PROPERTY_WO(type, name, field)
1275 #define SRTU_PROPERTY_RW_CHAIN(otype, type, name, field) SRTU_PROPERTY_RO(type, name, field); SRTU_PROPERTY_WO_CHAIN(otype, type, name, field)
1276 #define SRTU_PROPERTY_RRW_CHAIN(otype, type, name, field) SRTU_PROPERTY_RR(type, name, field); SRTU_PROPERTY_WO_CHAIN(otype, type, name, field)
1277
1278 #endif