transmission 2.83
[tomato.git] / release / src / router / transmission / libtransmission / utils.h
blob85d8efeb38f78c310d66103aee24911ba20b488e
1 /*
2 * This file Copyright (C) 2009-2014 Mnemosyne LLC
4 * It may be used under the GNU GPL versions 2 or 3
5 * or any future license endorsed by Mnemosyne LLC.
7 * $Id: utils.h 14241 2014-01-21 03:10:30Z jordan $
8 */
10 #ifndef TR_UTILS_H
11 #define TR_UTILS_H 1
13 #include <inttypes.h>
14 #include <stddef.h> /* size_t */
15 #include <time.h> /* time_t */
18 #ifdef __cplusplus
19 extern "C" {
20 #endif
22 /***
23 ****
24 ***/
26 /**
27 * @addtogroup utils Utilities
28 * @{
31 #ifndef UNUSED
32 #ifdef __GNUC__
33 #define UNUSED __attribute__ ((unused))
34 #else
35 #define UNUSED
36 #endif
37 #endif
39 #ifndef TR_GNUC_PRINTF
40 #ifdef __GNUC__
41 #define TR_GNUC_PRINTF(fmt, args) __attribute__ ((format (printf, fmt, args)))
42 #else
43 #define TR_GNUC_PRINTF(fmt, args)
44 #endif
45 #endif
47 #ifndef TR_GNUC_NONNULL
48 #ifdef __GNUC__
49 #define TR_GNUC_NONNULL(...) __attribute__ ((nonnull (__VA_ARGS__)))
50 #else
51 #define TR_GNUC_NONNULL(...)
52 #endif
53 #endif
55 #ifndef TR_GNUC_NULL_TERMINATED
56 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)
57 #define TR_GNUC_NULL_TERMINATED __attribute__ ((__sentinel__))
58 #define TR_GNUC_HOT __attribute ((hot))
59 #else
60 #define TR_GNUC_NULL_TERMINATED
61 #define TR_GNUC_HOT
62 #endif
63 #endif
65 #if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96)
66 #define TR_GNUC_MALLOC __attribute__ ((__malloc__))
67 #else
68 #define TR_GNUC_MALLOC
69 #endif
72 /***
73 ****
74 ***/
76 const char * tr_strip_positional_args (const char * fmt);
78 #if !defined (_)
79 #if defined (HAVE_LIBINTL_H) && !defined (SYS_DARWIN)
80 #include <libintl.h>
81 #define _(a) gettext (a)
82 #else
83 #define _(a)(a)
84 #endif
85 #endif
87 /* #define DISABLE_GETTEXT */
88 #ifndef DISABLE_GETTEXT
89 #if defined (WIN32) || defined (TR_LIGHTWEIGHT)
90 #define DISABLE_GETTEXT
91 #endif
92 #endif
93 #ifdef DISABLE_GETTEXT
94 #undef _
95 #define _(a) tr_strip_positional_args (a)
96 #endif
98 /****
99 *****
100 ****/
103 * @brief Rich Salz's classic implementation of shell-style pattern matching for ?, \, [], and * characters.
104 * @return 1 if the pattern matches, 0 if it doesn't, or -1 if an error occured
106 bool tr_wildmat (const char * text, const char * pattern) TR_GNUC_NONNULL (1,2);
108 /** @brief Portability wrapper for basename () that uses the system implementation if available */
109 char* tr_basename (const char * path) TR_GNUC_MALLOC;
111 /** @brief Portability wrapper for dirname () that uses the system implementation if available */
112 char* tr_dirname (const char * path) TR_GNUC_MALLOC;
115 * Like mkdir, but makes parent directories as needed.
117 * @return zero on success, or -1 if an error occurred
118 * (in which case errno is set appropriately).
120 int tr_mkdirp (const char * path, int permissions) TR_GNUC_NONNULL (1);
122 /** @brief Portability wrapper for mkdtemp () that uses the system implementation if available */
123 char* tr_mkdtemp (char * _template);
127 * @brief Loads a file and returns its contents.
128 * On failure, NULL is returned and errno is set.
130 uint8_t* tr_loadFile (const char * filename, size_t * size) TR_GNUC_MALLOC
131 TR_GNUC_NONNULL (1);
134 /** @brief build a filename from a series of elements using the
135 platform's correct directory separator. */
136 char* tr_buildPath (const char * first_element, ...) TR_GNUC_NULL_TERMINATED
137 TR_GNUC_MALLOC;
139 bool tr_fileExists (const char * filename, time_t * mtime);
142 * @brief Get available disk space (in bytes) for the specified folder.
143 * @return zero or positive integer on success, -1 in case of error.
145 int64_t tr_getDirFreeSpace (const char * path);
148 struct event;
151 * @brief Convenience wrapper around timer_add () to have a timer wake up in a number of seconds and microseconds
152 * @param timer
153 * @param seconds
154 * @param microseconds
156 void tr_timerAdd (struct event * timer, int seconds, int microseconds) TR_GNUC_NONNULL (1);
159 * @brief Convenience wrapper around timer_add () to have a timer wake up in a number of milliseconds
160 * @param timer
161 * @param milliseconds
163 void tr_timerAddMsec (struct event * timer, int milliseconds) TR_GNUC_NONNULL (1);
166 /** @brief return the current date in milliseconds */
167 uint64_t tr_time_msec (void);
169 /** @brief sleep the specified number of milliseconds */
170 void tr_wait_msec (long int delay_milliseconds);
173 * @brief make a copy of 'str' whose non-utf8 content has been corrected or stripped
174 * @return a newly-allocated string that must be freed with tr_free ()
175 * @param str the string to make a clean copy of
176 * @param len the length of the string to copy. If -1, the entire string is used.
178 char* tr_utf8clean (const char * str, int len) TR_GNUC_MALLOC;
181 /***
182 ****
183 ***/
185 /* Sometimes the system defines MAX/MIN, sometimes not.
186 In the latter case, define those here since we will use them */
187 #ifndef MAX
188 #define MAX(a, b)((a) > (b) ? (a) : (b))
189 #endif
190 #ifndef MIN
191 #define MIN(a, b)((a) > (b) ? (b) : (a))
192 #endif
194 /***
195 ****
196 ***/
198 /** @brief Portability wrapper around malloc () in which `0' is a safe argument */
199 void* tr_malloc (size_t size);
201 /** @brief Portability wrapper around calloc () in which `0' is a safe argument */
202 void* tr_malloc0 (size_t size);
204 /** @brief Portability wrapper around free () in which `NULL' is a safe argument */
205 void tr_free (void * p);
208 * @brief make a newly-allocated copy of a chunk of memory
209 * @param src the memory to copy
210 * @param byteCount the number of bytes to copy
211 * @return a newly-allocated copy of `src' that can be freed with tr_free ()
213 void* tr_memdup (const void * src, size_t byteCount);
215 #define tr_new(struct_type, n_structs) \
216 ((struct_type *) tr_malloc (sizeof (struct_type) * ((size_t)(n_structs))))
218 #define tr_new0(struct_type, n_structs) \
219 ((struct_type *) tr_malloc0 (sizeof (struct_type) * ((size_t)(n_structs))))
221 #define tr_renew(struct_type, mem, n_structs) \
222 ((struct_type *) realloc ((mem), sizeof (struct_type) * ((size_t)(n_structs))))
224 void* tr_valloc (size_t bufLen);
227 * @brief make a newly-allocated copy of a substring
228 * @param in is a void* so that callers can pass in both signed & unsigned without a cast
229 * @param len length of the substring to copy. if a length less than zero is passed in, strlen (len) is used
230 * @return a newly-allocated copy of `in' that can be freed with tr_free ()
232 char* tr_strndup (const void * in, int len) TR_GNUC_MALLOC;
235 * @brief make a newly-allocated copy of a string
236 * @param in is a void* so that callers can pass in both signed & unsigned without a cast
237 * @return a newly-allocated copy of `in' that can be freed with tr_free ()
239 char* tr_strdup (const void * in);
242 * @brief like strcmp () but gracefully handles NULL strings
244 int tr_strcmp0 (const char * str1, const char * str2);
248 struct evbuffer;
250 char* evbuffer_free_to_str (struct evbuffer * buf);
252 /** @brief similar to bsearch () but returns the index of the lower bound */
253 int tr_lowerBound (const void * key,
254 const void * base,
255 size_t nmemb,
256 size_t size,
257 int (* compar)(const void* key, const void* arrayMember),
258 bool * exact_match) TR_GNUC_HOT TR_GNUC_NONNULL (1,5,6);
260 /** @brief moves the best k items to the first slots in the array. O(n) */
261 void tr_quickfindFirstK (void * base, size_t nmemb, size_t size,
262 int (*compar)(const void *, const void *), size_t k);
265 * @brief sprintf () a string into a newly-allocated buffer large enough to hold it
266 * @return a newly-allocated string that can be freed with tr_free ()
268 char* tr_strdup_printf (const char * fmt, ...) TR_GNUC_PRINTF (1, 2)
269 TR_GNUC_MALLOC;
272 * @brief Translate a block of bytes into base64
273 * @return a newly-allocated string that can be freed with tr_free ()
275 char* tr_base64_encode (const void * input,
276 int inlen,
277 int * outlen) TR_GNUC_MALLOC;
280 * @brief Translate a block of bytes from base64 into raw form
281 * @return a newly-allocated string that can be freed with tr_free ()
283 char* tr_base64_decode (const void * input,
284 int inlen,
285 int * outlen) TR_GNUC_MALLOC;
287 /** @brief Portability wrapper for strlcpy () that uses the system implementation if available */
288 size_t tr_strlcpy (char * dst, const void * src, size_t siz);
290 /** @brief Portability wrapper for snprintf () that uses the system implementation if available */
291 int tr_snprintf (char * buf, size_t buflen,
292 const char * fmt, ...) TR_GNUC_PRINTF (3, 4) TR_GNUC_NONNULL (1,3);
294 /** @brief Convenience wrapper around strerorr () guaranteed to not return NULL
295 @param errno */
296 const char* tr_strerror (int);
298 /** @brief strips leading and trailing whitspace from a string
299 @return the stripped string */
300 char* tr_strstrip (char * str);
302 /** @brief Returns true if the string ends with the specified case-insensitive suffix */
303 bool tr_str_has_suffix (const char *str, const char *suffix);
306 /** @brief Portability wrapper for memmem () that uses the system implementation if available */
307 const char* tr_memmem (const char * haystack, size_t haystack_len,
308 const char * needle, size_t needle_len);
310 /** @brief Portability wrapper for strsep () that uses the system implementation if available */
311 char* tr_strsep (char ** str, const char * delim);
313 /***
314 ****
315 ***/
317 int compareInt (const void * va, const void * vb);
319 void tr_sha1_to_hex (char * out, const uint8_t * sha1) TR_GNUC_NONNULL (1,2);
321 void tr_hex_to_sha1 (uint8_t * out, const char * hex) TR_GNUC_NONNULL (1,2);
323 /** @brief convenience function to determine if an address is an IP address (IPv4 or IPv6) */
324 bool tr_addressIsIP (const char * address);
326 /** @brief return true if the url is a http or https url that Transmission understands */
327 bool tr_urlIsValidTracker (const char * url) TR_GNUC_NONNULL (1);
329 /** @brief return true if the url is a [ http, https, ftp, ftps ] url that Transmission understands */
330 bool tr_urlIsValid (const char * url, int url_len) TR_GNUC_NONNULL (1);
332 /** @brief parse a URL into its component parts
333 @return zero on success or an error number if an error occurred */
334 int tr_urlParse (const char * url,
335 int url_len,
336 char ** setme_scheme,
337 char ** setme_host,
338 int * setme_port,
339 char ** setme_path) TR_GNUC_NONNULL (1);
342 /** @brief return TR_RATIO_NA, TR_RATIO_INF, or a number in [0..1]
343 @return TR_RATIO_NA, TR_RATIO_INF, or a number in [0..1] */
344 double tr_getRatio (uint64_t numerator, uint64_t denominator);
347 * @brief Given a string like "1-4" or "1-4,6,9,14-51", this returns a
348 * newly-allocated array of all the integers in the set.
349 * @return a newly-allocated array of integers that must be freed with tr_free (),
350 * or NULL if a fragment of the string can't be parsed.
352 * For example, "5-8" will return [ 5, 6, 7, 8 ] and setmeCount will be 4.
354 int* tr_parseNumberRange (const char * str,
355 int str_len,
356 int * setmeCount) TR_GNUC_MALLOC TR_GNUC_NONNULL (1);
360 * @brief truncate a double value at a given number of decimal places.
362 * this can be used to prevent a printf () call from rounding up:
363 * call with the decimal_places argument equal to the number of
364 * decimal places in the printf ()'s precision:
366 * - printf ("%.2f%%", 99.999 ) ==> "100.00%"
368 * - printf ("%.2f%%", tr_truncd (99.999, 2)) ==> "99.99%"
369 * ^ ^
370 * | These should match |
371 * +------------------------+
373 double tr_truncd (double x, int decimal_places);
375 /* return a percent formatted string of either x.xx, xx.x or xxx */
376 char* tr_strpercent (char * buf, double x, size_t buflen);
379 * @param buf the buffer to write the string to
380 * @param buflef buf's size
381 * @param ratio the ratio to convert to a string
382 * @param the string represntation of "infinity"
384 char* tr_strratio (char * buf, size_t buflen, double ratio, const char * infinity) TR_GNUC_NONNULL (1,4);
386 /** @brief Portability wrapper for localtime_r () that uses the system implementation if available */
387 struct tm * tr_localtime_r (const time_t *_clock, struct tm *_result);
389 struct timeval;
391 /** @brief Portability wrapper for gettimeofday (), with tz argument dropped */
392 int tr_gettimeofday (struct timeval * tv);
396 * @brief move a file
397 * @return 0 on success; otherwise, return -1 and set errno
399 int tr_moveFile (const char * oldpath, const char * newpath,
400 bool * renamed) TR_GNUC_NONNULL (1,2);
402 /** @brief Portability wrapper for rename () */
403 int tr_rename (const char * oldpath_utf8, const char * newpath_utf8);
405 /** @brief Portability wrapper for remove () */
406 int tr_remove (const char * pathname_utf8);
408 /** @brief Test to see if the two filenames point to the same file. */
409 bool tr_is_same_file (const char * filename1, const char * filename2);
411 /** @brief convenience function to remove an item from an array */
412 void tr_removeElementFromArray (void * array,
413 unsigned int index_to_remove,
414 size_t sizeof_element,
415 size_t nmemb);
417 /***
418 ****
419 ***/
421 /** @brief Private libtransmission variable that's visible only for inlining in tr_time () */
422 extern time_t __tr_current_time;
425 * @brief very inexpensive form of time (NULL)
426 * @return the current epoch time in seconds
428 * This function returns a second counter that is updated once per second.
429 * If something blocks the libtransmission thread for more than a second,
430 * that counter may be thrown off, so this function is not guaranteed
431 * to always be accurate. However, it is *much* faster when 100% accuracy
432 * isn't needed
434 static inline time_t tr_time (void) { return __tr_current_time; }
436 /** @brief Private libtransmission function to update tr_time ()'s counter */
437 static inline void tr_timeUpdate (time_t now) { __tr_current_time = now; }
439 #ifdef WIN32
440 #include <windef.h> /* MAX_PATH */
441 #define TR_PATH_MAX (MAX_PATH + 1)
442 #else
443 #include <limits.h> /* PATH_MAX */
444 #ifdef PATH_MAX
445 #define TR_PATH_MAX PATH_MAX
446 #else
447 #define TR_PATH_MAX 4096
448 #endif
449 #endif
451 /** @brief Portability wrapper for realpath () that uses the system implementation if available.
452 @param resolved_path should be TR_PATH_MAX or larger */
453 char* tr_realpath (const char *path, char * resolved_path);
455 /** @brief Portability wrapper for htonll () that uses the system implementation if available */
456 uint64_t tr_htonll (uint64_t);
458 /** @brief Portability wrapper for htonll () that uses the system implementation if available */
459 uint64_t tr_ntohll (uint64_t);
461 /***
462 ****
463 ***/
465 /* example: tr_formatter_size_init (1024, _ ("KiB"), _ ("MiB"), _ ("GiB"), _ ("TiB")); */
467 void tr_formatter_size_init (unsigned int kilo, const char * kb, const char * mb,
468 const char * gb, const char * tb);
470 void tr_formatter_speed_init (unsigned int kilo, const char * kb, const char * mb,
471 const char * gb, const char * tb);
473 void tr_formatter_mem_init (unsigned int kilo, const char * kb, const char * mb,
474 const char * gb, const char * tb);
476 extern unsigned int tr_speed_K;
477 extern unsigned int tr_mem_K;
478 extern unsigned int tr_size_K;
480 /* format a speed from KBps into a user-readable string. */
481 char* tr_formatter_speed_KBps (char * buf, double KBps, size_t buflen);
483 /* format a memory size from bytes into a user-readable string. */
484 char* tr_formatter_mem_B (char * buf, int64_t bytes, size_t buflen);
486 /* format a memory size from MB into a user-readable string. */
487 static 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); }
489 /* format a file size from bytes into a user-readable string. */
490 char* tr_formatter_size_B (char * buf, int64_t bytes, size_t buflen);
492 void tr_formatter_get_units (void * dict);
494 /***
495 ****
496 ***/
498 #ifdef __cplusplus
500 #endif
502 /** @} */
504 #endif