vdr 2.8.3
tools.h
Go to the documentation of this file.
1/*
2 * tools.h: Various tools
3 *
4 * See the main source file 'vdr.c' for copyright information and
5 * how to reach the author.
6 *
7 * $Id: tools.h 5.19 2026/09/14 13:54:58 kls Exp $
8 */
9
10#ifndef __TOOLS_H
11#define __TOOLS_H
12
13#include <dirent.h>
14#include <errno.h>
15#include <fcntl.h>
16#include <float.h>
17#include <iconv.h>
18#include <math.h>
19#include <poll.h>
20#include <stdarg.h>
21#include <stddef.h>
22#include <stdint.h>
23#include <stdio.h>
24#include <stdlib.h>
25#include <string.h>
26#include <syslog.h>
27#include <sys/stat.h>
28#include <sys/types.h>
29#include "thread.h"
30
31typedef unsigned char uchar;
32
33extern int SysLogLevel;
34
35#define esyslog(a...) void( (SysLogLevel > 0) ? syslog_with_tid(LOG_ERR, a) : void() )
36#define isyslog(a...) void( (SysLogLevel > 1) ? syslog_with_tid(LOG_INFO, a) : void() )
37#define dsyslog(a...) void( (SysLogLevel > 2) ? syslog_with_tid(LOG_DEBUG, a) : void() )
38
39#define LOG_ERROR esyslog("ERROR (%s,%d): %m", __FILE__, __LINE__)
40#define LOG_ERROR_STR(s) esyslog("ERROR (%s,%d): %s: %m", __FILE__, __LINE__, s)
41
42#define SECSINDAY 86400
43
44#define KILOBYTE(n) ((n) * 1024)
45#define MEGABYTE(n) ((n) * 1024LL * 1024LL)
46
47#define MALLOC(type, size) (type *)malloc(sizeof(type) * (size))
48
49template<class T> inline void DELETENULL(T *&p) { T *q = p; p = NULL; delete q; }
50
51#define CHECK(s) { if ((s) < 0) LOG_ERROR; } // used for 'ioctl()' calls
52#define FATALERRNO (errno && errno != EAGAIN && errno != EINTR)
53
54#if __cplusplus >= 201103L
55// any gcc >= 4.8.1; we have swap, min, max
56#include <algorithm> // std::min, std::max, (c++98: also swap)
57#include <utility> // std::swap (since c++11)
58using std::min;
59using std::max;
60using std::swap;
61#else
62// no c++11 and old compiler, let's include our own templates
63template<class T> inline T min(T a, T b) { return a <= b ? a : b; }
64template<class T> inline T max(T a, T b) { return a >= b ? a : b; }
65template<class T> inline void swap(T &a, T &b) { T t = a; a = b; b = t; }
66#endif
67
68template<class T> inline int sgn(T a) { return a < 0 ? -1 : a > 0 ? 1 : 0; }
69
70template<class T> inline T constrain(T v, T l, T h) { return v < l ? l : v > h ? h : v; }
71
72void syslog_with_tid(int priority, const char *format, ...) __attribute__ ((format (printf, 2, 3)));
73
74#define BCDCHARTOINT(x) (10 * ((x & 0xF0) >> 4) + (x & 0xF))
75int BCD2INT(int x);
76
77#define IsBitSet(v, b) ((v) & (1 << (b))) // checks if the bit at index b is set in v, where the least significant bit has index 0
78
79// Unfortunately there are no platform independent macros for unaligned
80// access, so we do it this way:
81
82template<class T> inline T get_unaligned(T *p)
83{
84 struct s { T v; } __attribute__((packed));
85 return ((s *)p)->v;
86}
87
88template<class T> inline void put_unaligned(unsigned int v, T* p)
89{
90 struct s { T v; } __attribute__((packed));
91 ((s *)p)->v = v;
92}
93
94// Comparing doubles for equality is unsafe, but unfortunately we can't
95// overwrite operator==(double, double), so this will have to do:
96
97inline bool DoubleEqual(double a, double b)
98{
99 return fabs(a - b) <= DBL_EPSILON;
100}
101
102// When handling strings that might contain UTF-8 characters, it may be necessary
103// to process a "symbol" that consists of several actual character bytes. The
104// following functions allow transparently accessing a "char *" string without
105// having to worry about what character set is actually used.
106
107int Utf8CharLen(const char *s);
110uint Utf8CharGet(const char *s, int Length = 0);
114int Utf8CharSet(uint c, char *s = NULL);
118int Utf8SymChars(const char *s, int Symbols);
121int Utf8StrLen(const char *s);
124char *Utf8Strn0Cpy(char *Dest, const char *Src, int n);
129int Utf8ToArray(const char *s, uint *a, int Size);
133int Utf8FromArray(const uint *a, char *s, int Size, int Max = -1);
139
140// When allocating buffer space, make sure we reserve enough space to hold
141// a string in UTF-8 representation:
142
143#define Utf8BufSize(s) ((s) * 4 + 1)
144
145// The following macros automatically use the correct versions of the character
146// class functions:
147
148#define Utf8to(conv, c) (cCharSetConv::SystemCharacterTable() ? to##conv(c) : tow##conv(c))
149#define Utf8is(ccls, c) (cCharSetConv::SystemCharacterTable() ? is##ccls(c) : isw##ccls(c))
150
152private:
153 iconv_t cd;
154 char *result;
155 size_t length;
157public:
158 cCharSetConv(const char *FromCode = NULL, const char *ToCode = NULL);
164 const char *Convert(const char *From, char *To = NULL, size_t ToLength = 0);
174 static const char *SystemCharacterTable(void) { return systemCharacterTable; }
175 static void SetSystemCharacterTable(const char *CharacterTable);
176 };
177
178class cString {
179private:
180 char *s;
181public:
182 cString(const char *S = NULL, bool TakePointer = false);
183 cString(const char *S, const char *To);
184 cString(const cString &String);
185 cString(cString &&String): s(String.s) { String.s = NULL; }
186 virtual ~cString();
187 operator const void * () const { return s; } // to catch cases where operator*() should be used
188 operator const char * () const { return s; } // for use in (const char *) context
189 const char * operator*() const { return s; } // for use in (const void *) context (printf() etc.)
190 cString &operator=(const cString &String);
191 cString &operator=(cString &&String);
192 cString &operator=(const char *String);
193 cString &Append(const char *String);
194 cString &Append(char c);
195 cString &Truncate(int Index);
196 cString &CompactChars(char c);
197 static cString sprintf(const char *fmt, ...) __attribute__ ((format (printf, 1, 2)));
198 static cString vsprintf(const char *fmt, va_list &ap);
199 };
200
202private:
203 char *p;
204 char c;
205public:
207 p = NULL;
208 c = 0;
209 }
211 Set(s);
212 }
214 if (p)
215 *p = c;
216 }
217 void Set(char *s) {
218 if (s) {
219 p = s;
220 c = *s;
221 *s = 0;
222 }
223 else
224 p = NULL;
225 }
226 };
227
228ssize_t safe_read(int filedes, void *buffer, size_t size);
229ssize_t safe_write(int filedes, const void *buffer, size_t size);
230void writechar(int filedes, char c);
231int WriteAllOrNothing(int fd, const uchar *Data, int Length, int TimeoutMs = 0, int RetryMs = 0);
235char *strcpyrealloc(char *dest, const char *src);
236char *strn0cpy(char *dest, const char *src, size_t n);
237char *strreplace(char *s, char c1, char c2);
238char *strreplace(char *s, const char *s1, const char *s2);
239const char *strchrn(const char *s, char c, size_t n);
240int strcountchr(const char *s, char c);
241cString strgetbefore(const char *s, char c, int n = 1); // returns the part of 's' before (and excluding) the n'th occurrence of 'c' from the right, or an empty string if there is no such 'c'.
242const char *strgetlast(const char *s, char c); // returns the part of 's' after the last occurrence of 'c', or 's' if there is no 'c'.
243inline char *strgetlast(char *s, char c) { return const_cast<char *>(strgetlast(static_cast<const char *>(s), c)); } // returns the part of 's' after the last occurrence of 'c', or 's' if there is no 'c'.
244inline char *skipspace(const char *s)
245{
246 if ((uchar)*s > ' ') // most strings don't have any leading space, so handle this case as fast as possible
247 return (char *)s;
248 while (*s && (uchar)*s <= ' ') // avoiding isspace() here, because it is much slower
249 s++;
250 return (char *)s;
251}
252char *stripspace(char *s);
253char *strtrim(char *s, bool Shift = false);
257char *compactspace(char *s);
258char *compactchars(char *s, char c);
259cString strescape(const char *s, const char *chars);
260cString strgetval(const char *s, const char *name, char d = '=');
268char *strshift(char *s, int n);
274bool startswith(const char *s, const char *p);
275bool endswith(const char *s, const char *p);
276bool isempty(const char *s);
277int numdigits(int n);
278bool isnumber(const char *s);
279int64_t StrToNum(const char *s);
285bool StrInArray(const char *a[], const char *s);
288double atod(const char *s);
292cString dtoa(double d, const char *Format = "%f");
296cString itoa(int n);
297inline uint16_t Peek13(const uchar *p)
298{
299 uint16_t v = uint16_t(*p++ & 0x1F) << 8;
300 return v + (*p & 0xFF);
301}
302inline void Poke13(uchar *p, uint16_t v)
303{
304 v |= uint16_t(*p & ~0x1F) << 8;
305 *p++ = v >> 8;
306 *p = v & 0xFF;
307}
308cString Indent(int n, const char *s);
310cString AddDirectory(const char *DirName, const char *FileName);
311bool EntriesOnSameFileSystem(const char *File1, const char *File2);
315int FreeDiskSpaceMB(const char *Directory, int *UsedMB = NULL);
316bool DirectoryOk(const char *DirName, bool LogErrors = false);
317bool MakeDirs(const char *FileName, bool IsDirectory = false);
318bool RemoveFileOrDir(const char *FileName, bool FollowSymlinks = false);
319bool RemoveEmptyDirectories(const char *DirName, bool RemoveThis = false, const char *IgnoreFiles[] = NULL);
325int DirSizeMB(const char *DirName);
326char *ReadLink(const char *FileName);
327bool SpinUpDisk(const char *FileName);
328void TouchFile(const char *FileName, bool Create = false);
329time_t LastModifiedTime(const char *FileName);
330off_t FileSize(const char *FileName);
331cString WeekDayName(int WeekDay);
334cString WeekDayName(time_t t);
336cString WeekDayNameFull(int WeekDay);
339cString WeekDayNameFull(time_t t);
341cString DayDateTime(time_t t = 0);
344cString TimeToString(time_t t);
346cString DateString(time_t t);
348cString ShortDateString(time_t t);
350cString TimeString(time_t t);
352uchar *RgbToJpeg(uchar *Mem, int Width, int Height, int &Size, int Quality = 100);
361const char *GetHostName(void);
363
365private:
366 const uchar *data;
369 int i;
370 char *result;
371 static const char *b64;
372public:
373 cBase64Encoder(const uchar *Data, int Length, int MaxResult = 64);
380 const char *NextLine(void);
386 };
387
389private:
390 const uint8_t *data;
391 int length; // in bits
392 int index; // in bits
393public:
394 cBitStream(const uint8_t *Data, int Length) : data(Data), length(Length), index(0) {}
396 int GetBit(void);
397 uint32_t GetBits(int n);
398 void ByteAlign(void);
399 void WordAlign(void);
400 bool SetLength(int Length);
401 void SkipBits(int n) { index += n; }
402 void SkipBit(void) { SkipBits(1); }
403 bool IsEOF(void) const { return index >= length; }
404 void Reset(void) { index = 0; }
405 int Length(void) const { return length; }
406 int Index(void) const { return (IsEOF() ? length : index); }
407 const uint8_t *GetData(void) const { return (IsEOF() ? NULL : data + (index / 8)); }
408 };
409
410class cTimeMs {
411private:
412 uint64_t begin;
413 uint64_t end;
414public:
415 cTimeMs(int Ms = 0);
419 static uint64_t Now(void);
420 void Set(int Ms = 0);
425 bool TimedOut(void) const;
428 uint64_t Elapsed(void) const;
431 uint64_t Remaining(void) const;
435 void Reset(void);
439 };
440
442private:
443 size_t size;
444 char *buffer;
445public:
446 cReadLine(void);
447 ~cReadLine();
448 char *Read(FILE *f);
449 };
450
451class cPoller {
452private:
453 enum { MaxPollFiles = 64 };
456public:
457 cPoller(int FileHandle = -1, bool Out = false);
458 bool Add(int FileHandle, bool Out);
459 void Del(int FileHandle, bool Out);
460 bool Poll(int TimeoutMs = 0);
461 };
462
463class cReadDir {
464private:
466 struct dirent *result;
467#if !__GLIBC_PREREQ(2, 24) // readdir_r() is deprecated as of GLIBC 2.24
468 union { // according to "The GNU C Library Reference Manual"
469 struct dirent d;
470 char b[offsetof(struct dirent, d_name) + NAME_MAX + 1];
471 } u;
472#endif
473public:
474 cReadDir(const char *Directory);
475 ~cReadDir();
476 bool Ok(void) { return directory != NULL; }
477 struct dirent *Next(void);
478 };
479
480class cFile {
481private:
482 int f;
483 bool owner;
484public:
485 cFile(void);
486 ~cFile();
487 operator int () { return f; }
488 bool Open(const char *FileName, int Flags, mode_t Mode = DEFFILEMODE);
489 bool Open(int FileDes, bool Owner = true);
491 void Close(void);
492 bool IsOpen(void) { return f >= 0; }
493 bool Ready(bool Wait = true);
494 static bool FileReady(int FileDes, int TimeoutMs = 1000);
495 };
496
498private:
499 FILE *f;
500 char *fileName;
501 char *tempName;
502public:
503 cSafeFile(const char *FileName);
504 ~cSafeFile();
505 operator FILE* () { return f; }
506 bool Open(void);
507 bool Close(void);
508 };
509
512
514private:
515 int fd;
516 off_t curpos;
519 off_t begin;
520 off_t lastpos;
521 off_t ahead;
522 size_t readahead;
523 size_t written;
525 int FadviseDrop(off_t Offset, off_t Len);
526public:
527 cUnbufferedFile(void);
529 int Open(const char *FileName, int Flags, mode_t Mode = DEFFILEMODE);
530 int Close(void);
531 void SetReadAhead(size_t ra);
532 off_t Seek(off_t Offset, int Whence);
533 ssize_t Read(void *Data, size_t Size);
534 ssize_t Write(const void *Data, size_t Size);
535 static cUnbufferedFile *Create(const char *FileName, int Flags, mode_t Mode = DEFFILEMODE);
536 };
537
539private:
540 char *fileName;
541 int f;
542public:
543 cLockFile(const char *Directory);
544 ~cLockFile();
545 bool Lock(int WaitSeconds = 0);
546 void Unlock(void);
547 };
548
551private:
553 cListObject(const cListObject &ListObject) { abort(); } // no copy constructor!
554 cListObject& operator= (const cListObject &ListObject) { abort(); return *this; } // no assignment operator!
555public:
556 cListObject(void);
557 virtual ~cListObject();
558 virtual int Compare(const cListObject &ListObject) const { return 0; }
561 void Append(cListObject *Object);
562 void Insert(cListObject *Object);
563 void Unlink(void);
564 int Index(void) const;
565 cListObject *Prev(void) const { return prev; }
566 cListObject *Next(void) const { return next; }
567 };
568
570private:
573 time_t lastPut;
574public:
577 void Put(cListObject *Object);
578 void Purge(bool Force = false);
579 };
580
582
584protected:
586 int count;
588 const char *needsLocking;
590 cListBase(const char *NeedsLocking = NULL);
591public:
592 virtual ~cListBase();
593 bool Lock(cStateKey &StateKey, bool Write = false, int TimeoutMs = 0) const;
618 void SetSyncStateKey(cStateKey &StateKey) { stateLock.SetSyncStateKey(StateKey); }
624 void SetExplicitModify(void);
629 void SetModified(void);
631 void Add(cListObject *Object, cListObject *After = NULL);
632 void Ins(cListObject *Object, cListObject *Before = NULL);
633 void Del(cListObject *Object, bool DeleteObject = true);
634 virtual void Move(int From, int To);
635 void Move(cListObject *From, cListObject *To);
636 virtual void Clear(void);
637 bool Contains(const cListObject *Object) const;
644 const cListObject *Get(int Index) const;
645 cListObject *Get(int Index) { return const_cast<cListObject *>(static_cast<const cListBase *>(this)->Get(Index)); }
646 int Count(void) const { return count; }
647 void Sort(void);
648 };
649
650template<class T> class cList : public cListBase {
651public:
652 cList(const char *NeedsLocking = NULL): cListBase(NeedsLocking) {}
659 const T *Get(int Index) const { return (T *)cListBase::Get(Index); }
662 const T *First(void) const { return (T *)objects; }
664 const T *Last(void) const { return (T *)lastObject; }
666 const T *Prev(const T *Object) const { return (T *)Object->cListObject::Prev(); } // need to call cListObject's members to
669 const T *Next(const T *Object) const { return (T *)Object->cListObject::Next(); } // avoid ambiguities in case of a "list of lists"
672 T *Get(int Index) { return const_cast<T *>(static_cast<const cList<T> *>(this)->Get(Index)); }
674 T *First(void) { return const_cast<T *>(static_cast<const cList<T> *>(this)->First()); }
676 T *Last(void) { return const_cast<T *>(static_cast<const cList<T> *>(this)->Last()); }
678 T *Prev(const T *Object) { return const_cast<T *>(static_cast<const cList<T> *>(this)->Prev(Object)); }
680 T *Next(const T *Object) { return const_cast<T *>(static_cast<const cList<T> *>(this)->Next(Object)); }
682 };
683
684// The DEF_LIST_LOCK macro defines a convenience class that can be used to obtain
685// a lock on a cList and make sure the lock is released when the current scope
686// is left:
687
688#define DEF_LIST_LOCK2(Class, Name) \
689class c##Name##_Lock { \
690private: \
691 cStateKey stateKey; \
692 const c##Class *list; \
693public: \
694 c##Name##_Lock(bool Write = false) \
695 { \
696 if (Write) \
697 list = c##Class::Get##Name##Write(stateKey); \
698 else \
699 list = c##Class::Get##Name##Read(stateKey); \
700 } \
701 ~c##Name##_Lock(void) { if (list) stateKey.Remove(); } \
702 const c##Class *Name(void) const { return list; } \
703 c##Class *Name(void) { return const_cast<c##Class *>(list); } \
704 }
705#define DEF_LIST_LOCK(Class) DEF_LIST_LOCK2(Class, Class)
706
707// The USE_LIST_LOCK macro sets up a local variable of a class defined by
708// a suitable DEF_LIST_LOCK, and also a pointer to the provided list:
709
710#define USE_LIST_LOCK_READ2(Class, Name) \
711c##Name##_Lock Name##_Lock(false); \
712const c##Class *Name __attribute__((unused)) = Name##_Lock.Name();
713#define USE_LIST_LOCK_READ(Class) USE_LIST_LOCK_READ2(Class, Class)
714
715#define USE_LIST_LOCK_WRITE2(Class, Name) \
716c##Name##_Lock Name##_Lock(true); \
717c##Class *Name __attribute__((unused)) = Name##_Lock.Name();
718#define USE_LIST_LOCK_WRITE(Class) USE_LIST_LOCK_WRITE2(Class, Class)
719
720template<class T> class cVector {
722private:
723 mutable int allocated;
724 mutable int size;
725 mutable T *data;
726 cVector(const cVector &Vector) {} // don't copy...
727 cVector &operator=(const cVector &Vector) { return *this; } // ...or assign this!
728 void Realloc(int Index) const
729 {
730 if (++Index > allocated) {
731 data = (T *)realloc(data, Index * sizeof(T));
732 if (!data) {
733 esyslog("ERROR: out of memory - abort!");
734 abort();
735 }
736 for (int i = allocated; i < Index; i++)
737 data[i] = T(0);
738 allocated = Index;
739 }
740 }
741public:
742 cVector(int Allocated = 10)
743 {
744 allocated = 0;
745 size = 0;
746 data = NULL;
747 Realloc(Allocated);
748 }
749 virtual ~cVector() { free(data); }
750 T& At(int Index) const
751 {
752 Realloc(Index);
753 if (Index >= size)
754 size = Index + 1;
755 return data[Index];
756 }
757 const T& operator[](int Index) const
758 {
759 return At(Index);
760 }
761 T& operator[](int Index)
762 {
763 return At(Index);
764 }
765 int IndexOf(const T &Data) // returns the index of Data, or -1 if not found
766 {
767 for (int i = 0; i < size; i++) {
768 if (data[i] == Data)
769 return i;
770 }
771 return -1;
772 }
773 int Size(void) const { return size; }
774 const T *Data(void) const { return data; } // only valid as long as the data has not been modified
775 virtual void Insert(T Data, int Before = 0)
776 {
777 if (Before < size) {
778 Realloc(size);
779 memmove(&data[Before + 1], &data[Before], (size - Before) * sizeof(T));
780 size++;
781 data[Before] = Data;
782 }
783 else
784 Append(Data);
785 }
786 bool InsertUnique(T Data, int Before = 0)
787 {
788 if (IndexOf(Data) < 0) {
789 Insert(Data, Before);
790 return true;
791 }
792 return false;
793 }
794 virtual void Append(T Data)
795 {
796 if (size >= allocated)
797 Realloc(allocated * 3 / 2); // increase size by 50%
798 data[size++] = Data;
799 }
801 {
802 if (IndexOf(Data) < 0) {
803 Append(Data);
804 return true;
805 }
806 return false;
807 }
808 virtual void Remove(int Index, int Count = 1)
809 {
810 if (Index < 0 || Index >= size || Count < 1)
811 return; // prevents out-of-bounds access
812 if (Index + Count > size)
813 Count = size - Index;
814 int Tail = size - (Index + Count);
815 if (Tail > 0)
816 memmove(&data[Index], &data[Index + Count], Tail * sizeof(T));
817 size -= Count;
818 }
819 bool RemoveElement(const T &Data)
820 {
821 int i = IndexOf(Data);
822 if (i >= 0) {
823 Remove(i);
824 return true;
825 }
826 return false;
827 }
828 virtual void Clear(void)
829 {
830 for (int i = 0; i < size; i++)
831 data[i] = T(0);
832 size = 0;
833 }
834 void Sort(__compar_fn_t Compare)
835 {
836 qsort(data, size, sizeof(T), Compare);
837 }
838 };
839
840inline int CompareInts(const void *a, const void *b)
841{
842 return *(const int *)a - *(const int *)b;
843}
844
845inline int CompareStrings(const void *a, const void *b)
846{
847 return strcmp(*(const char **)a, *(const char **)b);
848}
849
850inline int CompareStringsIgnoreCase(const void *a, const void *b)
851{
852 return strcasecmp(*(const char **)a, *(const char **)b);
853}
854
855inline int CompareStringsNumerically(const void *a, const void *b)
856{
857 int d = atoi(*(const char **)a) - atoi(*(const char **)b);
858 return d ? d : CompareStrings(a, b);
859}
860
861class cStringList : public cVector<char *> {
862public:
863 cStringList(int Allocated = 10): cVector<char *>(Allocated) {}
864 virtual ~cStringList() override;
865 int Find(const char *s) const;
866 void Sort(bool IgnoreCase = false)
867 {
868 if (IgnoreCase)
870 else
872 }
877 virtual void Clear(void) override;
878 };
879
881public:
882 cFileNameList(const char *Directory = NULL, bool DirsOnly = false);
883 bool Load(const char *Directory, bool DirsOnly = false);
884 };
885
887private:
890 int size; // the total size of the buffer (bytes in memory)
891 int used; // the number of used bytes, starting at the beginning of the buffer
892 bool Realloc(int NewSize);
893 bool Assert(int NewSize) { return size < NewSize ? Realloc(NewSize) : true; } // inline for performance!
894public:
895 cDynamicBuffer(int InitialSize = 1024);
897 void Append(const uchar *Data, int Length);
898 void Append(uchar Data) { if (Assert(used + 1)) buffer[used++] = Data; }
899 void Set(int Index, uchar Data) { if (Assert(Index + 1)) buffer[Index] = Data; }
900 uchar Get(int Index) { return Index < used ? buffer[Index] : 0; }
901 void Clear(void) { used = 0; }
902 uchar *Data(void) { return buffer; }
903 int Length(void) { return used; }
904 };
905
906class cHashObject : public cListObject {
907 friend class cHashBase;
908private:
909 unsigned int id;
911public:
912 cHashObject(cListObject *Object, unsigned int Id) { object = Object; id = Id; }
913 cListObject *Object(void) { return object; }
914 };
915
917private:
919 int size;
921 unsigned int hashfn(unsigned int Id) const { return Id % size; }
922protected:
923 cHashBase(int Size, bool OwnObjects);
928public:
929 virtual ~cHashBase();
930 void Add(cListObject *Object, unsigned int Id);
931 void Del(cListObject *Object, unsigned int Id);
932 void Clear(void);
933 cListObject *Get(unsigned int Id) const;
934 cList<cHashObject> *GetList(unsigned int Id) const;
935 };
936
937#define HASHSIZE 512
938
939template<class T> class cHash : public cHashBase {
940public:
941 cHash(int Size = HASHSIZE, bool OwnObjects = false) : cHashBase(Size, OwnObjects) {}
942 T *Get(unsigned int Id) const { return (T *)cHashBase::Get(Id); }
943};
944
945#endif //__TOOLS_H
static uint8_t * SetLength(uint8_t *Data, int Length)
Definition ci.c:57
char * result
Definition tools.h:370
cBase64Encoder(const uchar *Data, int Length, int MaxResult=64)
Sets up a new base 64 encoder for the given Data, with the given Length.
Definition tools.c:1472
const char * NextLine(void)
Returns the next line of encoded data (terminated by '\0'), or NULL if there is no more encoded data.
Definition tools.c:1486
const uchar * data
Definition tools.h:366
int maxResult
Definition tools.h:368
static const char * b64
Definition tools.h:371
void SkipBit(void)
Definition tools.h:402
int Index(void) const
Definition tools.h:406
cBitStream(const uint8_t *Data, int Length)
Definition tools.h:394
int length
Definition tools.h:391
const uint8_t * data
Definition tools.h:390
int index
Definition tools.h:392
int Length(void) const
Definition tools.h:405
bool IsEOF(void) const
Definition tools.h:403
const uint8_t * GetData(void) const
Definition tools.h:407
void SkipBits(int n)
Definition tools.h:401
~cBitStream()
Definition tools.h:395
void Reset(void)
Definition tools.h:404
cCharSetConv(const char *FromCode=NULL, const char *ToCode=NULL)
Sets up a character set converter to convert from FromCode to ToCode.
Definition tools.c:1035
static const char * SystemCharacterTable(void)
Definition tools.h:174
static void SetSystemCharacterTable(const char *CharacterTable)
Definition tools.c:1053
char * result
Definition tools.h:154
size_t length
Definition tools.h:155
iconv_t cd
Definition tools.h:153
static char * systemCharacterTable
Definition tools.h:156
const char * Convert(const char *From, char *To=NULL, size_t ToLength=0)
Converts the given Text from FromCode to ToCode (as set in the constructor).
Definition tools.c:1076
cDynamicBuffer(int InitialSize=1024)
Definition tools.c:2376
void Set(int Index, uchar Data)
Definition tools.h:899
uchar Get(int Index)
Definition tools.h:900
bool Realloc(int NewSize)
Definition tools.c:2388
int Length(void)
Definition tools.h:903
uchar * Data(void)
Definition tools.h:902
uchar * buffer
Definition tools.h:888
void Clear(void)
Definition tools.h:901
bool Assert(int NewSize)
Definition tools.h:893
void Append(uchar Data)
Definition tools.h:898
int initialSize
Definition tools.h:889
bool Load(const char *Directory, bool DirsOnly=false)
Definition tools.c:1703
cFileNameList(const char *Directory=NULL, bool DirsOnly=false)
Definition tools.c:1698
cFile(void)
Definition tools.c:1731
bool owner
Definition tools.h:483
bool IsOpen(void)
Definition tools.h:492
int f
Definition tools.h:482
cListObject * Get(unsigned int Id) const
Definition tools.c:2463
cList< cHashObject > ** hashTable
Definition tools.h:918
int size
Definition tools.h:919
bool ownObjects
Definition tools.h:920
cHashBase(int Size, bool OwnObjects)
Creates a new hash of the given Size.
Definition tools.c:2414
unsigned int hashfn(unsigned int Id) const
Definition tools.h:921
friend class cHashBase
Definition tools.h:907
unsigned int id
Definition tools.h:909
cListObject * object
Definition tools.h:910
cListObject * Object(void)
Definition tools.h:913
cHashObject(cListObject *Object, unsigned int Id)
Definition tools.h:912
cHash(int Size=HASHSIZE, bool OwnObjects=false)
Definition tools.h:941
T * Get(unsigned int Id) const
Definition tools.h:942
cListObject * lastObject
Definition tools.h:585
cStateLock stateLock
Definition tools.h:587
bool useGarbageCollector
Definition tools.h:589
cListObject * Get(int Index)
Definition tools.h:645
void SetSyncStateKey(cStateKey &StateKey)
When making changes to this list (while holding a write lock) that shall not affect some other code t...
Definition tools.h:618
void SetUseGarbageCollector(void)
Definition tools.h:623
bool Lock(cStateKey &StateKey, bool Write=false, int TimeoutMs=0) const
Tries to get a lock on this list and returns true if successful.
Definition tools.c:2219
int count
Definition tools.h:586
cListObject * objects
Definition tools.h:585
const char * needsLocking
Definition tools.h:588
cListBase(const char *NeedsLocking=NULL)
Definition tools.c:2205
const cListObject * Get(int Index) const
Definition tools.c:2335
int Count(void) const
Definition tools.h:646
void Purge(bool Force=false)
Definition tools.c:2187
cListGarbageCollector(void)
Definition tools.c:2166
cListObject * objects
Definition tools.h:572
void Put(cListObject *Object)
Definition tools.c:2178
cListObject(const cListObject &ListObject)
Definition tools.h:553
cListObject * next
Definition tools.h:552
cListObject * Prev(void) const
Definition tools.h:565
cListObject(void)
Definition tools.c:2118
friend class cListGarbageCollector
Definition tools.h:550
cListObject * prev
Definition tools.h:552
virtual int Compare(const cListObject &ListObject) const
Must return 0 if this object is equal to ListObject, a positive value if it is "greater",...
Definition tools.h:558
cListObject * Next(void) const
Definition tools.h:566
Definition tools.h:650
T * Last(void)
Non-const version of Last().
Definition tools.h:676
T * Prev(const T *Object)
Non-const version of Prev().
Definition tools.h:678
T * First(void)
Non-const version of First().
Definition tools.h:674
const T * Prev(const T *Object) const
Definition tools.h:666
T * Get(int Index)
< Returns the element immediately following Object in this list, or NULL if Object is the last elemen...
Definition tools.h:672
const T * First(void) const
Returns the first element in this list, or NULL if the list is empty.
Definition tools.h:662
T * Next(const T *Object)
Non-const version of Next().
Definition tools.h:680
cList(const char *NeedsLocking=NULL)
Sets up a new cList of the given type T.
Definition tools.h:652
const T * Next(const T *Object) const
< Returns the element immediately before Object in this list, or NULL if Object is the first element ...
Definition tools.h:669
const T * Last(void) const
Returns the last element in this list, or NULL if the list is empty.
Definition tools.h:664
const T * Get(int Index) const
Returns the list element at the given Index, or NULL if no such element exists.
Definition tools.h:659
bool Lock(int WaitSeconds=0)
Definition tools.c:2067
void Unlock(void)
Definition tools.c:2107
char * fileName
Definition tools.h:540
int f
Definition tools.h:541
cLockFile(const char *Directory)
Definition tools.c:2053
char * p
Definition tools.h:203
void Set(char *s)
Definition tools.h:217
cNullTerminate(char *s)
Definition tools.h:210
cNullTerminate(void)
Definition tools.h:206
~cNullTerminate()
Definition tools.h:213
cPoller(int FileHandle=-1, bool Out=false)
Definition tools.c:1594
int numFileHandles
Definition tools.h:455
bool Add(int FileHandle, bool Out)
Definition tools.c:1600
bool Poll(int TimeoutMs=0)
Definition tools.c:1632
void Del(int FileHandle, bool Out)
Definition tools.c:1619
pollfd pfd[MaxPollFiles]
Definition tools.h:454
@ MaxPollFiles
Definition tools.h:453
struct dirent * result
Definition tools.h:466
cReadDir(const char *Directory)
Definition tools.c:1646
DIR * directory
Definition tools.h:465
bool Ok(void)
Definition tools.h:476
cReadLine(void)
Definition tools.c:1563
char * buffer
Definition tools.h:444
size_t size
Definition tools.h:443
char * Read(FILE *f)
Definition tools.c:1574
char * tempName
Definition tools.h:501
char * fileName
Definition tools.h:500
FILE * f
Definition tools.h:499
cSafeFile(const char *FileName)
Definition tools.c:1794
void SetSyncStateKey(cStateKey &StateKey)
Sets the given StateKey to be synchronized to the state of this lock.
Definition thread.c:834
cStringList(int Allocated=10)
Definition tools.h:863
void Sort(bool IgnoreCase=false)
Definition tools.h:866
void SortNumerically(void)
Definition tools.h:873
cString & CompactChars(char c)
Compact any sequence of characters 'c' to a single character, and strip all of them from the beginnin...
Definition tools.c:1236
static cString static cString vsprintf(const char *fmt, va_list &ap)
Definition tools.c:1255
const char * operator*() const
Definition tools.h:189
cString(const char *S=NULL, bool TakePointer=false)
Definition tools.c:1138
static cString sprintf(const char *fmt,...) __attribute__((format(printf
Definition tools.c:1242
cString & operator=(const cString &String)
Definition tools.c:1167
cString(cString &&String)
Definition tools.h:185
char * s
Definition tools.h:180
cString & Append(const char *String)
Definition tools.c:1195
cString & Truncate(int Index)
Truncate the string at the given Index (if Index is < 0 it is counted from the end of the string).
Definition tools.c:1226
uint64_t end
Definition tools.h:413
uint64_t Elapsed(void) const
Returns the number of milliseconds that have elapsed since the last call to Set().
Definition tools.c:855
void Set(int Ms=0)
Sets the timer.
Definition tools.c:842
bool TimedOut(void) const
Returns true if the number of milliseconds given in the last call to Set() have passed.
Definition tools.c:850
cTimeMs(int Ms=0)
Creates a timer with ms resolution and an initial timeout of Ms.
Definition tools.c:792
uint64_t begin
Definition tools.h:412
void Reset(void)
Resets the timer to the same timeout as given in the last call to Set().
Definition tools.c:865
static uint64_t Now(void)
Definition tools.c:799
uint64_t Remaining(void) const
Returns the number of milliseconds remaining until the timer times out.
Definition tools.c:860
off_t ahead
Definition tools.h:521
off_t begin
Definition tools.h:519
size_t readahead
Definition tools.h:522
static cUnbufferedFile * Create(const char *FileName, int Flags, mode_t Mode=DEFFILEMODE)
Definition tools.c:2038
void SetReadAhead(size_t ra)
Definition tools.c:1910
size_t totwritten
Definition tools.h:524
off_t lastpos
Definition tools.h:520
off_t cachedstart
Definition tools.h:517
ssize_t Write(const void *Data, size_t Size)
Definition tools.c:1987
int Close(void)
Definition tools.c:1886
off_t cachedend
Definition tools.h:518
int Open(const char *FileName, int Flags, mode_t Mode=DEFFILEMODE)
Definition tools.c:1868
ssize_t Read(void *Data, size_t Size)
Definition tools.c:1929
int FadviseDrop(off_t Offset, off_t Len)
Definition tools.c:1915
off_t Seek(off_t Offset, int Whence)
Definition tools.c:1921
cUnbufferedFile(void)
Definition tools.c:1858
size_t written
Definition tools.h:523
off_t curpos
Definition tools.h:516
int Size(void) const
Definition tools.h:773
cVector(int Allocated=10)
Definition tools.h:742
const T * Data(void) const
Definition tools.h:774
bool AppendUnique(T Data)
Definition tools.h:800
void Realloc(int Index) const
Definition tools.h:728
void Sort(__compar_fn_t Compare)
Definition tools.h:834
int IndexOf(const T &Data)
Definition tools.h:765
T & operator[](int Index)
Definition tools.h:761
cVector & operator=(const cVector &Vector)
Definition tools.h:727
int allocated
< cVector may only be used for simple types, like int or pointers - not for class objects that alloca...
Definition tools.h:723
virtual void Clear(void)
Definition tools.h:828
virtual ~cVector()
Definition tools.h:749
virtual void Insert(T Data, int Before=0)
Definition tools.h:775
T * data
Definition tools.h:725
virtual void Remove(int Index, int Count=1)
Definition tools.h:808
virtual void Append(T Data)
Definition tools.h:794
bool InsertUnique(T Data, int Before=0)
Definition tools.h:786
int size
Definition tools.h:724
T & At(int Index) const
Definition tools.h:750
const T & operator[](int Index) const
Definition tools.h:757
bool RemoveElement(const T &Data)
Definition tools.h:819
cVector(const cVector &Vector)
Definition tools.h:726
struct __attribute__((packed))
Definition pes2ts.c:138
const char * strgetlast(const char *s, char c)
Definition tools.c:218
char * Utf8Strn0Cpy(char *Dest, const char *Src, int n)
Copies at most n character bytes from Src to Dest, making sure that the resulting copy ends with a co...
Definition tools.c:962
int Utf8ToArray(const char *s, uint *a, int Size)
Converts the given character bytes (including the terminating 0) into an array of UTF-8 symbols of th...
Definition tools.c:985
int Utf8CharSet(uint c, char *s)
Converts the given UTF-8 symbol to a sequence of character bytes and copies them to the given string.
Definition tools.c:903
int Utf8StrLen(const char *s)
Returns the number of UTF-8 symbols formed by the given string of character bytes.
Definition tools.c:950
void syslog_with_tid(int priority, const char *format,...)
Definition tools.c:33
int Utf8SymChars(const char *s, int Symbols)
Returns the number of character bytes at the beginning of the given string that form at most the give...
Definition tools.c:937
uint Utf8CharGet(const char *s, int Length)
Returns the UTF-8 symbol at the beginning of the given string.
Definition tools.c:888
int SysLogLevel
Definition tools.c:31
int Utf8FromArray(const uint *a, char *s, int Size, int Max)
Converts the given array of UTF-8 symbols (including the terminating 0) into a sequence of character ...
Definition tools.c:1003
int Utf8CharLen(const char *s)
Returns the number of character bytes at the beginning of the given string that form a UTF-8 symbol.
Definition tools.c:874
int BCD2INT(int x)
Definition tools.c:42
cListGarbageCollector ListGarbageCollector
Definition tools.c:2164
char * ReadLink(const char *FileName)
returns a new string allocated on the heap, which the caller must delete (or NULL in case of an error...
Definition tools.c:714
char * strcpyrealloc(char *dest, const char *src)
Definition tools.c:111
const char * strgetlast(const char *s, char c)
Definition tools.c:218
cString TimeString(time_t t)
Converts the given time to a string of the form "hh:mm".
Definition tools.c:1348
cString WeekDayNameFull(int WeekDay)
Converts the given WeekDay (0=Sunday, 1=Monday, ...) to a full day name.
Definition tools.c:1286
T get_unaligned(T *p)
Definition tools.h:82
char * compactchars(char *s, char c)
removes all occurrences of 'c' from the beginning an end of 's' and replaces sequences of multiple 'c...
Definition tools.c:286
void TouchFile(const char *FileName, bool Create=false)
Definition tools.c:760
T constrain(T v, T l, T h)
Definition tools.h:70
bool isempty(const char *s)
Definition tools.c:387
char * strreplace(char *s, char c1, char c2)
Definition tools.c:139
#define HASHSIZE
Definition tools.h:937
cString strescape(const char *s, const char *chars)
Definition tools.c:310
int strcountchr(const char *s, char c)
returns the number of occurrences of 'c' in 's'.
Definition tools.c:196
cString TimeToString(time_t t)
Converts the given time to a string of the form "www mmm dd hh:mm:ss yyyy".
Definition tools.c:1318
bool RemoveEmptyDirectories(const char *DirName, bool RemoveThis=false, const char *IgnoreFiles[]=NULL)
Removes all empty directories under the given directory DirName.
Definition tools.c:628
bool SpinUpDisk(const char *FileName)
Definition tools.c:728
cString strgetbefore(const char *s, char c, int n=1)
Definition tools.c:208
uint16_t Peek13(const uchar *p)
Definition tools.h:297
cString WeekDayName(int WeekDay)
Converts the given WeekDay (0=Sunday, 1=Monday, ...) to a three letter day name.
Definition tools.c:1265
bool MakeDirs(const char *FileName, bool IsDirectory=false)
Definition tools.c:542
bool startswith(const char *s, const char *p)
Definition tools.c:367
unsigned char uchar
Definition tools.h:31
char * strshift(char *s, int n)
Shifts the given string to the left by the given number of bytes, thus removing the first n bytes fro...
Definition tools.c:355
const char * GetHostName(void)
Gets the host name of this machine.
Definition tools.c:1456
cString strgetval(const char *s, const char *name, char d='=')
Returns the value part of a 'name=value' pair in s.
Definition tools.c:333
int CompareStrings(const void *a, const void *b)
Definition tools.h:845
int CompareInts(const void *a, const void *b)
Definition tools.h:840
uchar * RgbToJpeg(uchar *Mem, int Width, int Height, int &Size, int Quality=100)
Converts the given Memory to a JPEG image and returns a pointer to the resulting image.
Definition tools.c:1413
int WriteAllOrNothing(int fd, const uchar *Data, int Length, int TimeoutMs=0, int RetryMs=0)
Writes either all Data to the given file descriptor, or nothing at all.
Definition tools.c:87
time_t LastModifiedTime(const char *FileName)
Definition tools.c:774
cString Indent(int n, const char *s)
Returns the given string s, preceeded with n blanks for indentation.
Definition tools.c:440
char * compactspace(char *s)
Definition tools.c:271
int sgn(T a)
Definition tools.h:68
double atod(const char *s)
Converts the given string, which is a floating point number using a '.
Definition tools.c:454
cString ShortDateString(time_t t)
Converts the given time to a string of the form "dd.mm.yy".
Definition tools.c:1339
ssize_t safe_read(int filedes, void *buffer, size_t size)
Definition tools.c:50
void Poke13(uchar *p, uint16_t v)
Definition tools.h:302
bool StrInArray(const char *a[], const char *s)
Returns true if the string s is equal to one of the strings pointed to by the (NULL terminated) array...
Definition tools.c:428
char * skipspace(const char *s)
Definition tools.h:244
char * stripspace(char *s)
Definition tools.c:224
void DELETENULL(T *&p)
Definition tools.h:49
int FreeDiskSpaceMB(const char *Directory, int *UsedMB=NULL)
Definition tools.c:507
bool DoubleEqual(double a, double b)
Definition tools.h:97
ssize_t safe_write(int filedes, const void *buffer, size_t size)
Definition tools.c:62
int numdigits(int n)
Definition tools.c:392
cString DayDateTime(time_t t=0)
Converts the given time to a string of the form "www dd.mm. hh:mm".
Definition tools.c:1307
int CompareStringsIgnoreCase(const void *a, const void *b)
Definition tools.h:850
bool RemoveFileOrDir(const char *FileName, bool FollowSymlinks=false)
Definition tools.c:570
int DirSizeMB(const char *DirName)
returns the total size of the files in the given directory, or -1 in case of an error
Definition tools.c:682
cString DateString(time_t t)
Converts the given time to a string of the form "www dd.mm.yyyy".
Definition tools.c:1328
cString dtoa(double d, const char *Format="%f")
Converts the given double value to a string, making sure it uses a '.
Definition tools.c:475
bool DirectoryOk(const char *DirName, bool LogErrors=false)
Definition tools.c:524
char * strtrim(char *s, bool Shift=false)
Returns a pointer to the first non white space character in s.
Definition tools.c:236
T min(T a, T b)
Definition tools.h:63
void swap(T &a, T &b)
Definition tools.h:65
T max(T a, T b)
Definition tools.h:64
#define esyslog(a...)
Definition tools.h:35
off_t FileSize(const char *FileName)
returns the size of the given file, or -1 in case of an error (e.g. if the file doesn't exist)
Definition tools.c:782
int CompareStringsNumerically(const void *a, const void *b)
Definition tools.h:855
bool EntriesOnSameFileSystem(const char *File1, const char *File2)
Checks whether the given files are on the same file system.
Definition tools.c:492
char * strn0cpy(char *dest, const char *src, size_t n)
Definition tools.c:128
void put_unaligned(unsigned int v, T *p)
Definition tools.h:88
bool endswith(const char *s, const char *p)
Definition tools.c:376
cString itoa(int n)
Definition tools.c:485
const char * strchrn(const char *s, char c, size_t n)
returns a pointer to the n'th occurrence (counting from 1) of c in s, or NULL if no such character wa...
Definition tools.c:183
bool isnumber(const char *s)
Definition tools.c:402
cString AddDirectory(const char *DirName, const char *FileName)
Definition tools.c:445
void writechar(int filedes, char c)
Definition tools.c:82
int64_t StrToNum(const char *s)
Converts the given string to a number.
Definition tools.c:413