source: trunk/libtransmission/utils.h @ 10031

Last change on this file since 10031 was 10031, checked in by charles, 12 years ago

(trunk) remove unnecessary #includes

  • Property svn:keywords set to Date Rev Author Id
File size: 16.9 KB
Line 
1/*
2 * This file Copyright (C) 2009-2010 Mnemosyne LLC
3 *
4 * This file is licensed by the GPL version 2.  Works owned by the
5 * Transmission project are granted a special exemption to clause 2(b)
6 * so that the bulk of its code can remain under the MIT license.
7 * This exemption does not extend to derived works not owned by
8 * the Transmission project.
9 *
10 * $Id: utils.h 10031 2010-01-28 13:33:40Z charles $
11 */
12
13#ifndef TR_UTILS_H
14#define TR_UTILS_H 1
15
16#include <inttypes.h>
17#include <stddef.h> /* size_t */
18#include <stdio.h> /* FILE* */
19#include <string.h> /* memcpy()* */
20#include <stdlib.h> /* malloc() */
21#include <time.h> /* time_t */
22
23#include "transmission.h"
24
25#ifdef __cplusplus
26extern "C" {
27#endif
28
29/***
30****
31***/
32
33/**
34 * @addtogroup utils Utilities
35 * @{
36 */
37
38#ifndef FALSE
39 #define FALSE 0
40#endif
41
42#ifndef TRUE
43 #define TRUE 1
44#endif
45
46#ifndef UNUSED
47 #ifdef __GNUC__
48  #define UNUSED __attribute__ ( ( unused ) )
49 #else
50  #define UNUSED
51 #endif
52#endif
53
54#ifndef TR_GNUC_PRINTF
55 #ifdef __GNUC__
56  #define TR_GNUC_PRINTF( fmt, args ) __attribute__ ( ( format ( printf, fmt, args ) ) )
57 #else
58  #define TR_GNUC_PRINTF( fmt, args )
59 #endif
60#endif
61
62#ifndef TR_GNUC_NONNULL
63 #ifdef __GNUC__
64  #define TR_GNUC_NONNULL( ... ) __attribute__((nonnull (__VA_ARGS__)))
65 #else
66  #define TR_GNUC_NONNULL( ... )
67 #endif
68#endif
69
70#ifndef TR_GNUC_NULL_TERMINATED
71 #if __GNUC__ > 4 || ( __GNUC__ == 4 && __GNUC_MINOR__ >= 3 )
72  #define TR_GNUC_NULL_TERMINATED __attribute__ ( ( __sentinel__ ) )
73  #define TR_GNUC_HOT __attribute ( ( hot ) )
74 #else
75  #define TR_GNUC_NULL_TERMINATED
76  #define TR_GNUC_HOT
77 #endif
78#endif
79
80#if __GNUC__ > 2 || ( __GNUC__ == 2 && __GNUC_MINOR__ >= 96 )
81 #define TR_GNUC_PURE __attribute__ ( ( __pure__ ) )
82 #define TR_GNUC_MALLOC __attribute__ ( ( __malloc__ ) )
83#else
84 #define TR_GNUC_PURE
85 #define TR_GNUC_MALLOC
86#endif
87
88
89/***
90****
91***/
92
93#if !defined( _ )
94 #if defined( HAVE_LIBINTL_H ) && !defined( SYS_DARWIN )
95  #include <libintl.h>
96  #define _( a ) gettext ( a )
97 #else
98  #define _( a ) ( a )
99 #endif
100#endif
101
102/* #define DISABLE_GETTEXT */
103#if defined(TR_EMBEDDED) && !defined(DISABLE_GETTEXT)
104 #define DISABLE_GETTEXT
105#endif
106#ifdef DISABLE_GETTEXT
107 const char * tr_strip_positional_args( const char * fmt );
108 #undef _
109 #define _( a ) tr_strip_positional_args( a )
110#endif
111
112/****
113*****
114****/
115
116void tr_msgInit( void );
117
118#define TR_MAX_MSG_LOG 10000
119
120extern int messageLevel;
121
122static inline tr_bool tr_msgLoggingIsActive( int level )
123{
124    return messageLevel >= level;
125}
126
127void tr_msg( const char * file, int line,
128             int level,
129             const char * torrent,
130             const char * fmt, ... ) TR_GNUC_PRINTF( 5, 6 );
131
132#define tr_nerr( n, ... ) \
133    do { \
134        if( tr_msgLoggingIsActive( TR_MSG_ERR ) ) \
135            tr_msg( __FILE__, __LINE__, TR_MSG_ERR, n, __VA_ARGS__ ); \
136    } while( 0 )
137
138#define tr_ninf( n, ... ) \
139    do { \
140        if( tr_msgLoggingIsActive( TR_MSG_INF) ) \
141            tr_msg( __FILE__, __LINE__, TR_MSG_INF, n, __VA_ARGS__ ); \
142    } while( 0 )
143
144#define tr_ndbg( n, ... ) \
145    do { \
146        if( tr_msgLoggingIsActive( TR_MSG_DBG) ) \
147            tr_msg( __FILE__, __LINE__, TR_MSG_DBG, n, __VA_ARGS__ ); \
148    } while( 0 )
149
150#define tr_torerr( tor, ... ) \
151    do { \
152        if( tr_msgLoggingIsActive( TR_MSG_ERR ) ) \
153            tr_msg( __FILE__, __LINE__, TR_MSG_ERR, tor->info.name, __VA_ARGS__ ); \
154    } while( 0 )
155
156#define tr_torinf( tor, ... ) \
157    do { \
158        if( tr_msgLoggingIsActive( TR_MSG_INF ) ) \
159            tr_msg( __FILE__, __LINE__, TR_MSG_INF, tor->info.name, __VA_ARGS__ ); \
160    } while( 0 )
161
162#define tr_tordbg( tor, ... ) \
163    do { \
164        if( tr_msgLoggingIsActive( TR_MSG_DBG ) ) \
165            tr_msg( __FILE__, __LINE__, TR_MSG_DBG, tor->info.name, __VA_ARGS__ ); \
166    } while( 0 )
167
168#define tr_err( ... ) \
169    do { \
170        if( tr_msgLoggingIsActive( TR_MSG_ERR ) ) \
171            tr_msg( __FILE__, __LINE__, TR_MSG_ERR, NULL, __VA_ARGS__ ); \
172    } while( 0 )
173
174#define tr_inf( ... ) \
175    do { \
176        if( tr_msgLoggingIsActive( TR_MSG_INF ) ) \
177            tr_msg( __FILE__, __LINE__, TR_MSG_INF, NULL, __VA_ARGS__ ); \
178    } while( 0 )
179
180#define tr_dbg( ... ) \
181    do { \
182        if( tr_msgLoggingIsActive( TR_MSG_DBG ) ) \
183            tr_msg( __FILE__, __LINE__, TR_MSG_DBG, NULL, __VA_ARGS__ ); \
184    } while( 0 )
185
186
187
188FILE*          tr_getLog( void );
189
190/** @brief return true if deep logging has been enabled by the user; false otherwise */
191tr_bool tr_deepLoggingIsActive( void );
192
193void           tr_deepLog( const char * file,
194                           int          line,
195                           const char * name,
196                           const char * fmt,
197                           ... ) TR_GNUC_PRINTF( 4, 5 ) TR_GNUC_NONNULL(1,4);
198
199/** @brief set the buffer with the current time formatted for deep logging. */
200char* tr_getLogTimeStr( char * buf, int buflen ) TR_GNUC_NONNULL(1);
201
202
203/**
204 * @brief Rich Salz's classic implementation of shell-style pattern matching for ?, \, [], and * characters.
205 * @return 1 if the pattern matches, 0 if it doesn't, or -1 if an error occured
206 */
207int tr_wildmat( const char * text, const char * pattern ) TR_GNUC_NONNULL(1,2);
208
209/** @brief Portability wrapper for basename() that uses the system implementation if available */
210char* tr_basename( const char * path ) TR_GNUC_MALLOC;
211
212/** @brief Portability wrapper for dirname() that uses the system implementation if available */
213char* tr_dirname( const char * path ) TR_GNUC_MALLOC;
214
215/**
216 * @brief Portability wrapper for mkdir()
217 *
218 * A portability wrapper around mkdir().
219 * On WIN32, the `permissions' argument is unused.
220 *
221 * @return zero on success, or -1 if an error occurred
222 * (in which case errno is set appropriately).
223 */
224int tr_mkdir( const char * path, int permissions ) TR_GNUC_NONNULL(1);
225
226/**
227 * Like mkdir, but makes parent directories as needed.
228 *
229 * @return zero on success, or -1 if an error occurred
230 * (in which case errno is set appropriately).
231 */
232int tr_mkdirp( const char * path, int permissions ) TR_GNUC_NONNULL(1);
233
234
235/**
236 * @brief Loads a file and returns its contents.
237 * On failure, NULL is returned and errno is set.
238 */
239uint8_t* tr_loadFile( const char * filename, size_t * size ) TR_GNUC_MALLOC
240                                                             TR_GNUC_NONNULL(1);
241
242
243/** @brief build a filename from a series of elements using the
244           platform's correct directory separator. */
245char* tr_buildPath( const char * first_element, ... ) TR_GNUC_NULL_TERMINATED
246                                                      TR_GNUC_MALLOC;
247
248struct event;
249
250/**
251 * @brief Convenience wrapper around timer_add() to have a timer wake up in a number of seconds and microseconds
252 * @param timer
253 * @param seconds
254 * @param microseconds
255 */
256void tr_timerAdd( struct event * timer, int seconds, int microseconds ) TR_GNUC_NONNULL(1);
257
258/**
259 * @brief Convenience wrapper around timer_add() to have a timer wake up in a number of milliseconds
260 * @param timer
261 * @param milliseconds
262 */
263void tr_timerAddMsec( struct event * timer, int milliseconds ) TR_GNUC_NONNULL(1);
264
265
266/** @brief return the current date in milliseconds */
267uint64_t tr_date( void );
268
269/** @brief sleep the specified number of milliseconds */
270void tr_wait_msec( uint64_t delay_milliseconds );
271
272/**
273 * @brief make a copy of 'str' whose non-utf8 content has been corrected or stripped
274 * @return a newly-allocated string that must be freed with tr_free()
275 * @param str the string to make a clean copy of
276 * @param len the length of the string to copy.  If -1, the entire string is used.
277 * @param err if an error occurs and err is non-NULL, it's set to TRUE.
278 */
279char* tr_utf8clean( const char * str, int len, tr_bool * err ) TR_GNUC_MALLOC;
280
281
282/***
283****
284***/
285
286/* Sometimes the system defines MAX/MIN, sometimes not.
287   In the latter case, define those here since we will use them */
288#ifndef MAX
289 #define MAX( a, b ) ( ( a ) > ( b ) ? ( a ) : ( b ) )
290#endif
291#ifndef MIN
292 #define MIN( a, b ) ( ( a ) > ( b ) ? ( b ) : ( a ) )
293#endif
294
295/***
296****
297***/
298
299/** @brief Portability wrapper around malloc() in which `0' is a safe argument */
300static inline void* tr_malloc( size_t size )
301{
302    return size ? malloc( size ) : NULL;
303}
304
305/** @brief Portability wrapper around calloc() in which `0' is a safe argument */
306static inline void* tr_malloc0( size_t size )
307{
308    return size ? calloc( 1, size ) : NULL;
309}
310
311/** @brief Portability wrapper around free() in which `NULL' is a safe argument */
312static inline void tr_free( void * p )
313{
314    if( p != NULL )
315        free( p );
316}
317
318/**
319 * @brief make a newly-allocated copy of a chunk of memory
320 * @param src the memory to copy
321 * @param byteCount the number of bytes to copy
322 * @return a newly-allocated copy of `src' that can be freed with tr_free()
323 */
324static inline void* tr_memdup( const void * src, int byteCount )
325{
326    return memcpy( tr_malloc( byteCount ), src, byteCount );
327}
328
329#define tr_new( struct_type, n_structs )           \
330    ( (struct_type *) tr_malloc ( ( (size_t) sizeof ( struct_type ) ) * ( ( size_t) ( n_structs ) ) ) )
331
332#define tr_new0( struct_type, n_structs )          \
333    ( (struct_type *) tr_malloc0 ( ( (size_t) sizeof ( struct_type ) ) * ( ( size_t) ( n_structs ) ) ) )
334
335#define tr_renew( struct_type, mem, n_structs )    \
336    ( (struct_type *) realloc ( ( mem ), ( (size_t) sizeof ( struct_type ) ) * ( ( size_t) ( n_structs ) ) ) )
337
338/**
339 * @brief make a newly-allocated copy of a substring
340 * @param in is a void* so that callers can pass in both signed & unsigned without a cast
341 * @param len length of the substring to copy.  if a length less than zero is passed in, strlen( len ) is used
342 * @return a newly-allocated copy of `in' that can be freed with tr_free()
343 */
344char* tr_strndup( const void * in, int len ) TR_GNUC_MALLOC;
345
346/**
347 * @brief make a newly-allocated copy of a string
348 * @param in is a void* so that callers can pass in both signed & unsigned without a cast
349 * @return a newly-allocated copy of `in' that can be freed with tr_free()
350 */
351static inline char* tr_strdup( const void * in )
352{
353    return tr_strndup( in, in ? strlen( (const char *) in ) : 0 );
354}
355
356/** @brief similar to bsearch() but returns the index of the lower bound */
357int tr_lowerBound( const void * key,
358                   const void * base,
359                   size_t       nmemb,
360                   size_t       size,
361                   int       (* compar)(const void* key, const void* arrayMember),
362                   tr_bool    * exact_match ) TR_GNUC_HOT TR_GNUC_NONNULL(1,5,6);
363
364
365/**
366 * @brief sprintf() a string into a newly-allocated buffer large enough to hold it
367 * @return a newly-allocated string that can be freed with tr_free()
368 */
369char* tr_strdup_printf( const char * fmt, ... ) TR_GNUC_PRINTF( 1, 2 )
370                                                TR_GNUC_MALLOC;
371
372/**
373 * @brief Translate a block of bytes into base64
374 * @return a newly-allocated string that can be freed with tr_free()
375 */
376char* tr_base64_encode( const void * input,
377                        int          inlen,
378                        int        * outlen ) TR_GNUC_MALLOC;
379
380/**
381 * @brief Translate a block of bytes from base64 into raw form
382 * @return a newly-allocated string that can be freed with tr_free()
383 */
384char* tr_base64_decode( const void * input,
385                        int          inlen,
386                        int        * outlen ) TR_GNUC_MALLOC;
387
388/** @brief Portability wrapper for strlcpy() that uses the system implementation if available */
389size_t tr_strlcpy( char * dst, const void * src, size_t siz );
390
391/** @brief Portability wrapper for snprintf() that uses the system implementation if available */
392int tr_snprintf( char * buf, size_t buflen,
393                 const char * fmt, ... ) TR_GNUC_PRINTF( 3, 4 ) TR_GNUC_NONNULL(1,3);
394
395/** @brief Convenience wrapper around strerorr() guaranteed to not return NULL
396    @param errno */
397const char* tr_strerror( int );
398
399/** @brief strips leading and trailing whitspace from a string
400    @return the stripped string */
401char* tr_strstrip( char * str );
402
403/** @brief Portability wrapper for memmem() that uses the system implementation if available */
404const char* tr_memmem( const char * haystack, size_t haystack_len,
405                       const char * needle, size_t needle_len );
406
407/***
408****
409***/
410
411typedef void ( tr_set_func )( void * element, void * userData );
412
413/**
414 * @brief find the differences and commonalities in two sorted sets
415 * @param a the first set
416 * @param aCount the number of elements in the set 'a'
417 * @param b the second set
418 * @param bCount the number of elements in the set 'b'
419 * @param compare the sorting method for both sets
420 * @param elementSize the sizeof the element in the two sorted sets
421 * @param in_a called for items in set 'a' but not set 'b'
422 * @param in_b called for items in set 'b' but not set 'a'
423 * @param in_both called for items that are in both sets
424 * @param userData user data passed along to in_a, in_b, and in_both
425 */
426void tr_set_compare( const void * a, size_t aCount,
427                     const void * b, size_t bCount,
428                     int compare( const void * a, const void * b ),
429                     size_t elementSize,
430                     tr_set_func in_a_cb,
431                     tr_set_func in_b_cb,
432                     tr_set_func in_both_cb,
433                     void * userData );
434
435void tr_sha1_to_hex( char * out, const uint8_t * sha1 ) TR_GNUC_NONNULL(1,2);
436
437void tr_hex_to_sha1( uint8_t * out, const char * hex ) TR_GNUC_NONNULL(1,2);
438
439
440/** @brief return TRUE if the url is a http, https, or ftp url that Transmission understands */
441tr_bool tr_httpIsValidURL( const char * url ) TR_GNUC_NONNULL(1);
442
443/** @brief parse a URL into its component parts
444    @return zero on success or an error number if an error occurred */
445int  tr_httpParseURL( const char * url,
446                      int          url_len,
447                      char      ** setme_host,
448                      int        * setme_port,
449                      char      ** setme_path ) TR_GNUC_NONNULL(1);
450
451
452/** @brief return TR_RATIO_NA, TR_RATIO_INF, or a number in [0..1]
453    @return TR_RATIO_NA, TR_RATIO_INF, or a number in [0..1] */
454double tr_getRatio( double numerator, double denominator );
455
456/**
457 * @brief Given a string like "1-4" or "1-4,6,9,14-51", this returns a
458 *        newly-allocated array of all the integers in the set.
459 * @return a newly-allocated array of integers that must be freed with tr_free(),
460 *         or NULL if a fragment of the string can't be parsed.
461 *
462 * For example, "5-8" will return [ 5, 6, 7, 8 ] and setmeCount will be 4.
463 */
464int* tr_parseNumberRange( const char * str,
465                          int str_len,
466                          int * setmeCount ) TR_GNUC_MALLOC TR_GNUC_NONNULL(1);
467
468
469/**
470 * @brief truncate a double value at a given number of decimal places.
471 *
472 * this can be used to prevent a printf() call from rounding up:
473 * call with the decimal_places argument equal to the number of
474 * decimal places in the printf()'s precision:
475 *
476 * - printf("%.2f%%",           99.999    ) ==> "100.00%"
477 *
478 * - printf("%.2f%%", tr_truncd(99.999, 2)) ==>  "99.99%"
479 *             ^                        ^
480 *             |   These should match   |
481 *             +------------------------+
482 */
483double tr_truncd( double x, int decimal_places );
484
485/**
486 * @param buf the buffer to write the string to
487 * @param buflef buf's size
488 * @param ratio the ratio to convert to a string
489 * @param the string represntation of "infinity"
490 */
491char* tr_strratio( char * buf, size_t buflen, double ratio, const char * infinity ) TR_GNUC_NONNULL(1,4);
492
493/** @brief Portability wrapper for localtime_r() that uses the system implementation if available */
494struct tm * tr_localtime_r( const time_t *_clock, struct tm *_result );
495
496
497/**
498 * @brief move a file
499 * @return 0 on success; otherwise, return -1 and set errno
500 */
501int tr_moveFile( const char * oldpath, const char * newpath,
502                 tr_bool * renamed ) TR_GNUC_NONNULL(1,2);
503
504/** @brief convenience function to remove an item from an array */
505static inline void tr_removeElementFromArray( void   * array,
506                                              int      index_to_remove,
507                                              size_t   sizeof_element,
508                                              size_t   nmemb )
509{
510    char * a = (char*) array;
511
512    memmove( a + sizeof_element * index_to_remove,
513             a + sizeof_element * ( index_to_remove  + 1 ),
514             sizeof_element * ( --nmemb - index_to_remove ) );
515}
516
517/***
518****
519***/
520
521/** @brief Private libtransmission variable that's visible only for inlining in tr_time() */
522extern time_t transmission_now;
523
524/**
525 * @brief very inexpensive form of time(NULL)
526 * @return the current epoch time in seconds
527 *
528 * This function returns a second counter that is updated once per second.
529 * If something blocks the libtransmission thread for more than a second,
530 * that counter may be thrown off, so this function is not guaranteed
531 * to always be accurate.  However, it is *much* faster when 100% accuracy
532 * isn't needed
533 */
534static inline time_t tr_time( void ) { return transmission_now; }
535
536/** @brief Private libtransmission function to update the second counter used by tr_time() */
537void tr_timeUpdate( time_t now );
538
539/***
540****
541***/
542
543#ifdef __cplusplus
544}
545#endif
546
547/** @} */
548
549#endif
Note: See TracBrowser for help on using the repository browser.