source: trunk/libtransmission/utils.h @ 8424

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

(trunk libT) expose tr_memmem() so it can be used by client code. use the OS' implementation if that's available.

  • Property svn:keywords set to Date Rev Author Id
File size: 13.1 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 8424 2009-05-19 04:48: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#ifndef FALSE
35 #define FALSE 0
36#endif
37
38#ifndef TRUE
39 #define TRUE 1
40#endif
41
42#ifndef UNUSED
43 #ifdef __GNUC__
44  #define UNUSED __attribute__ ( ( unused ) )
45 #else
46  #define UNUSED
47 #endif
48#endif
49
50#ifndef TR_GNUC_PRINTF
51 #ifdef __GNUC__
52  #define TR_GNUC_PRINTF( fmt,\
53                          args ) __attribute__ ( ( format ( printf, fmt,\
54                                                            args ) ) )
55 #else
56  #define TR_GNUC_PRINTF( fmt, args )
57 #endif
58#endif
59
60#ifndef TR_GNUC_NULL_TERMINATED
61 #if __GNUC__ >= 4
62  #define TR_GNUC_NULL_TERMINATED __attribute__ ( ( __sentinel__ ) )
63 #else
64  #define TR_GNUC_NULL_TERMINATED
65 #endif
66#endif
67
68#if __GNUC__ > 2 || ( __GNUC__ == 2 && __GNUC_MINOR__ >= 96 )
69 #define TR_GNUC_PURE __attribute__ ( ( __pure__ ) )
70 #define TR_GNUC_MALLOC __attribute__ ( ( __malloc__ ) )
71#else
72 #define TR_GNUC_PURE
73 #define TR_GNUC_MALLOC
74#endif
75
76
77/***
78****
79***/
80
81#if !defined( _ )
82 #if defined( HAVE_LIBINTL_H ) && !defined( SYS_DARWIN )
83  #include <libintl.h>
84  #define _( a ) gettext ( a )
85 #else
86  #define _( a ) ( a )
87 #endif
88#endif
89
90/* #define DISABLE_GETTEXT */
91#if defined(TR_EMBEDDED) && !defined(DISABLE_GETTEXT)
92 #define DISABLE_GETTEXT
93#endif
94#ifdef DISABLE_GETTEXT
95 const char * tr_strip_positional_args( const char * fmt );
96 #undef _
97 #define _( a ) tr_strip_positional_args( a )
98#endif
99
100/****
101*****
102****/
103
104void tr_assertImpl( const char * file, int line, const char * test, const char * fmt, ... ) TR_GNUC_PRINTF( 4, 5 );
105
106#ifdef NDEBUG
107 #define tr_assert( test, fmt, ... )
108#else
109 #define tr_assert( test, fmt, ... ) \
110    do { if( ! ( test ) ) tr_assertImpl( __FILE__, __LINE__, #test, fmt, __VA_ARGS__ ); } while( 0 )
111#endif
112       
113int            tr_msgLoggingIsActive( int level );
114
115void           tr_msg( const char * file,
116                       int          line,
117                       int          level,
118                       const char * torrent,
119                       const char * fmt,
120                       ... ) TR_GNUC_PRINTF( 5, 6 );
121
122#define tr_nerr( n, ... ) \
123    do { \
124        if( tr_msgLoggingIsActive( TR_MSG_ERR ) ) \
125            tr_msg( __FILE__, __LINE__, TR_MSG_ERR, n, __VA_ARGS__ ); \
126    } while( 0 )
127
128#define tr_ninf( n, ... ) \
129    do { \
130        if( tr_msgLoggingIsActive( TR_MSG_INF) ) \
131            tr_msg( __FILE__, __LINE__, TR_MSG_INF, n, __VA_ARGS__ ); \
132    } while( 0 )
133
134#define tr_ndbg( n, ... ) \
135    do { \
136        if( tr_msgLoggingIsActive( TR_MSG_DBG) ) \
137            tr_msg( __FILE__, __LINE__, TR_MSG_DBG, n, __VA_ARGS__ ); \
138    } while( 0 )
139
140#define tr_torerr( tor, ... ) \
141    do { \
142        if( tr_msgLoggingIsActive( TR_MSG_ERR ) ) \
143            tr_msg( __FILE__, __LINE__, TR_MSG_ERR, tor->info.name, __VA_ARGS__ ); \
144    } while( 0 )
145
146#define tr_torinf( tor, ... ) \
147    do { \
148        if( tr_msgLoggingIsActive( TR_MSG_INF ) ) \
149            tr_msg( __FILE__, __LINE__, TR_MSG_INF, tor->info.name, __VA_ARGS__ ); \
150    } while( 0 )
151
152#define tr_tordbg( tor, ... ) \
153    do { \
154        if( tr_msgLoggingIsActive( TR_MSG_DBG ) ) \
155            tr_msg( __FILE__, __LINE__, TR_MSG_DBG, tor->info.name, __VA_ARGS__ ); \
156    } while( 0 )
157
158#define tr_err( ... ) \
159    do { \
160        if( tr_msgLoggingIsActive( TR_MSG_ERR ) ) \
161            tr_msg( __FILE__, __LINE__, TR_MSG_ERR, NULL, __VA_ARGS__ ); \
162    } while( 0 )
163
164#define tr_inf( ... ) \
165    do { \
166        if( tr_msgLoggingIsActive( TR_MSG_INF ) ) \
167            tr_msg( __FILE__, __LINE__, TR_MSG_INF, NULL, __VA_ARGS__ ); \
168    } while( 0 )
169
170#define tr_dbg( ... ) \
171    do { \
172        if( tr_msgLoggingIsActive( TR_MSG_DBG ) ) \
173            tr_msg( __FILE__, __LINE__, TR_MSG_DBG, NULL, __VA_ARGS__ ); \
174    } while( 0 )
175
176
177
178FILE*          tr_getLog( void );
179
180tr_bool        tr_deepLoggingIsActive( void );
181
182void           tr_deepLog( const char * file,
183                           int          line,
184                           const char * name,
185                           const char * fmt,
186                           ... ) TR_GNUC_PRINTF( 4, 5 );
187
188char*          tr_getLogTimeStr( char * buf,
189                                 int    buflen );
190
191
192int            tr_wildmat( const char * text,
193                           const char * pattern );
194
195/** a portability wrapper for basename(). */
196char*          tr_basename( const char * path ) TR_GNUC_MALLOC;
197
198/** a portability wrapper for dirname(). */
199char*          tr_dirname( const char * path ) TR_GNUC_MALLOC;
200
201/**
202 * a portability wrapper around mkdir().
203 * On WIN32, the `permissions' argument is unused.
204 *
205 * @return zero on success, or -1 if an error occurred
206 * (in which case errno is set appropriately).
207 */
208int            tr_mkdir( const char * path,
209                         int          permissions );
210
211/**
212 * Like mkdir, but makes parent directories as needed.
213 *
214 * @return zero on success, or -1 if an error occurred
215 * (in which case errno is set appropriately).
216 */
217int            tr_mkdirp( const char * path,
218                          int          permissions );
219
220
221/**
222 * Loads a file and returns its contents.
223 * On failure, NULL is returned and errno is set.
224 */
225uint8_t*       tr_loadFile( const char * filename,
226                            size_t *     size ) TR_GNUC_MALLOC;
227
228
229/* creates a filename from a series of elements using the
230   correct separator for filenames. */
231char*          tr_buildPath( const char * first_element, ... )
232                                              TR_GNUC_NULL_TERMINATED
233                                              TR_GNUC_MALLOC;
234
235struct timeval;
236
237void tr_timevalMsec( uint64_t           milliseconds,
238                     struct timeval   * setme );
239
240
241/* return the current date in milliseconds */
242uint64_t       tr_date( void );
243
244/* wait the specified number of milliseconds */
245void           tr_wait( uint64_t delay_milliseconds );
246
247char*          tr_utf8clean( const char  * str,
248                             int           max_len,
249                             tr_bool     * err );
250
251
252/***
253****
254***/
255
256struct evbuffer;
257
258/** @brief pool of reusable buffers
259    @see tr_releaseBuffer() */
260struct evbuffer * tr_getBuffer( void );
261
262/** @brief return a buffer to the pool
263    @see tr_getBuffer() */
264void tr_releaseBuffer( struct evbuffer * buf );
265
266
267/***
268****
269***/
270
271/* Sometimes the system defines MAX/MIN, sometimes not. In the latter
272   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
340size_t      tr_strlcpy( char *       dst,
341                        const void * src,
342                        size_t       siz );
343
344int         tr_snprintf( char *       buf,
345                         size_t       buflen,
346                         const char * fmt,
347                         ... ) TR_GNUC_PRINTF( 3, 4 );
348
349const char* tr_strerror( int );
350
351char*       tr_strstrip( char * str );
352
353const char* tr_memmem( const char * haystack, size_t haystack_len,
354                       const char * needle, size_t needle_len );
355
356/***
357****
358***/
359
360typedef void ( tr_set_func )( void * element, void * userData );
361
362void        tr_set_compare( const void * a,
363                            size_t aCount,
364                            const void * b,
365                            size_t bCount,
366                            int compare( const void * a, const void * b ),
367                            size_t elementSize,
368                            tr_set_func in_a_cb,
369                            tr_set_func in_b_cb,
370                            tr_set_func in_both_cb,
371                            void * userData );
372
373void tr_sha1_to_hex( char *          out,
374                     const uint8_t * sha1 );
375
376
377int  tr_httpIsValidURL( const char * url );
378
379int  tr_httpParseURL( const char * url,
380                      int          url_len,
381                      char **      setme_host,
382                      int *        setme_port,
383                      char **      setme_path );
384
385
386/***
387****
388***/
389
390typedef struct tr_bitfield
391{
392    uint8_t *  bits;
393    size_t     bitCount;
394    size_t     byteCount;
395}
396tr_bitfield;
397
398tr_bitfield* tr_bitfieldConstruct( tr_bitfield*, size_t bitcount );
399
400tr_bitfield* tr_bitfieldDestruct( tr_bitfield* );
401
402static TR_INLINE tr_bitfield* tr_bitfieldNew( size_t bitcount )
403{
404    return tr_bitfieldConstruct( tr_new0( tr_bitfield, 1 ), bitcount );
405}
406
407static TR_INLINE void tr_bitfieldFree( tr_bitfield * b )
408{
409    tr_free( tr_bitfieldDestruct( b ) );
410}
411
412tr_bitfield* tr_bitfieldDup( const tr_bitfield* ) TR_GNUC_MALLOC;
413
414void         tr_bitfieldClear( tr_bitfield* );
415
416int          tr_bitfieldAdd( tr_bitfield*, size_t bit );
417
418int          tr_bitfieldRem( tr_bitfield*, size_t bit );
419
420int          tr_bitfieldAddRange( tr_bitfield *, size_t begin, size_t end );
421
422int          tr_bitfieldRemRange( tr_bitfield*, size_t begin, size_t end );
423
424void         tr_bitfieldDifference( tr_bitfield *, const tr_bitfield * );
425
426int          tr_bitfieldIsEmpty( const tr_bitfield* );
427
428size_t       tr_bitfieldCountTrueBits( const tr_bitfield* );
429
430tr_bitfield* tr_bitfieldOr( tr_bitfield*, const tr_bitfield* );
431
432/** A stripped-down version of bitfieldHas to be used
433    for speed when you're looping quickly.  This version
434    has none of tr_bitfieldHas()'s safety checks, so you
435    need to call tr_bitfieldTestFast() first before you
436    start looping. */
437static TR_INLINE tr_bool tr_bitfieldHasFast( const tr_bitfield * b, const size_t nth )
438{
439    return ( b->bits[nth>>3u] << ( nth & 7u ) & 0x80 ) != 0;
440}
441
442/** @param high the highest nth bit you're going to access */
443static TR_INLINE tr_bool tr_bitfieldTestFast( const tr_bitfield * b, const size_t high )
444{
445    return ( b != NULL )
446        && ( b->bits != NULL )
447        && ( high < b->bitCount );
448}
449
450static TR_INLINE tr_bool tr_bitfieldHas( const tr_bitfield * b, size_t nth )
451{
452    return tr_bitfieldTestFast( b, nth ) && tr_bitfieldHasFast( b, nth );
453}
454
455double tr_getRatio( double numerator, double denominator );
456
457int* tr_parseNumberRange( const char * str, int str_len, int * setmeCount );
458
459
460int tr_ptr2int( void* );
461
462void* tr_int2ptr( int );
463
464/**
465 * @param buf the buffer to write the string to
466 * @param buflef buf's size
467 * @param ratio the ratio to convert to a string
468 * @param the string represntation of "infinity"
469 */
470char* tr_strratio( char * buf, size_t buflen, double ratio, const char * infinity );
471
472struct tm * tr_localtime_r( const time_t *_clock, struct tm *_result );
473
474
475/** on success, return 0.  on failure, return -1 and set errno */
476int tr_moveFile( const char * oldpath, const char * newpath );
477
478
479#ifdef __cplusplus
480}
481#endif
482
483#endif
Note: See TracBrowser for help on using the repository browser.