source: trunk/libtransmission/utils.h @ 9891

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

(trunk libT) more documentation and doxygen markup

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