source: trunk/libtransmission/utils.h @ 9421

Last change on this file since 9421 was 9421, checked in by charles, 13 years ago

(trunk libT) #2531: when the user moves a torrent from one location to another, we don't need to reverify if the files are just rename()d

  • Property svn:keywords set to Date Rev Author Id
File size: 12.3 KB
Line 
1/*
2 * This file Copyright (C) 2009 Charles Kerr <charles@transmissionbt.com>
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 9421 2009-10-27 23:00:34Z 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,\
58                          args ) __attribute__ ( ( format ( printf, fmt,\
59                                                            args ) ) )
60 #else
61  #define TR_GNUC_PRINTF( fmt, args )
62 #endif
63#endif
64
65#ifndef TR_GNUC_NULL_TERMINATED
66 #if __GNUC__ >= 4
67  #define TR_GNUC_NULL_TERMINATED __attribute__ ( ( __sentinel__ ) )
68 #else
69  #define TR_GNUC_NULL_TERMINATED
70 #endif
71#endif
72
73#if __GNUC__ > 2 || ( __GNUC__ == 2 && __GNUC_MINOR__ >= 96 )
74 #define TR_GNUC_PURE __attribute__ ( ( __pure__ ) )
75 #define TR_GNUC_MALLOC __attribute__ ( ( __malloc__ ) )
76#else
77 #define TR_GNUC_PURE
78 #define TR_GNUC_MALLOC
79#endif
80
81
82/***
83****
84***/
85
86#if !defined( _ )
87 #if defined( HAVE_LIBINTL_H ) && !defined( SYS_DARWIN )
88  #include <libintl.h>
89  #define _( a ) gettext ( a )
90 #else
91  #define _( a ) ( a )
92 #endif
93#endif
94
95/* #define DISABLE_GETTEXT */
96#if defined(TR_EMBEDDED) && !defined(DISABLE_GETTEXT)
97 #define DISABLE_GETTEXT
98#endif
99#ifdef DISABLE_GETTEXT
100 const char * tr_strip_positional_args( const char * fmt );
101 #undef _
102 #define _( a ) tr_strip_positional_args( a )
103#endif
104
105/****
106*****
107****/
108
109void tr_assertImpl( const char * file, int line, const char * test, const char * fmt, ... ) TR_GNUC_PRINTF( 4, 5 );
110
111#ifdef NDEBUG
112 #define tr_assert( test, fmt, ... )
113#else
114 #define tr_assert( test, fmt, ... ) \
115    do { if( ! ( test ) ) tr_assertImpl( __FILE__, __LINE__, #test, fmt, __VA_ARGS__ ); } while( 0 )
116#endif
117
118int            tr_msgLoggingIsActive( int level );
119
120void           tr_msg( const char * file,
121                       int          line,
122                       int          level,
123                       const char * torrent,
124                       const char * fmt,
125                       ... ) TR_GNUC_PRINTF( 5, 6 );
126
127#define tr_nerr( n, ... ) \
128    do { \
129        if( tr_msgLoggingIsActive( TR_MSG_ERR ) ) \
130            tr_msg( __FILE__, __LINE__, TR_MSG_ERR, n, __VA_ARGS__ ); \
131    } while( 0 )
132
133#define tr_ninf( n, ... ) \
134    do { \
135        if( tr_msgLoggingIsActive( TR_MSG_INF) ) \
136            tr_msg( __FILE__, __LINE__, TR_MSG_INF, n, __VA_ARGS__ ); \
137    } while( 0 )
138
139#define tr_ndbg( n, ... ) \
140    do { \
141        if( tr_msgLoggingIsActive( TR_MSG_DBG) ) \
142            tr_msg( __FILE__, __LINE__, TR_MSG_DBG, n, __VA_ARGS__ ); \
143    } while( 0 )
144
145#define tr_torerr( tor, ... ) \
146    do { \
147        if( tr_msgLoggingIsActive( TR_MSG_ERR ) ) \
148            tr_msg( __FILE__, __LINE__, TR_MSG_ERR, tor->info.name, __VA_ARGS__ ); \
149    } while( 0 )
150
151#define tr_torinf( tor, ... ) \
152    do { \
153        if( tr_msgLoggingIsActive( TR_MSG_INF ) ) \
154            tr_msg( __FILE__, __LINE__, TR_MSG_INF, tor->info.name, __VA_ARGS__ ); \
155    } while( 0 )
156
157#define tr_tordbg( tor, ... ) \
158    do { \
159        if( tr_msgLoggingIsActive( TR_MSG_DBG ) ) \
160            tr_msg( __FILE__, __LINE__, TR_MSG_DBG, tor->info.name, __VA_ARGS__ ); \
161    } while( 0 )
162
163#define tr_err( ... ) \
164    do { \
165        if( tr_msgLoggingIsActive( TR_MSG_ERR ) ) \
166            tr_msg( __FILE__, __LINE__, TR_MSG_ERR, NULL, __VA_ARGS__ ); \
167    } while( 0 )
168
169#define tr_inf( ... ) \
170    do { \
171        if( tr_msgLoggingIsActive( TR_MSG_INF ) ) \
172            tr_msg( __FILE__, __LINE__, TR_MSG_INF, NULL, __VA_ARGS__ ); \
173    } while( 0 )
174
175#define tr_dbg( ... ) \
176    do { \
177        if( tr_msgLoggingIsActive( TR_MSG_DBG ) ) \
178            tr_msg( __FILE__, __LINE__, TR_MSG_DBG, NULL, __VA_ARGS__ ); \
179    } while( 0 )
180
181
182
183FILE*          tr_getLog( void );
184
185tr_bool        tr_deepLoggingIsActive( void );
186
187void           tr_deepLog( const char * file,
188                           int          line,
189                           const char * name,
190                           const char * fmt,
191                           ... ) TR_GNUC_PRINTF( 4, 5 );
192
193char*          tr_getLogTimeStr( char * buf,
194                                 int    buflen );
195
196
197int            tr_wildmat( const char * text,
198                           const char * pattern );
199
200/** @brief Portability wrapper for basename() that uses the system implementation if available */
201char* tr_basename( const char * path ) TR_GNUC_MALLOC;
202
203/** @brief Portability wrapper for dirname() that uses the system implementation if available */
204char* tr_dirname( const char * path ) TR_GNUC_MALLOC;
205
206/**
207 * @brief Portability wrapper for mkdir()
208 *
209 * a portability wrapper around mkdir().
210 * On WIN32, the `permissions' argument is unused.
211 *
212 * @return zero on success, or -1 if an error occurred
213 * (in which case errno is set appropriately).
214 */
215int            tr_mkdir( const char * path,
216                         int          permissions );
217
218/**
219 * Like mkdir, but makes parent directories as needed.
220 *
221 * @return zero on success, or -1 if an error occurred
222 * (in which case errno is set appropriately).
223 */
224int tr_mkdirp( const char * path, int permissions );
225
226
227/**
228 * @brief Loads a file and returns its contents.
229 * On failure, NULL is returned and errno is set.
230 */
231uint8_t* tr_loadFile( const char * filename, size_t * size ) TR_GNUC_MALLOC;
232
233
234/** @brief build a filename from a series of elements using the
235           platform's correct directory separator. */
236char* tr_buildPath( const char * first_element, ... ) TR_GNUC_NULL_TERMINATED
237                                                      TR_GNUC_MALLOC;
238
239struct timeval;
240
241tr_bool tr_isTimeval( const struct timeval * tv );
242
243void tr_timevalMsec( uint64_t milliseconds, struct timeval * setme );
244
245void tr_timevalSet( struct timeval * setme, int seconds, int microseconds );
246
247struct event;
248
249void tr_timerAdd( struct event * timer, int seconds, int milliseconds );
250
251
252/** @brief return the current date in milliseconds */
253uint64_t       tr_date( void );
254
255/** @brief wait the specified number of milliseconds */
256void           tr_wait( uint64_t delay_milliseconds );
257
258/**
259 * @brief make a copy of 'str' whose non-utf8 content has been corrected or stripped
260 * @param str the string to make a clean copy of
261 * @param len the length of the string to copy.  If -1, the entire string is used.
262 * @param err if an error occurs and err is non-NULL, it's set to TRUE.
263 */
264char* tr_utf8clean( const char * str, int len, tr_bool * err ) TR_GNUC_MALLOC;
265
266
267/***
268****
269***/
270
271/* Sometimes the system defines MAX/MIN, sometimes not.
272   In the latter case, define those here since we will use them */
273#ifndef MAX
274 #define MAX( a, b ) ( ( a ) > ( b ) ? ( a ) : ( b ) )
275#endif
276#ifndef MIN
277 #define MIN( a, b ) ( ( a ) > ( b ) ? ( b ) : ( a ) )
278#endif
279
280/***
281****
282***/
283
284static TR_INLINE void* tr_malloc( size_t size )
285{
286    return size ? malloc( size ) : NULL;
287}
288static TR_INLINE void* tr_malloc0( size_t size )
289{
290    return size ? calloc( 1, size ) : NULL;
291}
292static TR_INLINE void tr_free( void * p )
293{
294    if( p != NULL )
295        free( p );
296}
297static TR_INLINE void* tr_memdup( const void * src, int byteCount )
298{
299    return memcpy( tr_malloc( byteCount ), src, byteCount );
300}
301
302#define tr_new( struct_type, n_structs )           \
303    ( (struct_type *) tr_malloc ( ( (size_t) sizeof ( struct_type ) ) * ( ( size_t) ( n_structs ) ) ) )
304
305#define tr_new0( struct_type, n_structs )          \
306    ( (struct_type *) tr_malloc0 ( ( (size_t) sizeof ( struct_type ) ) * ( ( size_t) ( n_structs ) ) ) )
307
308#define tr_renew( struct_type, mem, n_structs )    \
309    ( (struct_type *) realloc ( ( mem ), ( (size_t) sizeof ( struct_type ) ) * ( ( size_t) ( n_structs ) ) ) )
310
311/** @param in is a void* so that callers can pass in both signed & unsigned without a cast */
312char* tr_strndup( const void * in, int len ) TR_GNUC_MALLOC;
313
314/** @param in is a void* so that callers can pass in both signed & unsigned without a cast */
315static TR_INLINE char* tr_strdup( const void * in )
316{
317    return tr_strndup( in, in ? strlen( (const char *) in ) : 0 );
318}
319
320/* @brief same argument list as bsearch() */
321int tr_lowerBound( const void * key,
322                   const void * base,
323                   size_t       nmemb,
324                   size_t       size,
325                   int       (* compar)(const void* key, const void* arrayMember),
326                   tr_bool    * exact_match );
327
328
329char*       tr_strdup_printf( const char * fmt,
330                              ... )  TR_GNUC_PRINTF( 1, 2 ) TR_GNUC_MALLOC;
331
332char*       tr_base64_encode( const void * input,
333                              int          inlen,
334                              int *        outlen ) TR_GNUC_MALLOC;
335
336char*       tr_base64_decode( const void * input,
337                              int          inlen,
338                              int *        outlen ) TR_GNUC_MALLOC;
339
340/** @brief Portability wrapper for strlcpy() that uses the system implementation if available */
341size_t tr_strlcpy( char * dst, const void * src, size_t siz );
342
343/** @brief Portability wrapper for snprintf() that uses the system implementation if available */
344int tr_snprintf( char * buf, size_t buflen,
345                 const char * fmt, ... ) TR_GNUC_PRINTF( 3, 4 );
346
347const char* tr_strerror( int );
348
349/** @brief strips leading and trailing whitspace from a string
350    @return the stripped string */
351char* tr_strstrip( char * str );
352
353/** @brief Portability wrapper for memmem() that uses the system implementation if available */
354const char* tr_memmem( const char * haystack, size_t haystack_len,
355                       const char * needle, size_t needle_len );
356
357/***
358****
359***/
360
361typedef void ( tr_set_func )( void * element, void * userData );
362
363void        tr_set_compare( const void * a,
364                            size_t aCount,
365                            const void * b,
366                            size_t bCount,
367                            int compare( const void * a, const void * b ),
368                            size_t elementSize,
369                            tr_set_func in_a_cb,
370                            tr_set_func in_b_cb,
371                            tr_set_func in_both_cb,
372                            void * userData );
373
374void tr_sha1_to_hex( char *          out,
375                     const uint8_t * sha1 );
376
377
378tr_bool tr_httpIsValidURL( const char * url );
379
380int  tr_httpParseURL( const char * url,
381                      int          url_len,
382                      char **      setme_host,
383                      int *        setme_port,
384                      char **      setme_path );
385
386double tr_getRatio( double numerator, double denominator );
387
388int* tr_parseNumberRange( const char * str, int str_len, int * setmeCount ) TR_GNUC_MALLOC;
389
390
391int tr_ptr2int( void* );
392
393void* tr_int2ptr( int );
394
395/* truncate a double value at a given number of decimal places.
396   this can be used to prevent a printf() call from rounding up:
397   call with the decimal_places argument equal to the number of
398   decimal places in the printf()'s precision:
399
400   - printf("%.2f%%",           99.999    ) ==> "100.00%"
401
402   - printf("%.2f%%", tr_truncd(99.999, 2)) ==>  "99.99%"
403               ^                        ^
404               |   These should match   |
405               +------------------------+
406*/
407double tr_truncd( double x, int decimal_places );
408
409/**
410 * @param buf the buffer to write the string to
411 * @param buflef buf's size
412 * @param ratio the ratio to convert to a string
413 * @param the string represntation of "infinity"
414 */
415char* tr_strratio( char * buf, size_t buflen, double ratio, const char * infinity );
416
417/** @brief Portability wrapper for localtime_r() that uses the system implementation if available */
418struct tm * tr_localtime_r( const time_t *_clock, struct tm *_result );
419
420
421/** on success, return 0.  on failure, return -1 and set errno */
422int tr_moveFile( const char * oldpath, const char * newpath, tr_bool * renamed );
423
424
425#ifdef __cplusplus
426}
427#endif
428
429/** @} */
430
431#endif
Note: See TracBrowser for help on using the repository browser.