source: trunk/libtransmission/utils.h @ 14321

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

(trunk, libT) #4160 'foreign character support' -- merge mike.dld's 4160-03a-file.platch, which introduces tr_sys_file_*() portability wrappers

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