vdr  2.4.1
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 4.16 2018/03/04 14:06:36 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 
31 typedef unsigned char uchar;
32 
33 extern 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 
49 template<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 // In case some plugin needs to use the STL and gets an error message regarding one
55 // of these functions, you can #define DISABLE_TEMPLATES_COLLIDING_WITH_STL before
56 // including tools.h.
57 #if !defined(__STL_CONFIG_H) // for old versions of the STL
58 #if !defined(DISABLE_TEMPLATES_COLLIDING_WITH_STL) && !defined(_STL_ALGOBASE_H)
59 template<class T> inline T min(T a, T b) { return a <= b ? a : b; }
60 template<class T> inline T max(T a, T b) { return a >= b ? a : b; }
61 #endif
62 template<class T> inline int sgn(T a) { return a < 0 ? -1 : a > 0 ? 1 : 0; }
63 #if !defined(DISABLE_TEMPLATES_COLLIDING_WITH_STL) && !defined(_MOVE_H)
64 template<class T> inline void swap(T &a, T &b) { T t = a; a = b; b = t; }
65 #endif
66 #endif
67 
68 template<class T> inline T constrain(T v, T l, T h) { return v < l ? l : v > h ? h : v; }
69 
70 void syslog_with_tid(int priority, const char *format, ...) __attribute__ ((format (printf, 2, 3)));
71 
72 #define BCDCHARTOINT(x) (10 * ((x & 0xF0) >> 4) + (x & 0xF))
73 int BCD2INT(int x);
74 
75 #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
76 
77 // Unfortunately there are no platform independent macros for unaligned
78 // access, so we do it this way:
79 
80 template<class T> inline T get_unaligned(T *p)
81 {
82  struct s { T v; } __attribute__((packed));
83  return ((s *)p)->v;
84 }
85 
86 template<class T> inline void put_unaligned(unsigned int v, T* p)
87 {
88  struct s { T v; } __attribute__((packed));
89  ((s *)p)->v = v;
90 }
91 
92 // Comparing doubles for equality is unsafe, but unfortunately we can't
93 // overwrite operator==(double, double), so this will have to do:
94 
95 inline bool DoubleEqual(double a, double b)
96 {
97  return fabs(a - b) <= DBL_EPSILON;
98 }
99 
100 // When handling strings that might contain UTF-8 characters, it may be necessary
101 // to process a "symbol" that consists of several actual character bytes. The
102 // following functions allow transparently accessing a "char *" string without
103 // having to worry about what character set is actually used.
104 
105 int Utf8CharLen(const char *s);
108 uint Utf8CharGet(const char *s, int Length = 0);
112 int Utf8CharSet(uint c, char *s = NULL);
116 int Utf8SymChars(const char *s, int Symbols);
119 int Utf8StrLen(const char *s);
122 char *Utf8Strn0Cpy(char *Dest, const char *Src, int n);
127 int Utf8ToArray(const char *s, uint *a, int Size);
131 int Utf8FromArray(const uint *a, char *s, int Size, int Max = -1);
137 
138 // When allocating buffer space, make sure we reserve enough space to hold
139 // a string in UTF-8 representation:
140 
141 #define Utf8BufSize(s) ((s) * 4)
142 
143 // The following macros automatically use the correct versions of the character
144 // class functions:
145 
146 #define Utf8to(conv, c) (cCharSetConv::SystemCharacterTable() ? to##conv(c) : tow##conv(c))
147 #define Utf8is(ccls, c) (cCharSetConv::SystemCharacterTable() ? is##ccls(c) : isw##ccls(c))
148 
150 private:
151  iconv_t cd;
152  char *result;
153  size_t length;
154  static char *systemCharacterTable;
155 public:
156  cCharSetConv(const char *FromCode = NULL, const char *ToCode = NULL);
161  ~cCharSetConv();
162  const char *Convert(const char *From, char *To = NULL, size_t ToLength = 0);
172  static const char *SystemCharacterTable(void) { return systemCharacterTable; }
173  static void SetSystemCharacterTable(const char *CharacterTable);
174  };
175 
176 class cString {
177 private:
178  char *s;
179 public:
180  cString(const char *S = NULL, bool TakePointer = false);
181  cString(const char *S, const char *To);
182  cString(const cString &String);
183  virtual ~cString();
184  operator const void * () const { return s; } // to catch cases where operator*() should be used
185  operator const char * () const { return s; } // for use in (const char *) context
186  const char * operator*() const { return s; } // for use in (const void *) context (printf() etc.)
187  cString &operator=(const cString &String);
188  cString &operator=(const char *String);
189  cString &Append(const char *String);
190  cString &Truncate(int Index);
191  cString &CompactChars(char c);
192  static cString sprintf(const char *fmt, ...) __attribute__ ((format (printf, 1, 2)));
193  static cString vsprintf(const char *fmt, va_list &ap);
194  };
195 
196 ssize_t safe_read(int filedes, void *buffer, size_t size);
197 ssize_t safe_write(int filedes, const void *buffer, size_t size);
198 void writechar(int filedes, char c);
199 int WriteAllOrNothing(int fd, const uchar *Data, int Length, int TimeoutMs = 0, int RetryMs = 0);
203 char *strcpyrealloc(char *dest, const char *src);
204 char *strn0cpy(char *dest, const char *src, size_t n);
205 char *strreplace(char *s, char c1, char c2);
206 char *strreplace(char *s, const char *s1, const char *s2);
207 const char *strchrn(const char *s, char c, size_t n);
208 int strcountchr(const char *s, char c);
209 inline char *skipspace(const char *s)
210 {
211  if ((uchar)*s > ' ') // most strings don't have any leading space, so handle this case as fast as possible
212  return (char *)s;
213  while (*s && (uchar)*s <= ' ') // avoiding isspace() here, because it is much slower
214  s++;
215  return (char *)s;
216 }
217 char *stripspace(char *s);
218 char *compactspace(char *s);
219 char *compactchars(char *s, char c);
220 cString strescape(const char *s, const char *chars);
221 cString strgetval(const char *s, const char *name, char d = '=');
229 char *strshift(char *s, int n);
235 bool startswith(const char *s, const char *p);
236 bool endswith(const char *s, const char *p);
237 bool isempty(const char *s);
238 int numdigits(int n);
239 bool isnumber(const char *s);
240 int64_t StrToNum(const char *s);
246 bool StrInArray(const char *a[], const char *s);
249 double atod(const char *s);
253 cString dtoa(double d, const char *Format = "%f");
257 cString itoa(int n);
258 inline uint16_t Peek13(const uchar *p)
259 {
260  uint16_t v = uint16_t(*p++ & 0x1F) << 8;
261  return v + (*p & 0xFF);
262 }
263 inline void Poke13(uchar *p, uint16_t v)
264 {
265  v |= uint16_t(*p & ~0x1F) << 8;
266  *p++ = v >> 8;
267  *p = v & 0xFF;
268 }
269 cString AddDirectory(const char *DirName, const char *FileName);
270 bool EntriesOnSameFileSystem(const char *File1, const char *File2);
274 int FreeDiskSpaceMB(const char *Directory, int *UsedMB = NULL);
275 bool DirectoryOk(const char *DirName, bool LogErrors = false);
276 bool MakeDirs(const char *FileName, bool IsDirectory = false);
277 bool RemoveFileOrDir(const char *FileName, bool FollowSymlinks = false);
278 bool RemoveEmptyDirectories(const char *DirName, bool RemoveThis = false, const char *IgnoreFiles[] = NULL);
284 int DirSizeMB(const char *DirName);
285 char *ReadLink(const char *FileName);
286 bool SpinUpDisk(const char *FileName);
287 void TouchFile(const char *FileName);
288 time_t LastModifiedTime(const char *FileName);
289 off_t FileSize(const char *FileName);
290 cString WeekDayName(int WeekDay);
293 cString WeekDayName(time_t t);
295 cString WeekDayNameFull(int WeekDay);
298 cString WeekDayNameFull(time_t t);
300 cString DayDateTime(time_t t = 0);
303 cString TimeToString(time_t t);
305 cString DateString(time_t t);
307 cString ShortDateString(time_t t);
309 cString TimeString(time_t t);
311 uchar *RgbToJpeg(uchar *Mem, int Width, int Height, int &Size, int Quality = 100);
320 const char *GetHostName(void);
322 
324 private:
325  const uchar *data;
326  int length;
328  int i;
329  char *result;
330  static const char *b64;
331 public:
332  cBase64Encoder(const uchar *Data, int Length, int MaxResult = 64);
338  ~cBase64Encoder();
339  const char *NextLine(void);
345  };
346 
347 class cBitStream {
348 private:
349  const uint8_t *data;
350  int length; // in bits
351  int index; // in bits
352 public:
353  cBitStream(const uint8_t *Data, int Length) : data(Data), length(Length), index(0) {}
355  int GetBit(void);
356  uint32_t GetBits(int n);
357  void ByteAlign(void);
358  void WordAlign(void);
359  bool SetLength(int Length);
360  void SkipBits(int n) { index += n; }
361  void SkipBit(void) { SkipBits(1); }
362  bool IsEOF(void) const { return index >= length; }
363  void Reset(void) { index = 0; }
364  int Length(void) const { return length; }
365  int Index(void) const { return (IsEOF() ? length : index); }
366  const uint8_t *GetData(void) const { return (IsEOF() ? NULL : data + (index / 8)); }
367  };
368 
369 class cTimeMs {
370 private:
371  uint64_t begin;
372 public:
373  cTimeMs(int Ms = 0);
377  static uint64_t Now(void);
378  void Set(int Ms = 0);
379  bool TimedOut(void) const;
380  uint64_t Elapsed(void) const;
381  };
382 
383 class cReadLine {
384 private:
385  size_t size;
386  char *buffer;
387 public:
388  cReadLine(void);
389  ~cReadLine();
390  char *Read(FILE *f);
391  };
392 
393 class cPoller {
394 private:
395  enum { MaxPollFiles = 64 };
396  pollfd pfd[MaxPollFiles];
398 public:
399  cPoller(int FileHandle = -1, bool Out = false);
400  bool Add(int FileHandle, bool Out);
401  void Del(int FileHandle, bool Out);
402  bool Poll(int TimeoutMs = 0);
403  };
404 
405 class cReadDir {
406 private:
407  DIR *directory;
408  struct dirent *result;
409 #if !__GLIBC_PREREQ(2, 24) // readdir_r() is deprecated as of GLIBC 2.24
410  union { // according to "The GNU C Library Reference Manual"
411  struct dirent d;
412  char b[offsetof(struct dirent, d_name) + NAME_MAX + 1];
413  } u;
414 #endif
415 public:
416  cReadDir(const char *Directory);
417  ~cReadDir();
418  bool Ok(void) { return directory != NULL; }
419  struct dirent *Next(void);
420  };
421 
422 class cFile {
423 private:
424  static bool files[];
425  static int maxFiles;
426  int f;
427 public:
428  cFile(void);
429  ~cFile();
430  operator int () { return f; }
431  bool Open(const char *FileName, int Flags, mode_t Mode = DEFFILEMODE);
432  bool Open(int FileDes);
433  void Close(void);
434  bool IsOpen(void) { return f >= 0; }
435  bool Ready(bool Wait = true);
436  static bool AnyFileReady(int FileDes = -1, int TimeoutMs = 1000);
437  static bool FileReady(int FileDes, int TimeoutMs = 1000);
438  static bool FileReadyForWriting(int FileDes, int TimeoutMs = 1000);
439  };
440 
441 class cSafeFile {
442 private:
443  FILE *f;
444  char *fileName;
445  char *tempName;
446 public:
447  cSafeFile(const char *FileName);
448  ~cSafeFile();
449  operator FILE* () { return f; }
450  bool Open(void);
451  bool Close(void);
452  };
453 
456 
458 private:
459  int fd;
460  off_t curpos;
461  off_t cachedstart;
462  off_t cachedend;
463  off_t begin;
464  off_t lastpos;
465  off_t ahead;
466  size_t readahead;
467  size_t written;
468  size_t totwritten;
469  int FadviseDrop(off_t Offset, off_t Len);
470 public:
471  cUnbufferedFile(void);
472  ~cUnbufferedFile();
473  int Open(const char *FileName, int Flags, mode_t Mode = DEFFILEMODE);
474  int Close(void);
475  void SetReadAhead(size_t ra);
476  off_t Seek(off_t Offset, int Whence);
477  ssize_t Read(void *Data, size_t Size);
478  ssize_t Write(const void *Data, size_t Size);
479  static cUnbufferedFile *Create(const char *FileName, int Flags, mode_t Mode = DEFFILEMODE);
480  };
481 
482 class cLockFile {
483 private:
484  char *fileName;
485  int f;
486 public:
487  cLockFile(const char *Directory);
488  ~cLockFile();
489  bool Lock(int WaitSeconds = 0);
490  void Unlock(void);
491  };
492 
493 class cListObject {
494  friend class cListGarbageCollector;
495 private:
496  cListObject *prev, *next;
497  cListObject(const cListObject &ListObject) { abort(); } // no copy constructor!
498  cListObject& operator= (const cListObject &ListObject) { abort(); return *this; } // no assignment operator!
499 public:
500  cListObject(void);
501  virtual ~cListObject();
502  virtual int Compare(const cListObject &ListObject) const { return 0; }
505  void Append(cListObject *Object);
506  void Insert(cListObject *Object);
507  void Unlink(void);
508  int Index(void) const;
509  cListObject *Prev(void) const { return prev; }
510  cListObject *Next(void) const { return next; }
511  };
512 
514 private:
517  time_t lastPut;
518 public:
519  cListGarbageCollector(void);
521  void Put(cListObject *Object);
522  void Purge(bool Force = false);
523  };
524 
526 
527 class cListBase {
528 protected:
529  cListObject *objects, *lastObject;
530  int count;
532  const char *needsLocking;
534  cListBase(const char *NeedsLocking = NULL);
535 public:
536  virtual ~cListBase();
537  bool Lock(cStateKey &StateKey, bool Write = false, int TimeoutMs = 0) const;
562  void SetSyncStateKey(cStateKey &StateKey) { stateLock.SetSyncStateKey(StateKey); }
567  void SetUseGarbageCollector(void) { useGarbageCollector = true; }
568  void SetExplicitModify(void);
573  void SetModified(void);
575  void Add(cListObject *Object, cListObject *After = NULL);
576  void Ins(cListObject *Object, cListObject *Before = NULL);
577  void Del(cListObject *Object, bool DeleteObject = true);
578  virtual void Move(int From, int To);
579  void Move(cListObject *From, cListObject *To);
580  virtual void Clear(void);
581  bool Contains(const cListObject *Object) const;
588  const cListObject *Get(int Index) const;
589  cListObject *Get(int Index) { return const_cast<cListObject *>(static_cast<const cListBase *>(this)->Get(Index)); }
590  int Count(void) const { return count; }
591  void Sort(void);
592  };
593 
594 template<class T> class cList : public cListBase {
595 public:
596  cList(const char *NeedsLocking = NULL): cListBase(NeedsLocking) {}
603  const T *Get(int Index) const { return (T *)cListBase::Get(Index); }
606  const T *First(void) const { return (T *)objects; }
608  const T *Last(void) const { return (T *)lastObject; }
610  const T *Prev(const T *Object) const { return (T *)Object->cListObject::Prev(); } // need to call cListObject's members to
613  const T *Next(const T *Object) const { return (T *)Object->cListObject::Next(); } // avoid ambiguities in case of a "list of lists"
616  T *Get(int Index) { return const_cast<T *>(static_cast<const cList<T> *>(this)->Get(Index)); }
618  T *First(void) { return const_cast<T *>(static_cast<const cList<T> *>(this)->First()); }
620  T *Last(void) { return const_cast<T *>(static_cast<const cList<T> *>(this)->Last()); }
622  T *Prev(const T *Object) { return const_cast<T *>(static_cast<const cList<T> *>(this)->Prev(Object)); }
624  T *Next(const T *Object) { return const_cast<T *>(static_cast<const cList<T> *>(this)->Next(Object)); }
626  };
627 
628 // The DEF_LIST_LOCK macro defines a convenience class that can be used to obtain
629 // a lock on a cList and make sure the lock is released when the current scope
630 // is left:
631 
632 #define DEF_LIST_LOCK2(Class, Name) \
633 class c##Name##_Lock { \
634 private: \
635  cStateKey stateKey; \
636  const c##Class *list; \
637 public: \
638  c##Name##_Lock(bool Write = false) \
639  { \
640  if (Write) \
641  list = c##Class::Get##Name##Write(stateKey); \
642  else \
643  list = c##Class::Get##Name##Read(stateKey); \
644  } \
645  ~c##Name##_Lock() { if (list) stateKey.Remove(); } \
646  const c##Class *Name(void) const { return list; } \
647  c##Class *Name(void) { return const_cast<c##Class *>(list); } \
648  }
649 #define DEF_LIST_LOCK(Class) DEF_LIST_LOCK2(Class, Class)
650 
651 // The USE_LIST_LOCK macro sets up a local variable of a class defined by
652 // a suitable DEF_LIST_LOCK, and also a pointer to the provided list:
653 
654 #define USE_LIST_LOCK_READ2(Class, Name) \
655 c##Name##_Lock Name##_Lock(false); \
656 const c##Class *Name __attribute__((unused)) = Name##_Lock.Name();
657 #define USE_LIST_LOCK_READ(Class) USE_LIST_LOCK_READ2(Class, Class)
658 
659 #define USE_LIST_LOCK_WRITE2(Class, Name) \
660 c##Name##_Lock Name##_Lock(true); \
661 c##Class *Name __attribute__((unused)) = Name##_Lock.Name();
662 #define USE_LIST_LOCK_WRITE(Class) USE_LIST_LOCK_WRITE2(Class, Class)
663 
664 template<class T> class cVector {
666 private:
667  mutable int allocated;
668  mutable int size;
669  mutable T *data;
670  cVector(const cVector &Vector) {} // don't copy...
671  cVector &operator=(const cVector &Vector) { return *this; } // ...or assign this!
672  void Realloc(int Index) const
673  {
674  if (++Index > allocated) {
675  data = (T *)realloc(data, Index * sizeof(T));
676  if (!data) {
677  esyslog("ERROR: out of memory - abort!");
678  abort();
679  }
680  for (int i = allocated; i < Index; i++)
681  data[i] = T(0);
682  allocated = Index;
683  }
684  }
685 public:
686  cVector(int Allocated = 10)
687  {
688  allocated = 0;
689  size = 0;
690  data = NULL;
691  Realloc(Allocated);
692  }
693  virtual ~cVector() { free(data); }
694  T& At(int Index) const
695  {
696  Realloc(Index);
697  if (Index >= size)
698  size = Index + 1;
699  return data[Index];
700  }
701  const T& operator[](int Index) const
702  {
703  return At(Index);
704  }
705  T& operator[](int Index)
706  {
707  return At(Index);
708  }
709  int IndexOf(const T &Data) // returns the index of Data, or -1 if not found
710  {
711  for (int i = 0; i < size; i++) {
712  if (data[i] == Data)
713  return i;
714  }
715  return -1;
716  }
717  int Size(void) const { return size; }
718  virtual void Insert(T Data, int Before = 0)
719  {
720  if (Before < size) {
721  Realloc(size);
722  memmove(&data[Before + 1], &data[Before], (size - Before) * sizeof(T));
723  size++;
724  data[Before] = Data;
725  }
726  else
727  Append(Data);
728  }
729  bool InsertUnique(T Data, int Before = 0)
730  {
731  if (IndexOf(Data) < 0) {
732  Insert(Data, Before);
733  return true;
734  }
735  return false;
736  }
737  virtual void Append(T Data)
738  {
739  if (size >= allocated)
740  Realloc(allocated * 3 / 2); // increase size by 50%
741  data[size++] = Data;
742  }
743  bool AppendUnique(T Data)
744  {
745  if (IndexOf(Data) < 0) {
746  Append(Data);
747  return true;
748  }
749  return false;
750  }
751  virtual void Remove(int Index)
752  {
753  if (Index < 0)
754  return; // prevents out-of-bounds access
755  if (Index < size - 1)
756  memmove(&data[Index], &data[Index + 1], (size - Index) * sizeof(T));
757  size--;
758  }
759  bool RemoveElement(const T &Data)
760  {
761  int i = IndexOf(Data);
762  if (i >= 0) {
763  Remove(i);
764  return true;
765  }
766  return false;
767  }
768  virtual void Clear(void)
769  {
770  for (int i = 0; i < size; i++)
771  data[i] = T(0);
772  size = 0;
773  }
774  void Sort(__compar_fn_t Compare)
775  {
776  qsort(data, size, sizeof(T), Compare);
777  }
778  };
779 
780 inline int CompareInts(const void *a, const void *b)
781 {
782  return *(const int *)a - *(const int *)b;
783 }
784 
785 inline int CompareStrings(const void *a, const void *b)
786 {
787  return strcmp(*(const char **)a, *(const char **)b);
788 }
789 
790 inline int CompareStringsIgnoreCase(const void *a, const void *b)
791 {
792  return strcasecmp(*(const char **)a, *(const char **)b);
793 }
794 
795 inline int CompareStringsNumerically(const void *a, const void *b)
796 {
797  int d = atoi(*(const char **)a) - atoi(*(const char **)b);
798  return d ? d : CompareStrings(a, b);
799 }
800 
801 class cStringList : public cVector<char *> {
802 public:
803  cStringList(int Allocated = 10): cVector<char *>(Allocated) {}
804  virtual ~cStringList();
805  int Find(const char *s) const;
806  void Sort(bool IgnoreCase = false)
807  {
808  if (IgnoreCase)
810  else
812  }
813  void SortNumerically(void)
814  {
816  }
817  virtual void Clear(void);
818  };
819 
820 class cFileNameList : public cStringList {
821 public:
822  cFileNameList(const char *Directory = NULL, bool DirsOnly = false);
823  bool Load(const char *Directory, bool DirsOnly = false);
824  };
825 
827 private:
830  int size; // the total size of the buffer (bytes in memory)
831  int used; // the number of used bytes, starting at the beginning of the buffer
832  bool Realloc(int NewSize);
833  bool Assert(int NewSize) { return size < NewSize ? Realloc(NewSize) : true; } // inline for performance!
834 public:
835  cDynamicBuffer(int InitialSize = 1024);
836  ~cDynamicBuffer();
837  void Append(const uchar *Data, int Length);
838  void Append(uchar Data) { if (Assert(used + 1)) buffer[used++] = Data; }
839  void Set(int Index, uchar Data) { if (Assert(Index + 1)) buffer[Index] = Data; }
840  uchar Get(int Index) { return Index < used ? buffer[Index] : 0; }
841  void Clear(void) { used = 0; }
842  uchar *Data(void) { return buffer; }
843  int Length(void) { return used; }
844  };
845 
846 class cHashObject : public cListObject {
847  friend class cHashBase;
848 private:
849  unsigned int id;
851 public:
852  cHashObject(cListObject *Object, unsigned int Id) { object = Object; id = Id; }
853  cListObject *Object(void) { return object; }
854  };
855 
856 class cHashBase {
857 private:
859  int size;
861  unsigned int hashfn(unsigned int Id) const { return Id % size; }
862 protected:
863  cHashBase(int Size, bool OwnObjects);
868 public:
869  virtual ~cHashBase();
870  void Add(cListObject *Object, unsigned int Id);
871  void Del(cListObject *Object, unsigned int Id);
872  void Clear(void);
873  cListObject *Get(unsigned int Id) const;
874  cList<cHashObject> *GetList(unsigned int Id) const;
875  };
876 
877 #define HASHSIZE 512
878 
879 template<class T> class cHash : public cHashBase {
880 public:
881  cHash(int Size = HASHSIZE, bool OwnObjects = false) : cHashBase(Size, OwnObjects) {}
882  T *Get(unsigned int Id) const { return (T *)cHashBase::Get(Id); }
883 };
884 
885 #endif //__TOOLS_H
cList::Get
T * Get(int Index)
< Returns the element immediately following Object in this list, or NULL if Object is the last elemen...
Definition: tools.h:616
cCharSetConv::SystemCharacterTable
static const char * SystemCharacterTable(void)
Definition: tools.h:172
DateString
cString DateString(time_t t)
Converts the given time to a string of the form "www dd.mm.yyyy".
Definition: tools.c:1213
cCharSetConv::result
char * result
Definition: tools.h:152
stripspace
char * stripspace(char *s)
Definition: tools.c:201
cListBase::SetSyncStateKey
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:562
safe_read
ssize_t safe_read(int filedes, void *buffer, size_t size)
Definition: tools.c:53
cBitStream::IsEOF
bool IsEOF(void) const
Definition: tools.h:362
cPoller
Definition: tools.h:393
cReadLine
Definition: tools.h:383
cStateLock
Definition: thread.h:171
cString::sprintf
static cString sprintf(const char *fmt,...) __attribute__((format(printf
Definition: tools.c:1127
cBase64Encoder
Definition: tools.h:323
cVector::data
T * data
Definition: tools.h:669
cString::Truncate
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:1111
SetLength
static uint8_t * SetLength(uint8_t *Data, int Length)
Definition: ci.c:57
SpinUpDisk
bool SpinUpDisk(const char *FileName)
Definition: tools.c:667
cBitStream::~cBitStream
~cBitStream()
Definition: tools.h:354
cHash::cHash
cHash(int Size=HASHSIZE, bool OwnObjects=false)
Definition: tools.h:881
Utf8CharLen
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:793
cStringList::cStringList
cStringList(int Allocated=10)
Definition: tools.h:803
cStringList
Definition: tools.h:801
cVector::cVector
cVector(const cVector &Vector)
Definition: tools.h:670
cHashBase::size
int size
Definition: tools.h:859
put_unaligned
void put_unaligned(unsigned int v, T *p)
Definition: tools.h:86
cList::Prev
T * Prev(const T *Object)
Non-const version of Prev().
Definition: tools.h:622
CompareStrings
int CompareStrings(const void *a, const void *b)
Definition: tools.h:785
WriteAllOrNothing
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:90
cFileNameList
Definition: tools.h:820
GetHostName
const char * GetHostName(void)
Gets the host name of this machine.
Definition: tools.c:1341
cList::Get
const T * Get(int Index) const
Returns the list element at the given Index, or NULL if no such element exists.
Definition: tools.h:603
cUnbufferedFile::begin
off_t begin
Definition: tools.h:463
CompareStringsNumerically
int CompareStringsNumerically(const void *a, const void *b)
Definition: tools.h:795
CompareInts
int CompareInts(const void *a, const void *b)
Definition: tools.h:780
cVector::AppendUnique
bool AppendUnique(T Data)
Definition: tools.h:743
strchrn
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:176
cDynamicBuffer::used
int used
Definition: tools.h:831
cSafeFile::fileName
char * fileName
Definition: tools.h:444
isnumber
bool isnumber(const char *s)
Definition: tools.c:346
cCharSetConv::length
size_t length
Definition: tools.h:153
cTimeMs::begin
uint64_t begin
Definition: tools.h:371
cBitStream::GetData
const uint8_t * GetData(void) const
Definition: tools.h:366
TouchFile
void TouchFile(const char *FileName)
Definition: tools.c:699
cCharSetConv::cCharSetConv
cCharSetConv(const char *FromCode=NULL, const char *ToCode=NULL)
Sets up a character set converter to convert from FromCode to ToCode.
Definition: tools.c:950
cHashBase
Definition: tools.h:856
cCharSetConv::cd
iconv_t cd
Definition: tools.h:151
cBase64Encoder::b64
static const char * b64
Definition: tools.h:330
ListGarbageCollector
cListGarbageCollector ListGarbageCollector
Definition: tools.c:2088
cHashObject::id
unsigned int id
Definition: tools.h:849
DayDateTime
cString DayDateTime(time_t t=0)
Converts the given time to a string of the form "www dd.mm. hh:mm".
Definition: tools.c:1192
Utf8Strn0Cpy
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:881
cVector::size
int size
Definition: tools.h:668
constrain
T constrain(T v, T l, T h)
Definition: tools.h:68
cListObject::prev
cListObject * prev
Definition: tools.h:496
cHashObject::cHashObject
cHashObject(cListObject *Object, unsigned int Id)
Definition: tools.h:852
cListGarbageCollector::mutex
cMutex mutex
Definition: tools.h:515
Utf8ToArray
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:900
cVector::Clear
virtual void Clear(void)
Definition: tools.h:768
Peek13
uint16_t Peek13(const uchar *p)
Definition: tools.h:258
cListBase::useGarbageCollector
bool useGarbageCollector
Definition: tools.h:533
cReadDir::Ok
bool Ok(void)
Definition: tools.h:418
cPoller::numFileHandles
int numFileHandles
Definition: tools.h:397
MakeDirs
bool MakeDirs(const char *FileName, bool IsDirectory=false)
Definition: tools.c:481
cListBase::Count
int Count(void) const
Definition: tools.h:590
cListBase::stateLock
cStateLock stateLock
Definition: tools.h:531
cFile
Definition: tools.h:422
cBitStream::length
int length
Definition: tools.h:350
cListGarbageCollector::objects
cListObject * objects
Definition: tools.h:516
cDynamicBuffer::Get
uchar Get(int Index)
Definition: tools.h:840
cCharSetConv::~cCharSetConv
~cCharSetConv()
Definition: tools.c:961
cCharSetConv
Definition: tools.h:149
EntriesOnSameFileSystem
bool EntriesOnSameFileSystem(const char *File1, const char *File2)
Checks whether the given files are on the same file system.
Definition: tools.c:431
strgetval
cString strgetval(const char *s, const char *name, char d='=')
Returns the value part of a 'name=value' pair in s.
Definition: tools.c:277
DELETENULL
void DELETENULL(T *&p)
Definition: tools.h:49
cVector::InsertUnique
bool InsertUnique(T Data, int Before=0)
Definition: tools.h:729
endswith
bool endswith(const char *s, const char *p)
Definition: tools.c:320
cBitStream::Reset
void Reset(void)
Definition: tools.h:363
cFile::IsOpen
bool IsOpen(void)
Definition: tools.h:434
cListObject::Prev
cListObject * Prev(void) const
Definition: tools.h:509
cVector
Definition: tools.h:664
cStateKey
Definition: thread.h:233
cHashBase::Get
cListObject * Get(unsigned int Id) const
Definition: tools.c:2387
cListGarbageCollector
Definition: tools.h:513
StrToNum
int64_t StrToNum(const char *s)
Converts the given string to a number.
Definition: tools.c:357
atod
double atod(const char *s)
Converts the given string, which is a floating point number using a '.
Definition: tools.c:393
cFile::f
int f
Definition: tools.h:426
CompareStringsIgnoreCase
int CompareStringsIgnoreCase(const void *a, const void *b)
Definition: tools.h:790
cBitStream::SkipBit
void SkipBit(void)
Definition: tools.h:361
strescape
cString strescape(const char *s, const char *chars)
Definition: tools.c:254
cUnbufferedFile
cUnbufferedFile is used for large files that are mainly written or read in a streaming manner,...
Definition: tools.h:457
strn0cpy
char * strn0cpy(char *dest, const char *src, size_t n)
Definition: tools.c:131
cMutex
Definition: thread.h:67
cString::operator=
cString & operator=(const cString &String)
Definition: tools.c:1082
cUnbufferedFile::curpos
off_t curpos
Definition: tools.h:460
cHashObject::object
cListObject * object
Definition: tools.h:850
DoubleEqual
bool DoubleEqual(double a, double b)
Definition: tools.h:95
cDynamicBuffer::buffer
uchar * buffer
Definition: tools.h:828
Utf8CharSet
int Utf8CharSet(uint c, char *s=NULL)
Converts the given UTF-8 symbol to a sequence of character bytes and copies them to the given string.
Definition: tools.c:822
strcountchr
int strcountchr(const char *s, char c)
returns the number of occurrences of 'c' in 's'.
Definition: tools.c:189
cDynamicBuffer::Set
void Set(int Index, uchar Data)
Definition: tools.h:839
cListObject::cListObject
cListObject(const cListObject &ListObject)
Definition: tools.h:497
cReadLine::size
size_t size
Definition: tools.h:385
cListObject
Definition: tools.h:493
cListBase::needsLocking
const char * needsLocking
Definition: tools.h:532
strreplace
char * strreplace(char *s, char c1, char c2)
Definition: tools.c:139
cReadLine::buffer
char * buffer
Definition: tools.h:386
cVector::RemoveElement
bool RemoveElement(const T &Data)
Definition: tools.h:759
cList::Last
const T * Last(void) const
Returns the last element in this list, or NULL if the list is empty.
Definition: tools.h:608
cUnbufferedFile::totwritten
size_t totwritten
Definition: tools.h:468
cString::vsprintf
static cString static cString vsprintf(const char *fmt, va_list &ap)
Definition: tools.c:1140
cVector::operator=
cVector & operator=(const cVector &Vector)
Definition: tools.h:671
FileSize
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:713
LastModifiedTime
time_t LastModifiedTime(const char *FileName)
Definition: tools.c:705
SysLogLevel
int SysLogLevel
Definition: tools.c:31
cReadDir::directory
DIR * directory
Definition: tools.h:407
numdigits
int numdigits(int n)
Definition: tools.c:336
cBase64Encoder::i
int i
Definition: tools.h:328
cUnbufferedFile::cachedstart
off_t cachedstart
Definition: tools.h:461
uchar
unsigned char uchar
Definition: tools.h:31
compactspace
char * compactspace(char *s)
Definition: tools.c:213
cCharSetConv::Convert
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:991
cListBase::count
int count
Definition: tools.h:530
cVector::Sort
void Sort(__compar_fn_t Compare)
Definition: tools.h:774
cVector::Realloc
void Realloc(int Index) const
Definition: tools.h:672
cBase64Encoder::length
int length
Definition: tools.h:326
cHashBase::ownObjects
bool ownObjects
Definition: tools.h:860
cVector::Remove
virtual void Remove(int Index)
Definition: tools.h:751
cDynamicBuffer::initialSize
int initialSize
Definition: tools.h:829
ShortDateString
cString ShortDateString(time_t t)
Converts the given time to a string of the form "dd.mm.yy".
Definition: tools.c:1224
cString::operator*
const char * operator*() const
Definition: tools.h:186
cFile::maxFiles
static int maxFiles
Definition: tools.h:425
Utf8CharGet
uint Utf8CharGet(const char *s, int Length=0)
Returns the UTF-8 symbol at the beginning of the given string.
Definition: tools.c:807
itoa
cString itoa(int n)
Definition: tools.c:424
cTimeMs
Definition: tools.h:369
cList::First
T * First(void)
Non-const version of First().
Definition: tools.h:618
cString::s
char * s
Definition: tools.h:178
cBase64Encoder::maxResult
int maxResult
Definition: tools.h:327
cReadDir::result
struct dirent * result
Definition: tools.h:408
cBase64Encoder::result
char * result
Definition: tools.h:329
cBitStream::data
const uint8_t * data
Definition: tools.h:349
cVector::Size
int Size(void) const
Definition: tools.h:717
cString::CompactChars
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:1121
cString::~cString
virtual ~cString()
Definition: tools.c:1077
RemoveEmptyDirectories
bool RemoveEmptyDirectories(const char *DirName, bool RemoveThis=false, const char *IgnoreFiles[]=NULL)
Removes all empty directories under the given directory DirName.
Definition: tools.c:567
cUnbufferedFile::fd
int fd
Definition: tools.h:459
cList
Definition: tools.h:594
strshift
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:299
cDynamicBuffer::Length
int Length(void)
Definition: tools.h:843
cLockFile
Definition: tools.h:482
cList::First
const T * First(void) const
Returns the first element in this list, or NULL if the list is empty.
Definition: tools.h:606
HASHSIZE
#define HASHSIZE
Definition: tools.h:877
cListBase
Definition: tools.h:527
cUnbufferedFile::lastpos
off_t lastpos
Definition: tools.h:464
cHash::Get
T * Get(unsigned int Id) const
Definition: tools.h:882
DirectoryOk
bool DirectoryOk(const char *DirName, bool LogErrors=false)
Definition: tools.c:463
cListGarbageCollector::lastPut
time_t lastPut
Definition: tools.h:517
cListBase::Get
cListObject * Get(int Index)
Definition: tools.h:589
cHashBase::hashfn
unsigned int hashfn(unsigned int Id) const
Definition: tools.h:861
cVector::~cVector
virtual ~cVector()
Definition: tools.h:693
cVector::IndexOf
int IndexOf(const T &Data)
Definition: tools.h:709
cDynamicBuffer::size
int size
Definition: tools.h:830
AddDirectory
cString AddDirectory(const char *DirName, const char *FileName)
Definition: tools.c:384
cUnbufferedFile::written
size_t written
Definition: tools.h:467
strcpyrealloc
char * strcpyrealloc(char *dest, const char *src)
Definition: tools.c:114
safe_write
ssize_t safe_write(int filedes, const void *buffer, size_t size)
Definition: tools.c:65
cHashObject::Object
cListObject * Object(void)
Definition: tools.h:853
cString
Definition: tools.h:176
cString::cString
cString(const char *S=NULL, bool TakePointer=false)
Definition: tools.c:1053
cListObject::Compare
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:502
cDynamicBuffer::Data
uchar * Data(void)
Definition: tools.h:842
Utf8StrLen
int Utf8StrLen(const char *s)
Returns the number of UTF-8 symbols formed by the given string of character bytes.
Definition: tools.c:869
skipspace
char * skipspace(const char *s)
Definition: tools.h:209
cList::Prev
const T * Prev(const T *Object) const
Definition: tools.h:610
cBase64Encoder::data
const uchar * data
Definition: tools.h:325
swap
void swap(T &a, T &b)
Definition: tools.h:64
cList::Next
T * Next(const T *Object)
Non-const version of Next().
Definition: tools.h:624
WeekDayNameFull
cString WeekDayNameFull(int WeekDay)
Converts the given WeekDay (0=Sunday, 1=Monday, ...) to a full day name.
Definition: tools.c:1171
cStateLock::SetSyncStateKey
void SetSyncStateKey(cStateKey &StateKey)
Sets the given StateKey to be synchronized to the state of this lock.
Definition: thread.c:789
cListBase::Get
const cListObject * Get(int Index) const
Definition: tools.c:2259
RemoveFileOrDir
bool RemoveFileOrDir(const char *FileName, bool FollowSymlinks=false)
Definition: tools.c:509
cList::Last
T * Last(void)
Non-const version of Last().
Definition: tools.h:620
DirSizeMB
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:621
ReadLink
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:653
cListObject::Next
cListObject * Next(void) const
Definition: tools.h:510
cSafeFile::tempName
char * tempName
Definition: tools.h:445
cUnbufferedFile::readahead
size_t readahead
Definition: tools.h:466
compactchars
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:230
TimeString
cString TimeString(time_t t)
Converts the given time to a string of the form "hh:mm".
Definition: tools.c:1233
cBitStream::index
int index
Definition: tools.h:351
dtoa
cString dtoa(double d, const char *Format="%f")
Converts the given double value to a string, making sure it uses a '.
Definition: tools.c:414
cListBase::objects
cListObject * objects
Definition: tools.h:529
cVector::Insert
virtual void Insert(T Data, int Before=0)
Definition: tools.h:718
cVector::At
T & At(int Index) const
Definition: tools.h:694
sgn
int sgn(T a)
Definition: tools.h:62
cBitStream::cBitStream
cBitStream(const uint8_t *Data, int Length)
Definition: tools.h:353
cReadDir
Definition: tools.h:405
cBitStream
Definition: tools.h:347
cString::Append
cString & Append(const char *String)
Definition: tools.c:1100
Poke13
void Poke13(uchar *p, uint16_t v)
Definition: tools.h:263
cBitStream::Length
int Length(void) const
Definition: tools.h:364
StrInArray
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:372
cVector::operator[]
T & operator[](int Index)
Definition: tools.h:705
Utf8SymChars
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:856
cCharSetConv::SetSystemCharacterTable
static void SetSystemCharacterTable(const char *CharacterTable)
Definition: tools.c:968
max
T max(T a, T b)
Definition: tools.h:60
RgbToJpeg
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:1298
cUnbufferedFile::cachedend
off_t cachedend
Definition: tools.h:462
cListBase::SetUseGarbageCollector
void SetUseGarbageCollector(void)
Definition: tools.h:567
startswith
bool startswith(const char *s, const char *p)
Definition: tools.c:311
FreeDiskSpaceMB
int FreeDiskSpaceMB(const char *Directory, int *UsedMB=NULL)
Definition: tools.c:446
cStringList::SortNumerically
void SortNumerically(void)
Definition: tools.h:813
cSafeFile
Definition: tools.h:441
cDynamicBuffer
Definition: tools.h:826
cVector::cVector
cVector(int Allocated=10)
Definition: tools.h:686
cList::Next
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:613
cHash
Definition: tools.h:879
cDynamicBuffer::Clear
void Clear(void)
Definition: tools.h:841
isempty
bool isempty(const char *s)
Definition: tools.c:331
cLockFile::fileName
char * fileName
Definition: tools.h:484
cBitStream::SkipBits
void SkipBits(int n)
Definition: tools.h:360
min
T min(T a, T b)
Definition: tools.h:59
cVector::Append
virtual void Append(T Data)
Definition: tools.h:737
cStringList::Sort
void Sort(bool IgnoreCase=false)
Definition: tools.h:806
cHashObject
Definition: tools.h:846
cVector::operator[]
const T & operator[](int Index) const
Definition: tools.h:701
TimeToString
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:1203
Utf8FromArray
int Utf8FromArray(const uint *a, char *s, int Size, int Max=-1)
Converts the given array of UTF-8 symbols (including the terminating 0) into a sequence of character ...
Definition: tools.c:918
syslog_with_tid
void syslog_with_tid(int priority, const char *format,...) __attribute__((format(printf
cVector::allocated
int allocated
< cVector may only be used for simple types, like int or pointers - not for class objects that alloca...
Definition: tools.h:667
cList::cList
cList(const char *NeedsLocking=NULL)
Sets up a new cList of the given type T.
Definition: tools.h:596
cUnbufferedFile::ahead
off_t ahead
Definition: tools.h:465
get_unaligned
T get_unaligned(T *p)
Definition: tools.h:80
thread.h
cCharSetConv::systemCharacterTable
static char * systemCharacterTable
Definition: tools.h:154
WeekDayName
cString WeekDayName(int WeekDay)
Converts the given WeekDay (0=Sunday, 1=Monday, ...) to a three letter day name.
Definition: tools.c:1150
esyslog
#define esyslog(a...)
Definition: tools.h:35
writechar
void writechar(int filedes, char c)
Definition: tools.c:85
cSafeFile::f
FILE * f
Definition: tools.h:443
cLockFile::f
int f
Definition: tools.h:485
cHashBase::hashTable
cList< cHashObject > ** hashTable
Definition: tools.h:858
cBitStream::Index
int Index(void) const
Definition: tools.h:365
__attribute__
struct __attribute__((packed))
Definition: recording.c:2501
cDynamicBuffer::Assert
bool Assert(int NewSize)
Definition: tools.h:833
BCD2INT
int BCD2INT(int x)
Definition: tools.c:45
cDynamicBuffer::Append
void Append(uchar Data)
Definition: tools.h:838