source: trunk/libtransmission/utils.h @ 14336

Last change on this file since 14336 was 14336, checked in by jordan, 8 years ago

(trunk) #4160: mike.dld patch: 4160-07-env.patch

  • Property svn:keywords set to Date Rev Author Id
File size: 16.0 KB
Line 
1/*
2 * This file Copyright (C) 2009-2014 Mnemosyne LLC
3 *
4 * It may be used under the GNU GPL versions 2 or 3
5 * or any future license endorsed by Mnemosyne LLC.
6 *
7 * $Id: utils.h 14336 2014-09-21 18:05:14Z jordan $
8 */
9
10#ifndef TR_UTILS_H
11#define TR_UTILS_H 1
12
13#include <inttypes.h>
14#include <stdarg.h>
15#include <stddef.h> /* size_t */
16#include <time.h> /* time_t */
17
18
19#ifdef __cplusplus
20extern "C" {
21#endif
22
23/***
24****
25***/
26
27/**
28 * @addtogroup utils Utilities
29 * @{
30 */
31
32#ifndef UNUSED
33 #ifdef __GNUC__
34  #define UNUSED __attribute__ ((unused))
35 #else
36  #define UNUSED
37 #endif
38#endif
39
40#ifndef TR_GNUC_PRINTF
41 #ifdef __GNUC__
42  #define TR_GNUC_PRINTF(fmt, args) __attribute__ ((format (printf, fmt, args)))
43 #else
44  #define TR_GNUC_PRINTF(fmt, args)
45 #endif
46#endif
47
48#ifndef TR_GNUC_NONNULL
49 #ifdef __GNUC__
50  #define TR_GNUC_NONNULL(...) __attribute__ ((nonnull (__VA_ARGS__)))
51 #else
52  #define TR_GNUC_NONNULL(...)
53 #endif
54#endif
55
56#ifndef TR_GNUC_NULL_TERMINATED
57 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)
58  #define TR_GNUC_NULL_TERMINATED __attribute__ ((__sentinel__))
59  #define TR_GNUC_HOT __attribute ((hot))
60 #else
61  #define TR_GNUC_NULL_TERMINATED
62  #define TR_GNUC_HOT
63 #endif
64#endif
65
66#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96)
67 #define TR_GNUC_MALLOC __attribute__ ((__malloc__))
68#else
69 #define TR_GNUC_MALLOC
70#endif
71
72
73#ifndef __has_feature
74 #define __has_feature(x) 0
75#endif
76#ifndef __has_extension
77 #define __has_extension __has_feature
78#endif
79
80/**
81 * @def TR_STATIC_ASSERT
82 * @brief This helper allows to perform static checks at compile time
83 */
84#if defined (static_assert)
85 #define TR_STATIC_ASSERT static_assert
86#elif __has_feature (c_static_assert) || __has_extension (c_static_assert)
87 #define TR_STATIC_ASSERT _Static_assert
88#else
89 #define TR_STATIC_ASSERT(x, msg) { const char static_check[((x) ? 1 : -1)] UNUSED; }
90#endif
91
92
93/***
94****
95***/
96
97const char * tr_strip_positional_args (const char * fmt);
98
99#if !defined (_)
100 #if defined (HAVE_LIBINTL_H) && !defined (__APPLE__)
101  #include <libintl.h>
102  #define _(a) gettext (a)
103 #else
104  #define _(a)(a)
105 #endif
106#endif
107
108/* #define DISABLE_GETTEXT */
109#ifndef DISABLE_GETTEXT
110 #if defined (_WIN32) || defined (TR_LIGHTWEIGHT)
111   #define DISABLE_GETTEXT
112 #endif
113#endif
114#ifdef DISABLE_GETTEXT
115 #undef _
116 #define _(a) tr_strip_positional_args (a)
117#endif
118
119/****
120*****
121****/
122
123/**
124 * @brief Rich Salz's classic implementation of shell-style pattern matching for ?, \, [], and * characters.
125 * @return 1 if the pattern matches, 0 if it doesn't, or -1 if an error occured
126 */
127bool tr_wildmat (const char * text, const char * pattern) TR_GNUC_NONNULL (1,2);
128
129
130/**
131 * @brief Loads a file and returns its contents.
132 * On failure, NULL is returned and errno is set.
133 */
134uint8_t* tr_loadFile (const char * filename, size_t * size) TR_GNUC_MALLOC
135                                                             TR_GNUC_NONNULL (1);
136
137
138/** @brief build a filename from a series of elements using the
139           platform's correct directory separator. */
140char* tr_buildPath (const char * first_element, ...) TR_GNUC_NULL_TERMINATED
141                                                      TR_GNUC_MALLOC;
142
143/**
144 * @brief Get available disk space (in bytes) for the specified folder.
145 * @return zero or positive integer on success, -1 in case of error.
146 */
147int64_t tr_getDirFreeSpace (const char * path);
148
149
150struct event;
151
152/**
153 * @brief Convenience wrapper around timer_add () to have a timer wake up in a number of seconds and microseconds
154 * @param timer
155 * @param seconds
156 * @param microseconds
157 */
158void tr_timerAdd (struct event * timer, int seconds, int microseconds) TR_GNUC_NONNULL (1);
159
160/**
161 * @brief Convenience wrapper around timer_add () to have a timer wake up in a number of milliseconds
162 * @param timer
163 * @param milliseconds
164 */
165void tr_timerAddMsec (struct event * timer, int milliseconds) TR_GNUC_NONNULL (1);
166
167
168/** @brief return the current date in milliseconds */
169uint64_t tr_time_msec (void);
170
171/** @brief sleep the specified number of milliseconds */
172void tr_wait_msec (long int delay_milliseconds);
173
174/**
175 * @brief make a copy of 'str' whose non-utf8 content has been corrected or stripped
176 * @return a newly-allocated string that must be freed with tr_free ()
177 * @param str the string to make a clean copy of
178 * @param len the length of the string to copy. If -1, the entire string is used.
179 */
180char* tr_utf8clean (const char * str, int len) TR_GNUC_MALLOC;
181
182#ifdef WIN32
183
184char    * tr_win32_native_to_utf8    (const wchar_t * text,
185                                      int             text_size);
186wchar_t * tr_win32_utf8_to_native    (const char    * text,
187                                      int             text_size);
188wchar_t * tr_win32_utf8_to_native_ex (const char    * text,
189                                      int             text_size,
190                                      int             extra_chars);
191char    * tr_win32_format_message    (uint32_t        code);
192
193#endif
194
195/***
196****
197***/
198
199/* Sometimes the system defines MAX/MIN, sometimes not.
200   In the latter case, define those here since we will use them */
201#ifndef MAX
202 #define MAX(a, b)((a) > (b) ? (a) : (b))
203#endif
204#ifndef MIN
205 #define MIN(a, b)((a) > (b) ? (b) : (a))
206#endif
207
208/***
209****
210***/
211
212/** @brief Portability wrapper around malloc () in which `0' is a safe argument */
213void* tr_malloc (size_t size);
214
215/** @brief Portability wrapper around calloc () in which `0' is a safe argument */
216void* tr_malloc0 (size_t size);
217
218/** @brief Portability wrapper around free () in which `NULL' is a safe argument */
219void tr_free (void * p);
220
221/**
222 * @brief make a newly-allocated copy of a chunk of memory
223 * @param src the memory to copy
224 * @param byteCount the number of bytes to copy
225 * @return a newly-allocated copy of `src' that can be freed with tr_free ()
226 */
227void* tr_memdup (const void * src, size_t byteCount);
228
229#define tr_new(struct_type, n_structs)           \
230  ((struct_type *) tr_malloc (sizeof (struct_type) * ((size_t)(n_structs))))
231
232#define tr_new0(struct_type, n_structs)          \
233  ((struct_type *) tr_malloc0 (sizeof (struct_type) * ((size_t)(n_structs))))
234
235#define tr_renew(struct_type, mem, n_structs)    \
236  ((struct_type *) realloc ((mem), sizeof (struct_type) * ((size_t)(n_structs))))
237
238void* tr_valloc (size_t bufLen);
239
240/**
241 * @brief make a newly-allocated copy of a substring
242 * @param in is a void* so that callers can pass in both signed & unsigned without a cast
243 * @param len length of the substring to copy. if a length less than zero is passed in, strlen (len) is used
244 * @return a newly-allocated copy of `in' that can be freed with tr_free ()
245 */
246char* tr_strndup (const void * in, int len) TR_GNUC_MALLOC;
247
248/**
249 * @brief make a newly-allocated copy of a string
250 * @param in is a void* so that callers can pass in both signed & unsigned without a cast
251 * @return a newly-allocated copy of `in' that can be freed with tr_free ()
252 */
253char* tr_strdup (const void * in);
254
255/**
256 * @brief like strcmp () but gracefully handles NULL strings
257 */
258int tr_strcmp0 (const char * str1, const char * str2);
259
260
261
262struct evbuffer;
263
264char* evbuffer_free_to_str (struct evbuffer * buf);
265
266/** @brief similar to bsearch () but returns the index of the lower bound */
267int tr_lowerBound (const void * key,
268                   const void * base,
269                   size_t       nmemb,
270                   size_t       size,
271                   int     (* compar)(const void* key, const void* arrayMember),
272                   bool       * exact_match) TR_GNUC_HOT TR_GNUC_NONNULL (1,5,6);
273
274/** @brief moves the best k items to the first slots in the array. O(n) */
275void tr_quickfindFirstK (void * base, size_t nmemb, size_t size,
276                         int (*compar)(const void *, const void *), size_t k);
277
278/**
279 * @brief sprintf () a string into a newly-allocated buffer large enough to hold it
280 * @return a newly-allocated string that can be freed with tr_free ()
281 */
282char* tr_strdup_printf (const char * fmt, ...) TR_GNUC_PRINTF (1, 2)
283                                                TR_GNUC_MALLOC;
284char * tr_strdup_vprintf (const char * fmt,
285                          va_list      args) TR_GNUC_MALLOC;
286
287/**
288 * @brief Translate a block of bytes into base64
289 * @return a newly-allocated string that can be freed with tr_free ()
290 */
291char* tr_base64_encode (const void * input,
292                        int          inlen,
293                        int        * outlen) TR_GNUC_MALLOC;
294
295/**
296 * @brief Translate a block of bytes from base64 into raw form
297 * @return a newly-allocated string that can be freed with tr_free ()
298 */
299char* tr_base64_decode (const void * input,
300                        int          inlen,
301                        int        * outlen) TR_GNUC_MALLOC;
302
303/** @brief Portability wrapper for strlcpy () that uses the system implementation if available */
304size_t tr_strlcpy (char * dst, const void * src, size_t siz);
305
306/** @brief Portability wrapper for snprintf () that uses the system implementation if available */
307int tr_snprintf (char * buf, size_t buflen,
308                 const char * fmt, ...) TR_GNUC_PRINTF (3, 4) TR_GNUC_NONNULL (1,3);
309
310/** @brief Convenience wrapper around strerorr () guaranteed to not return NULL
311    @param errno */
312const char* tr_strerror (int);
313
314/** @brief strips leading and trailing whitspace from a string
315    @return the stripped string */
316char* tr_strstrip (char * str);
317
318/** @brief Returns true if the string ends with the specified case-insensitive suffix */
319bool tr_str_has_suffix (const char *str, const char *suffix);
320
321
322/** @brief Portability wrapper for memmem () that uses the system implementation if available */
323const char* tr_memmem (const char * haystack, size_t haystack_len,
324                       const char * needle, size_t needle_len);
325
326/** @brief Portability wrapper for strsep () that uses the system implementation if available */
327char* tr_strsep (char ** str, const char * delim);
328
329/***
330****
331***/
332
333int compareInt (const void * va, const void * vb);
334
335void tr_sha1_to_hex (char * out, const uint8_t * sha1) TR_GNUC_NONNULL (1,2);
336
337void tr_hex_to_sha1 (uint8_t * out, const char * hex) TR_GNUC_NONNULL (1,2);
338
339/** @brief convenience function to determine if an address is an IP address (IPv4 or IPv6) */
340bool tr_addressIsIP (const char * address);
341
342/** @brief return true if the url is a http or https url that Transmission understands */
343bool tr_urlIsValidTracker (const char * url) TR_GNUC_NONNULL (1);
344
345/** @brief return true if the url is a [ http, https, ftp, ftps ] url that Transmission understands */
346bool tr_urlIsValid (const char * url, int url_len) TR_GNUC_NONNULL (1);
347
348/** @brief parse a URL into its component parts
349    @return zero on success or an error number if an error occurred */
350int  tr_urlParse (const char * url,
351                  int          url_len,
352                  char      ** setme_scheme,
353                  char      ** setme_host,
354                  int        * setme_port,
355                  char      ** setme_path) TR_GNUC_NONNULL (1);
356
357
358/** @brief return TR_RATIO_NA, TR_RATIO_INF, or a number in [0..1]
359    @return TR_RATIO_NA, TR_RATIO_INF, or a number in [0..1] */
360double tr_getRatio (uint64_t numerator, uint64_t denominator);
361
362/**
363 * @brief Given a string like "1-4" or "1-4,6,9,14-51", this returns a
364 *        newly-allocated array of all the integers in the set.
365 * @return a newly-allocated array of integers that must be freed with tr_free (),
366 *         or NULL if a fragment of the string can't be parsed.
367 *
368 * For example, "5-8" will return [ 5, 6, 7, 8 ] and setmeCount will be 4.
369 */
370int* tr_parseNumberRange (const char * str,
371                          int str_len,
372                          int * setmeCount) TR_GNUC_MALLOC TR_GNUC_NONNULL (1);
373
374
375/**
376 * @brief truncate a double value at a given number of decimal places.
377 *
378 * this can be used to prevent a printf () call from rounding up:
379 * call with the decimal_places argument equal to the number of
380 * decimal places in the printf ()'s precision:
381 *
382 * - printf ("%.2f%%",           99.999  ) ==> "100.00%"
383 *
384 * - printf ("%.2f%%", tr_truncd (99.999, 2)) ==>  "99.99%"
385 *             ^                        ^
386 *             |   These should match   |
387 *             +------------------------+
388 */
389double tr_truncd (double x, int decimal_places);
390
391/* return a percent formatted string of either x.xx, xx.x or xxx */
392char* tr_strpercent (char * buf, double x, size_t buflen);
393
394/**
395 * @param buf the buffer to write the string to
396 * @param buflef buf's size
397 * @param ratio the ratio to convert to a string
398 * @param the string represntation of "infinity"
399 */
400char* tr_strratio (char * buf, size_t buflen, double ratio, const char * infinity) TR_GNUC_NONNULL (1,4);
401
402/** @brief Portability wrapper for localtime_r () that uses the system implementation if available */
403struct tm * tr_localtime_r (const time_t *_clock, struct tm *_result);
404
405struct timeval;
406
407/** @brief Portability wrapper for gettimeofday (), with tz argument dropped */
408int tr_gettimeofday (struct timeval * tv);
409
410
411/**
412 * @brief move a file
413 * @return 0 on success; otherwise, return -1 and set errno
414 */
415int tr_moveFile (const char * oldpath, const char * newpath,
416                 bool * renamed) TR_GNUC_NONNULL (1,2);
417
418/** @brief convenience function to remove an item from an array */
419void tr_removeElementFromArray (void         * array,
420                                unsigned int   index_to_remove,
421                                size_t         sizeof_element,
422                                size_t         nmemb);
423
424/***
425****
426***/
427
428/** @brief Private libtransmission variable that's visible only for inlining in tr_time () */
429extern time_t __tr_current_time;
430
431/**
432 * @brief very inexpensive form of time (NULL)
433 * @return the current epoch time in seconds
434 *
435 * This function returns a second counter that is updated once per second.
436 * If something blocks the libtransmission thread for more than a second,
437 * that counter may be thrown off, so this function is not guaranteed
438 * to always be accurate. However, it is *much* faster when 100% accuracy
439 * isn't needed
440 */
441static inline time_t tr_time (void) { return __tr_current_time; }
442
443/** @brief Private libtransmission function to update tr_time ()'s counter */
444static inline void tr_timeUpdate (time_t now) { __tr_current_time = now; }
445
446/** @brief Portability wrapper for htonll () that uses the system implementation if available */
447uint64_t tr_htonll (uint64_t);
448
449/** @brief Portability wrapper for htonll () that uses the system implementation if available */
450uint64_t tr_ntohll (uint64_t);
451
452/***
453****
454***/
455
456/* example: tr_formatter_size_init (1024, _ ("KiB"), _ ("MiB"), _ ("GiB"), _ ("TiB")); */
457
458void tr_formatter_size_init (unsigned int kilo, const char * kb, const char * mb,
459                                                const char * gb, const char * tb);
460
461void tr_formatter_speed_init (unsigned int kilo, const char * kb, const char * mb,
462                                                 const char * gb, const char * tb);
463
464void tr_formatter_mem_init (unsigned int kilo, const char * kb, const char * mb,
465                                               const char * gb, const char * tb);
466
467extern unsigned int tr_speed_K;
468extern unsigned int tr_mem_K;
469extern unsigned int tr_size_K;
470
471/* format a speed from KBps into a user-readable string. */
472char* tr_formatter_speed_KBps (char * buf, double KBps, size_t buflen);
473
474/* format a memory size from bytes into a user-readable string. */
475char* tr_formatter_mem_B (char * buf, int64_t bytes, size_t buflen);
476
477/* format a memory size from MB into a user-readable string. */
478static inline char* tr_formatter_mem_MB (char * buf, double MBps, size_t buflen) { return tr_formatter_mem_B (buf, MBps * tr_mem_K * tr_mem_K, buflen); }
479
480/* format a file size from bytes into a user-readable string. */
481char* tr_formatter_size_B (char * buf, int64_t bytes, size_t buflen);
482
483void tr_formatter_get_units (void * dict);
484
485/***
486****
487***/
488
489/** @brief Check if environment variable exists. */
490bool   tr_env_key_exists (const char * key);
491
492/** @brief Get environment variable value as int. */
493int    tr_env_get_int    (const char * key,
494                          int          default_value);
495
496/** @brief Get environment variable value as string (should be freed afterwards). */
497char * tr_env_get_string (const char * key,
498                          const char * default_value);
499
500/***
501****
502***/
503
504#ifdef __cplusplus
505}
506#endif
507
508/** @} */
509
510#endif
Note: See TracBrowser for help on using the repository browser.