source: trunk/libtransmission/utils.h @ 8561

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

(trunk libT) re-start work on making libT doxygen friendly. still a long ways to go on this.

  • Property svn:keywords set to Date Rev Author Id
File size: 13.7 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 8561 2009-05-29 19:17:12Z 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
241void tr_timevalMsec( uint64_t milliseconds, struct timeval   * setme );
242
243
244/** @brief return the current date in milliseconds */
245uint64_t       tr_date( void );
246
247/** @brief wait the specified number of milliseconds */
248void           tr_wait( uint64_t delay_milliseconds );
249
250/**
251 * @brief make a copy of 'str' whose non-utf8 content has been corrected or stripped
252 * @param str the string to make a clean copy of
253 * @param len the length of the string to copy.  If -1, the entire string is used.
254 * @param err if an error occurs and err is non-NULL, it's set to TRUE.
255 */
256char* tr_utf8clean( const char * str, int len, tr_bool * err ) TR_GNUC_MALLOC;
257
258
259/***
260****
261***/
262
263struct evbuffer;
264
265/** @brief pool of reusable buffers
266    @see tr_releaseBuffer() */
267struct evbuffer * tr_getBuffer( void );
268
269/** @brief return a buffer to the pool
270    @see tr_getBuffer() */
271void tr_releaseBuffer( struct evbuffer * buf );
272
273
274/***
275****
276***/
277
278/* Sometimes the system defines MAX/MIN, sometimes not.
279   In the latter case, define those here since we will use them */
280#ifndef MAX
281 #define MAX( a, b ) ( ( a ) > ( b ) ? ( a ) : ( b ) )
282#endif
283#ifndef MIN
284 #define MIN( a, b ) ( ( a ) > ( b ) ? ( b ) : ( a ) )
285#endif
286
287/***
288****
289***/
290
291static TR_INLINE void* tr_malloc( size_t size )
292{
293    return size ? malloc( size ) : NULL;
294}
295static TR_INLINE void* tr_malloc0( size_t size )
296{
297    return size ? calloc( 1, size ) : NULL;
298}
299static TR_INLINE void tr_free( void * p )
300{
301    if( p != NULL )
302        free( p );
303}
304static TR_INLINE void* tr_memdup( const void * src, int byteCount )
305{
306    return memcpy( tr_malloc( byteCount ), src, byteCount );
307}
308
309#define tr_new( struct_type, n_structs )           \
310    ( (struct_type *) tr_malloc ( ( (size_t) sizeof ( struct_type ) ) * ( ( size_t) ( n_structs ) ) ) )
311
312#define tr_new0( struct_type, n_structs )          \
313    ( (struct_type *) tr_malloc0 ( ( (size_t) sizeof ( struct_type ) ) * ( ( size_t) ( n_structs ) ) ) )
314
315#define tr_renew( struct_type, mem, n_structs )    \
316    ( (struct_type *) realloc ( ( mem ), ( (size_t) sizeof ( struct_type ) ) * ( ( size_t) ( n_structs ) ) ) )
317
318/** @param in is a void* so that callers can pass in both signed & unsigned without a cast */
319char* tr_strndup( const void * in, int len ) TR_GNUC_MALLOC;
320
321/** @param in is a void* so that callers can pass in both signed & unsigned without a cast */
322static TR_INLINE char* tr_strdup( const void * in )
323{
324    return tr_strndup( in, in ? strlen( (const char *) in ) : 0 );
325}
326
327/* @brief same argument list as bsearch() */
328int tr_lowerBound( const void * key,
329                   const void * base,
330                   size_t       nmemb,
331                   size_t       size,
332                   int       (* compar)(const void* key, const void* arrayMember),
333                   tr_bool    * exact_match );
334
335
336char*       tr_strdup_printf( const char * fmt,
337                              ... )  TR_GNUC_PRINTF( 1, 2 ) TR_GNUC_MALLOC;
338
339char*       tr_base64_encode( const void * input,
340                              int          inlen,
341                              int *        outlen ) TR_GNUC_MALLOC;
342
343char*       tr_base64_decode( const void * input,
344                              int          inlen,
345                              int *        outlen ) TR_GNUC_MALLOC;
346
347/** @brief Portability wrapper for strlcpy() that uses the system implementation if available */
348size_t tr_strlcpy( char * dst, const void * src, size_t siz );
349
350/** @brief Portability wrapper for snprintf() that uses the system implementation if available */
351int tr_snprintf( char * buf, size_t buflen,
352                 const char * fmt, ... ) TR_GNUC_PRINTF( 3, 4 );
353
354const char* tr_strerror( int );
355
356/** @brief strips leading and trailing whitspace from a string
357    @return the stripped string */
358char* tr_strstrip( char * str );
359
360/** @brief Portability wrapper for memmem() that uses the system implementation if available */
361const char* tr_memmem( const char * haystack, size_t haystack_len,
362                       const char * needle, size_t needle_len );
363
364/***
365****
366***/
367
368typedef void ( tr_set_func )( void * element, void * userData );
369
370void        tr_set_compare( const void * a,
371                            size_t aCount,
372                            const void * b,
373                            size_t bCount,
374                            int compare( const void * a, const void * b ),
375                            size_t elementSize,
376                            tr_set_func in_a_cb,
377                            tr_set_func in_b_cb,
378                            tr_set_func in_both_cb,
379                            void * userData );
380
381void tr_sha1_to_hex( char *          out,
382                     const uint8_t * sha1 );
383
384
385int  tr_httpIsValidURL( const char * url );
386
387int  tr_httpParseURL( const char * url,
388                      int          url_len,
389                      char **      setme_host,
390                      int *        setme_port,
391                      char **      setme_path );
392
393
394/***
395****
396***/
397
398typedef struct tr_bitfield
399{
400    uint8_t *  bits;
401    size_t     bitCount;
402    size_t     byteCount;
403}
404tr_bitfield;
405
406tr_bitfield* tr_bitfieldConstruct( tr_bitfield*, size_t bitcount );
407
408tr_bitfield* tr_bitfieldDestruct( tr_bitfield* );
409
410static TR_INLINE tr_bitfield* tr_bitfieldNew( size_t bitcount )
411{
412    return tr_bitfieldConstruct( tr_new0( tr_bitfield, 1 ), bitcount );
413}
414
415static TR_INLINE void tr_bitfieldFree( tr_bitfield * b )
416{
417    tr_free( tr_bitfieldDestruct( b ) );
418}
419
420tr_bitfield* tr_bitfieldDup( const tr_bitfield* ) TR_GNUC_MALLOC;
421
422void         tr_bitfieldClear( tr_bitfield* );
423
424int          tr_bitfieldAdd( tr_bitfield*, size_t bit );
425
426int          tr_bitfieldRem( tr_bitfield*, size_t bit );
427
428int          tr_bitfieldAddRange( tr_bitfield *, size_t begin, size_t end );
429
430int          tr_bitfieldRemRange( tr_bitfield*, size_t begin, size_t end );
431
432void         tr_bitfieldDifference( tr_bitfield *, const tr_bitfield * );
433
434int          tr_bitfieldIsEmpty( const tr_bitfield* );
435
436size_t       tr_bitfieldCountTrueBits( const tr_bitfield* );
437
438tr_bitfield* tr_bitfieldOr( tr_bitfield*, const tr_bitfield* );
439
440/** A stripped-down version of bitfieldHas to be used
441    for speed when you're looping quickly.  This version
442    has none of tr_bitfieldHas()'s safety checks, so you
443    need to call tr_bitfieldTestFast() first before you
444    start looping. */
445static TR_INLINE tr_bool tr_bitfieldHasFast( const tr_bitfield * b, const size_t nth )
446{
447    return ( b->bits[nth>>3u] << ( nth & 7u ) & 0x80 ) != 0;
448}
449
450/** @param high the highest nth bit you're going to access */
451static TR_INLINE tr_bool tr_bitfieldTestFast( const tr_bitfield * b, const size_t high )
452{
453    return ( b != NULL )
454        && ( b->bits != NULL )
455        && ( high < b->bitCount );
456}
457
458static TR_INLINE tr_bool tr_bitfieldHas( const tr_bitfield * b, size_t nth )
459{
460    return tr_bitfieldTestFast( b, nth ) && tr_bitfieldHasFast( b, nth );
461}
462
463double tr_getRatio( double numerator, double denominator );
464
465int* tr_parseNumberRange( const char * str, int str_len, int * setmeCount ) TR_GNUC_MALLOC;
466
467
468int tr_ptr2int( void* );
469
470void* tr_int2ptr( int );
471
472/**
473 * @param buf the buffer to write the string to
474 * @param buflef buf's size
475 * @param ratio the ratio to convert to a string
476 * @param the string represntation of "infinity"
477 */
478char* tr_strratio( char * buf, size_t buflen, double ratio, const char * infinity );
479
480/** @brief Portability wrapper for localtime_r() that uses the system implementation if available */
481struct tm * tr_localtime_r( const time_t *_clock, struct tm *_result );
482
483
484/** on success, return 0.  on failure, return -1 and set errno */
485int tr_moveFile( const char * oldpath, const char * newpath );
486
487
488#ifdef __cplusplus
489}
490#endif
491
492/** @} */
493
494#endif
Note: See TracBrowser for help on using the repository browser.