source: trunk/libtransmission/utils.h @ 14320

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

(trunk, libT) #4160 'foreign character support' -- merge mike.dld's 4160-02b-path.patch, which updates the codebase to use the new tr_sys_path_*() portability wrappers introduced in 4160-02a

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