Remove spaces and tabs at end of lines.
[synfig.git] / ETL / trunk / ETL / _stringf.h
1 /* =========================================================================
2 ** Extended Template and Library
3 ** stringf Procedure Implementation
4 ** $Id$
5 **
6 ** Copyright (c) 2002 Robert B. Quattlebaum Jr.
7 ** Copyright (c) 2007 Chris Moore
8 **
9 ** This package is free software; you can redistribute it and/or
10 ** modify it under the terms of the GNU General Public License as
11 ** published by the Free Software Foundation; either version 2 of
12 ** the License, or (at your option) any later version.
13 **
14 ** This package is distributed in the hope that it will be useful,
15 ** but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17 ** General Public License for more details.
18 **
19 ** === N O T E S ===========================================================
20 **
21 ** This is an internal header file, included by other ETL headers.
22 ** You should not attempt to use it directly.
23 **
24 ** ========================================================================= */
25
26 /* === S T A R T =========================================================== */
27
28 #ifndef __ETL__STRINGF_H
29 #define __ETL__STRINGF_H
30
31 /* === H E A D E R S ======================================================= */
32
33 #include <string>
34 #include <cstdarg>
35 #include <cstdlib>
36
37 /* === M A C R O S ========================================================= */
38
39 #ifndef ETL_STRPRINTF_MAX_LENGTH
40 #define ETL_STRPRINTF_MAX_LENGTH        (800)
41 #endif
42
43 #ifdef WIN32
44 #define POPEN_BINARY_READ_TYPE "rb"
45 #define POPEN_BINARY_WRITE_TYPE "wb"
46 #else
47 #define POPEN_BINARY_READ_TYPE "r"
48 #define POPEN_BINARY_WRITE_TYPE "w"
49 #endif
50
51 /* === T Y P E D E F S ===================================================== */
52
53 _ETL_BEGIN_CDECLS
54
55 #if defined(__APPLE__) || defined(__CYGWIN__) || defined(_WIN32)
56 #define ETL_NO_THROW
57 #else
58 #define ETL_NO_THROW throw()
59 #endif
60
61 #ifdef HAVE_VASPRINTF   // This is the preferred method
62  extern int vasprintf(char **,const char *,va_list)ETL_NO_THROW;
63 #else
64
65 # ifdef HAVE_VSNPRINTF  // This is the secondary method
66  extern int vsnprintf(char *,size_t,const char*,va_list)ETL_NO_THROW;
67 # endif
68
69 #endif
70
71 #ifdef HAVE_VSSCANF
72 extern int vsscanf(const char *,const char *,va_list)ETL_NO_THROW;
73 #else
74 #define ETL_NO_VSTRSCANF
75 #ifdef HAVE_SSCANF
76 extern int sscanf(const char *buf, const char *format, ...)ETL_NO_THROW;
77 #endif
78 #endif
79
80 #include <unistd.h>
81
82 _ETL_END_CDECLS
83
84 /* === C L A S S E S & S T R U C T S ======================================= */
85
86 _ETL_BEGIN_NAMESPACE
87
88 inline std::string
89 vstrprintf(const char *format, va_list args)
90 {
91 #ifdef HAVE_VASPRINTF   // This is the preferred method (and safest)
92         char *buffer;
93         std::string ret;
94         int i=vasprintf(&buffer,format,args);
95         if (i>-1)
96         {
97                 ret=buffer;
98                 free(buffer);
99         }
100         return ret;
101 #else
102 #ifdef HAVE_VSNPRINTF   // This is the secondary method (Safe, but bulky)
103 #warning etl::vstrprintf() has a maximum size of ETL_STRPRINTF_MAX_LENGTH in this configuration.
104 #ifdef ETL_THREAD_SAFE
105         char buffer[ETL_STRPRINTF_MAX_LENGTH];
106 #else
107         static char buffer[ETL_STRPRINTF_MAX_LENGTH];
108 #endif
109         vsnprintf(buffer,sizeof(buffer),format,args);
110         return buffer;
111 #else                                   // This is the worst method (UNSAFE, but "works")
112 #warning Potential for Buffer-overflow bug using vsprintf
113 #define ETL_UNSAFE_STRPRINTF    (true)
114 // Here, we are doubling the size of the buffer to make this case
115 // slightly more safe.
116 #ifdef ETL_THREAD_SAFE
117         char buffer[ETL_STRPRINTF_MAX_LENGTH*2];
118 #else
119         static char buffer[ETL_STRPRINTF_MAX_LENGTH*2];
120 #endif
121         vsprintf(buffer,format,args);
122         return buffer;
123 #endif
124 #endif
125 }
126
127 inline std::string
128 strprintf(const char *format, ...)
129 {
130         va_list args;
131         va_start(args,format);
132         return vstrprintf(format,args);
133 }
134
135 #ifndef ETL_NO_VSTRSCANF
136 inline int
137 vstrscanf(const std::string &data, const char*format, va_list args)
138 {
139     return vsscanf(data.c_str(),format,args);
140 }
141
142 inline int
143 strscanf(const std::string &data, const char*format, ...)
144 {
145         va_list args;
146         va_start(args,format);
147         return vstrscanf(data, format,args);
148 }
149 #else
150
151 #if defined (HAVE_SSCANF) && defined (__GNUC__)
152 #define strscanf(data,format,...) sscanf(data.c_str(),format,__VA_ARGS__)
153 #endif
154 #endif
155
156
157 #define stratof(X) (atof((X).c_str()))
158 #define stratoi(X) (atoi((X).c_str()))
159
160 inline std::string
161 basename(const std::string &str)
162 {
163         std::string::const_iterator iter;
164
165         if(str.size() == 1 && str[0] == ETL_DIRECTORY_SEPARATOR)
166                 return str;
167
168         if(str.end()[-1]==ETL_DIRECTORY_SEPARATOR)
169                 iter=str.end()-2;
170         else
171                 iter=str.end()-1;
172
173         for(;iter!=str.begin();iter--)
174                 if(*iter==ETL_DIRECTORY_SEPARATOR)
175                         break;
176
177         if (*iter==ETL_DIRECTORY_SEPARATOR)
178                 iter++;
179
180         if(str.end()[-1]==ETL_DIRECTORY_SEPARATOR)
181                 return std::string(iter,str.end()-1);
182
183         return std::string(iter,str.end());
184 }
185
186 inline std::string
187 dirname(const std::string &str)
188 {
189         std::string::const_iterator iter;
190
191         if(str.size() == 1 && str[0] == ETL_DIRECTORY_SEPARATOR)
192                 return str;
193
194         if(str.end()[-1]==ETL_DIRECTORY_SEPARATOR)
195                 iter=str.end()-2;
196         else
197                 iter=str.end()-1;
198
199         for(;iter!=str.begin();iter--)
200                 if(*iter==ETL_DIRECTORY_SEPARATOR)
201                         break;
202
203         if(iter==str.begin())
204         {
205            if (*iter==ETL_DIRECTORY_SEPARATOR)
206                    return "/";
207            else
208                    return ".";
209         }
210
211         return std::string(str.begin(),iter);
212 }
213
214 // filename_extension("/f.e/d.c") => ".c"
215 inline std::string
216 filename_extension(const std::string &str)
217 {
218         std::string base = basename(str);
219         std::string::size_type pos = base.find_last_of('.');
220         if (pos == std::string::npos) return std::string();
221         return base.substr(pos);
222 }
223
224 // filename_sans_extension("/f.e/d.c") => "/f.e/d"
225 inline std::string
226 filename_sans_extension(const std::string &str)
227 {
228         std::string base = basename(str);
229         std::string::size_type pos = base.find_last_of('.');
230         if (pos == std::string::npos) return str;
231         std::string dir = dirname(str);
232         if (dir == ".") return base.substr(0,pos);
233         return dir + ETL_DIRECTORY_SEPARATOR + base.substr(0,pos);
234 }
235
236 inline bool
237 is_absolute_path(const std::string &path)
238 {
239 #ifdef WIN32
240         if(path.size()>=3 && path[1]==':' && (path[2]=='\\' || path[2]=='/'))
241                 return true;
242 #endif
243         if(!path.empty() && path[0]==ETL_DIRECTORY_SEPARATOR)
244                 return true;
245         return false;
246 }
247
248 inline std::string
249 unix_to_local_path(const std::string &path)
250 {
251         std::string ret;
252         std::string::const_iterator iter;
253         for(iter=path.begin();iter!=path.end();iter++)
254                 switch(*iter)
255                 {
256                 case '/':
257                         ret+=ETL_DIRECTORY_SEPARATOR;
258                         break;
259                 case '~':
260                         ret+='~';
261                         break;
262                 default:
263                         ret+=*iter;
264                         break;
265                 }
266         return ret;
267 }
268
269 inline std::string
270 current_working_directory()
271 {
272         char dir[256];
273         std::string ret(getcwd(dir,sizeof(dir)));
274         return ret;
275 }
276
277 inline std::string
278 get_root_from_path(std::string path)
279 {
280         std::string ret;
281         std::string::const_iterator iter;
282
283         for(iter=path.begin();iter!=path.end();++iter)
284         {
285                 if(*iter==ETL_DIRECTORY_SEPARATOR)
286                         break;
287                 ret+=*iter;
288         }
289         //if(iter!=path.end())
290                 ret+=ETL_DIRECTORY_SEPARATOR;
291         return ret;
292 }
293
294 inline std::string
295 remove_root_from_path(std::string path)
296 {
297         while(!path.empty())
298         {
299                 if(path[0]==ETL_DIRECTORY_SEPARATOR)
300                 {
301                         path.erase(path.begin());
302                         return path;
303                 }
304                 path.erase(path.begin());
305         }
306         return path;
307 }
308
309 inline std::string
310 cleanup_path(std::string path)
311 {
312         std::string ret;
313
314         while(basename(path)=="."&&path.size()!=1)path=dirname(path);
315
316         while(!path.empty())
317         {
318                 std::string dir(get_root_from_path(path));
319                 if((dir=="../" || dir=="..\\") && ret.size())
320                 {
321                         ret=dirname(ret);
322                         if (*(ret.end()-1)!=ETL_DIRECTORY_SEPARATOR)
323                                 ret+=ETL_DIRECTORY_SEPARATOR;
324                 }
325                 else if((dir!="./" && dir!=".\\") && dir!=".")
326                         ret+=dir;
327                 path=remove_root_from_path(path);
328         }
329         if (ret.size()==0)ret+='.';
330
331         // Remove any trailing directory separators
332         if(ret.size() && ret[ret.size()-1]==ETL_DIRECTORY_SEPARATOR)
333                 ret.erase(ret.begin()+ret.size()-1);
334         return ret;
335 }
336
337 inline std::string
338 absolute_path(std::string path)
339 {
340         std::string ret(current_working_directory());
341
342         if(path.empty())
343                 return cleanup_path(ret);
344         if(is_absolute_path(path))
345                 return cleanup_path(path);
346         return cleanup_path(ret+ETL_DIRECTORY_SEPARATOR+path);
347 }
348
349 inline std::string
350 relative_path(std::string curr_path,std::string dest_path)
351 {
352         // If dest_path is already a relative path,
353         // then there is no need to do anything.
354         if(!is_absolute_path(dest_path))
355                 dest_path=absolute_path(dest_path);
356         else
357                 dest_path=cleanup_path(dest_path);
358
359         if(!is_absolute_path(curr_path))
360                 curr_path=absolute_path(curr_path);
361         else
362                 curr_path=cleanup_path(curr_path);
363
364 #ifdef WIN32
365         // If we are on windows and the dest path is on a different drive,
366         // then there is no way to make a relative path to it.
367         if(dest_path.size()>=3 && dest_path[1]==':' && dest_path[0]!=curr_path[0])
368                 return dest_path;
369 #endif
370
371         if(curr_path==dirname(dest_path))
372                 return basename(dest_path);
373
374         while(!dest_path.empty() && !curr_path.empty() && get_root_from_path(dest_path)==get_root_from_path(curr_path))
375         {
376                 dest_path=remove_root_from_path(dest_path);
377                 curr_path=remove_root_from_path(curr_path);
378         }
379
380         while(!curr_path.empty())
381         {
382                 dest_path=std::string("..")+ETL_DIRECTORY_SEPARATOR+dest_path;
383                 curr_path=remove_root_from_path(curr_path);
384         }
385
386         return dest_path;
387 }
388
389 _ETL_END_NAMESPACE
390
391 /* === E N D =============================================================== */
392
393 #endif