source: trunk/libtransmission/utils.h @ 14348

Last change on this file since 14348 was 14348, checked in by mikedld, 8 years ago

#5722: Rename remaining WIN32 uses to _WIN32

  • Property svn:keywords set to Date Rev Author Id
File size: 16.1 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 14348 2014-11-30 20:08:20Z mikedld $
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
193void      tr_win32_make_args_utf8    (int    * argc,
194                                      char *** argv);
195
196#endif
197
198/***
199****
200***/
201
202/* Sometimes the system defines MAX/MIN, sometimes not.
203   In the latter case, define those here since we will use them */
204#ifndef MAX
205 #define MAX(a, b)((a) > (b) ? (a) : (b))
206#endif
207#ifndef MIN
208 #define MIN(a, b)((a) > (b) ? (b) : (a))
209#endif
210
211/***
212****
213***/
214
215/** @brief Portability wrapper around malloc () in which `0' is a safe argument */
216void* tr_malloc (size_t size);
217
218/** @brief Portability wrapper around calloc () in which `0' is a safe argument */
219void* tr_malloc0 (size_t size);
220
221/** @brief Portability wrapper around free () in which `NULL' is a safe argument */
222void tr_free (void * p);
223
224/**
225 * @brief make a newly-allocated copy of a chunk of memory
226 * @param src the memory to copy
227 * @param byteCount the number of bytes to copy
228 * @return a newly-allocated copy of `src' that can be freed with tr_free ()
229 */
230void* tr_memdup (const void * src, size_t byteCount);
231
232#define tr_new(struct_type, n_structs)           \
233  ((struct_type *) tr_malloc (sizeof (struct_type) * ((size_t)(n_structs))))
234
235#define tr_new0(struct_type, n_structs)          \
236  ((struct_type *) tr_malloc0 (sizeof (struct_type) * ((size_t)(n_structs))))
237
238#define tr_renew(struct_type, mem, n_structs)    \
239  ((struct_type *) realloc ((mem), sizeof (struct_type) * ((size_t)(n_structs))))
240
241void* tr_valloc (size_t bufLen);
242
243/**
244 * @brief make a newly-allocated copy of a substring
245 * @param in is a void* so that callers can pass in both signed & unsigned without a cast
246 * @param len length of the substring to copy. if a length less than zero is passed in, strlen (len) is used
247 * @return a newly-allocated copy of `in' that can be freed with tr_free ()
248 */
249char* tr_strndup (const void * in, int len) TR_GNUC_MALLOC;
250
251/**
252 * @brief make a newly-allocated copy of a string
253 * @param in is a void* so that callers can pass in both signed & unsigned without a cast
254 * @return a newly-allocated copy of `in' that can be freed with tr_free ()
255 */
256char* tr_strdup (const void * in);
257
258/**
259 * @brief like strcmp () but gracefully handles NULL strings
260 */
261int tr_strcmp0 (const char * str1, const char * str2);
262
263
264
265struct evbuffer;
266
267char* evbuffer_free_to_str (struct evbuffer * buf);
268
269/** @brief similar to bsearch () but returns the index of the lower bound */
270int tr_lowerBound (const void * key,
271                   const void * base,
272                   size_t       nmemb,
273                   size_t       size,
274                   int     (* compar)(const void* key, const void* arrayMember),
275                   bool       * exact_match) TR_GNUC_HOT TR_GNUC_NONNULL (1,5,6);
276
277/** @brief moves the best k items to the first slots in the array. O(n) */
278void tr_quickfindFirstK (void * base, size_t nmemb, size_t size,
279                         int (*compar)(const void *, const void *), size_t k);
280
281/**
282 * @brief sprintf () a string into a newly-allocated buffer large enough to hold it
283 * @return a newly-allocated string that can be freed with tr_free ()
284 */
285char* tr_strdup_printf (const char * fmt, ...) TR_GNUC_PRINTF (1, 2)
286                                                TR_GNUC_MALLOC;
287char * tr_strdup_vprintf (const char * fmt,
288                          va_list      args) TR_GNUC_MALLOC;
289
290/**
291 * @brief Translate a block of bytes into base64
292 * @return a newly-allocated string that can be freed with tr_free ()
293 */
294char* tr_base64_encode (const void * input,
295                        int          inlen,
296                        int        * outlen) TR_GNUC_MALLOC;
297
298/**
299 * @brief Translate a block of bytes from base64 into raw form
300 * @return a newly-allocated string that can be freed with tr_free ()
301 */
302char* tr_base64_decode (const void * input,
303                        int          inlen,
304                        int        * outlen) TR_GNUC_MALLOC;
305
306/** @brief Portability wrapper for strlcpy () that uses the system implementation if available */
307size_t tr_strlcpy (char * dst, const void * src, size_t siz);
308
309/** @brief Portability wrapper for snprintf () that uses the system implementation if available */
310int tr_snprintf (char * buf, size_t buflen,
311                 const char * fmt, ...) TR_GNUC_PRINTF (3, 4) TR_GNUC_NONNULL (1,3);
312
313/** @brief Convenience wrapper around strerorr () guaranteed to not return NULL
314    @param errno */
315const char* tr_strerror (int);
316
317/** @brief strips leading and trailing whitspace from a string
318    @return the stripped string */
319char* tr_strstrip (char * str);
320
321/** @brief Returns true if the string ends with the specified case-insensitive suffix */
322bool tr_str_has_suffix (const char *str, const char *suffix);
323
324
325/** @brief Portability wrapper for memmem () that uses the system implementation if available */
326const char* tr_memmem (const char * haystack, size_t haystack_len,
327                       const char * needle, size_t needle_len);
328
329/** @brief Portability wrapper for strsep () that uses the system implementation if available */
330char* tr_strsep (char ** str, const char * delim);
331
332/***
333****
334***/
335
336int compareInt (const void * va, const void * vb);
337
338void tr_sha1_to_hex (char * out, const uint8_t * sha1) TR_GNUC_NONNULL (1,2);
339
340void tr_hex_to_sha1 (uint8_t * out, const char * hex) TR_GNUC_NONNULL (1,2);
341
342/** @brief convenience function to determine if an address is an IP address (IPv4 or IPv6) */
343bool tr_addressIsIP (const char * address);
344
345/** @brief return true if the url is a http or https url that Transmission understands */
346bool tr_urlIsValidTracker (const char * url) TR_GNUC_NONNULL (1);
347
348/** @brief return true if the url is a [ http, https, ftp, ftps ] url that Transmission understands */
349bool tr_urlIsValid (const char * url, int url_len) TR_GNUC_NONNULL (1);
350
351/** @brief parse a URL into its component parts
352    @return zero on success or an error number if an error occurred */
353int  tr_urlParse (const char * url,
354                  int          url_len,
355                  char      ** setme_scheme,
356                  char      ** setme_host,
357                  int        * setme_port,
358                  char      ** setme_path) TR_GNUC_NONNULL (1);
359
360
361/** @brief return TR_RATIO_NA, TR_RATIO_INF, or a number in [0..1]
362    @return TR_RATIO_NA, TR_RATIO_INF, or a number in [0..1] */
363double tr_getRatio (uint64_t numerator, uint64_t denominator);
364
365/**
366 * @brief Given a string like "1-4" or "1-4,6,9,14-51", this returns a
367 *        newly-allocated array of all the integers in the set.
368 * @return a newly-allocated array of integers that must be freed with tr_free (),
369 *         or NULL if a fragment of the string can't be parsed.
370 *
371 * For example, "5-8" will return [ 5, 6, 7, 8 ] and setmeCount will be 4.
372 */
373int* tr_parseNumberRange (const char * str,
374                          int str_len,
375                          int * setmeCount) TR_GNUC_MALLOC TR_GNUC_NONNULL (1);
376
377
378/**
379 * @brief truncate a double value at a given number of decimal places.
380 *
381 * this can be used to prevent a printf () call from rounding up:
382 * call with the decimal_places argument equal to the number of
383 * decimal places in the printf ()'s precision:
384 *
385 * - printf ("%.2f%%",           99.999  ) ==> "100.00%"
386 *
387 * - printf ("%.2f%%", tr_truncd (99.999, 2)) ==>  "99.99%"
388 *             ^                        ^
389 *             |   These should match   |
390 *             +------------------------+
391 */
392double tr_truncd (double x, int decimal_places);
393
394/* return a percent formatted string of either x.xx, xx.x or xxx */
395char* tr_strpercent (char * buf, double x, size_t buflen);
396
397/**
398 * @param buf the buffer to write the string to
399 * @param buflef buf's size
400 * @param ratio the ratio to convert to a string
401 * @param the string represntation of "infinity"
402 */
403char* tr_strratio (char * buf, size_t buflen, double ratio, const char * infinity) TR_GNUC_NONNULL (1,4);
404
405/** @brief Portability wrapper for localtime_r () that uses the system implementation if available */
406struct tm * tr_localtime_r (const time_t *_clock, struct tm *_result);
407
408struct timeval;
409
410/** @brief Portability wrapper for gettimeofday (), with tz argument dropped */
411int tr_gettimeofday (struct timeval * tv);
412
413
414/**
415 * @brief move a file
416 * @return 0 on success; otherwise, return -1 and set errno
417 */
418int tr_moveFile (const char * oldpath, const char * newpath,
419                 bool * renamed) TR_GNUC_NONNULL (1,2);
420
421/** @brief convenience function to remove an item from an array */
422void tr_removeElementFromArray (void         * array,
423                                unsigned int   index_to_remove,
424                                size_t         sizeof_element,
425                                size_t         nmemb);
426
427/***
428****
429***/
430
431/** @brief Private libtransmission variable that's visible only for inlining in tr_time () */
432extern time_t __tr_current_time;
433
434/**
435 * @brief very inexpensive form of time (NULL)
436 * @return the current epoch time in seconds
437 *
438 * This function returns a second counter that is updated once per second.
439 * If something blocks the libtransmission thread for more than a second,
440 * that counter may be thrown off, so this function is not guaranteed
441 * to always be accurate. However, it is *much* faster when 100% accuracy
442 * isn't needed
443 */
444static inline time_t tr_time (void) { return __tr_current_time; }
445
446/** @brief Private libtransmission function to update tr_time ()'s counter */
447static inline void tr_timeUpdate (time_t now) { __tr_current_time = now; }
448
449/** @brief Portability wrapper for htonll () that uses the system implementation if available */
450uint64_t tr_htonll (uint64_t);
451
452/** @brief Portability wrapper for htonll () that uses the system implementation if available */
453uint64_t tr_ntohll (uint64_t);
454
455/***
456****
457***/
458
459/* example: tr_formatter_size_init (1024, _ ("KiB"), _ ("MiB"), _ ("GiB"), _ ("TiB")); */
460
461void tr_formatter_size_init (unsigned int kilo, const char * kb, const char * mb,
462                                                const char * gb, const char * tb);
463
464void tr_formatter_speed_init (unsigned int kilo, const char * kb, const char * mb,
465                                                 const char * gb, const char * tb);
466
467void tr_formatter_mem_init (unsigned int kilo, const char * kb, const char * mb,
468                                               const char * gb, const char * tb);
469
470extern unsigned int tr_speed_K;
471extern unsigned int tr_mem_K;
472extern unsigned int tr_size_K;
473
474/* format a speed from KBps into a user-readable string. */
475char* tr_formatter_speed_KBps (char * buf, double KBps, size_t buflen);
476
477/* format a memory size from bytes into a user-readable string. */
478char* tr_formatter_mem_B (char * buf, int64_t bytes, size_t buflen);
479
480/* format a memory size from MB into a user-readable string. */
481static 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); }
482
483/* format a file size from bytes into a user-readable string. */
484char* tr_formatter_size_B (char * buf, int64_t bytes, size_t buflen);
485
486void tr_formatter_get_units (void * dict);
487
488/***
489****
490***/
491
492/** @brief Check if environment variable exists. */
493bool   tr_env_key_exists (const char * key);
494
495/** @brief Get environment variable value as int. */
496int    tr_env_get_int    (const char * key,
497                          int          default_value);
498
499/** @brief Get environment variable value as string (should be freed afterwards). */
500char * tr_env_get_string (const char * key,
501                          const char * default_value);
502
503/***
504****
505***/
506
507#ifdef __cplusplus
508}
509#endif
510
511/** @} */
512
513#endif
Note: See TracBrowser for help on using the repository browser.