]> Creatis software - gdcm.git/blob - src/gdcmUtil.cxx
* FIX: src/* fix the doxygen warnings.
[gdcm.git] / src / gdcmUtil.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmUtil.cxx,v $
5   Language:  C++
6   Date:      $Date: 2004/11/16 10:25:53 $
7   Version:   $Revision: 1.65 $
8                                                                                 
9   Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10   l'Image). All rights reserved. See Doc/License.txt or
11   http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
12                                                                                 
13      This software is distributed WITHOUT ANY WARRANTY; without even
14      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15      PURPOSE.  See the above copyright notices for more information.
16                                                                                 
17 =========================================================================*/
18
19 #include "gdcmUtil.h"
20 #include "gdcmDebug.h"
21
22 // For GetCurrentDate, GetCurrentTime
23 #include <time.h>
24 #include <sys/types.h>
25 #include <sys/stat.h>
26
27 #include <stdarg.h>  //only included in implementation file
28 #include <stdio.h>   //only included in implementation file
29
30 #include <unistd.h>  // for gethostname
31 #include <netdb.h>   // for gethostbyname
32
33 namespace gdcm 
34 {
35
36 /**
37  * \ingroup Globals
38  * \brief Provide a better 'c++' approach for sprintf
39  * For example c code is:
40  * sprintf(trash, "%04x|%04x", group , element);
41  *
42  * c++ is 
43  * std::ostringstream buf;
44  * buf << std::right << std::setw(4) << std::setfill('0') << std::hex
45  *     << group << "|" << std::right << std::setw(4) << std::setfill('0') 
46  *     << std::hex <<  element;
47  * buf.str();
48  */
49
50 std::string Util::Format(const char* format, ...)
51 {
52    char buffer[2048];
53    va_list args;
54    va_start(args, format);
55    vsprintf(buffer, format, args);  //might be a security flaw
56    va_end(args); // Each invocation of va_start should be matched 
57                  // by a corresponding invocation of va_end
58                  // args is then 'undefined'
59    return buffer;
60 }
61
62
63 /**
64  * \ingroup Globals
65  * \brief Because not available in C++ (?)
66  */
67 void Util::Tokenize (const std::string& str,
68                      std::vector<std::string>& tokens,
69                      const std::string& delimiters)
70 {
71    std::string::size_type lastPos = str.find_first_not_of(delimiters,0);
72    std::string::size_type pos     = str.find_first_of    (delimiters,lastPos);
73    while (std::string::npos != pos || std::string::npos != lastPos)
74    {
75       tokens.push_back(str.substr(lastPos, pos - lastPos));
76       lastPos = str.find_first_not_of(delimiters, pos);
77       pos     = str.find_first_of    (delimiters, lastPos);
78    }
79 }
80
81 /**
82  * \ingroup Globals
83  * \brief Because not available in C++ (?)
84  *        Counts the number of occurences of a substring within a string
85  */
86  
87 int Util::CountSubstring (const std::string& str,
88                           const std::string& subStr)
89 {
90    int count = 0;   // counts how many times it appears
91    unsigned int x = 0;       // The index position in the string
92
93    do
94    {
95       x = str.find(subStr,x);       // Find the substring
96       if (x != std::string::npos)   // If present
97       {
98          count++;                  // increase the count
99          x += subStr.length();     // Skip this word
100       }
101    }
102    while (x != std::string::npos);  // Carry on until not present
103
104    return count;
105 }
106
107 /**
108  * \ingroup Globals
109  * \brief  Weed out a string from the non-printable characters (in order
110  *         to avoid corrupting the terminal of invocation when printing)
111  * @param s string to remove non printable characters from
112  */
113 std::string Util::CreateCleanString(std::string const & s)
114 {
115    std::string str = s;
116
117    for(unsigned int i=0;i<str.size();i++)
118    {
119       if(!isprint(str[i]))
120       {
121          str[i]='.';
122       }
123    }
124
125    if(str.size()>0)
126    {
127       if(!isprint(s[str.size()-1]))
128       {
129          if(s[str.size()-1]==0)
130          {
131             str[str.size()-1]=' ';
132          }
133       }
134    }
135
136    return str;
137 }
138
139 /**
140  * \ingroup Globals
141  * \brief   Add a SEPARATOR to the end of the name is necessary
142  * @param   pathname file/directory name to normalize 
143  */
144 std::string Util::NormalizePath(std::string const & pathname)
145 {
146    const char SEPARATOR_X      = '/';
147    const char SEPARATOR_WIN    = '\\';
148    const std::string SEPARATOR = "/";
149    std::string name = pathname;
150    int size = name.size();
151
152    if( name[size-1] != SEPARATOR_X && name[size-1] != SEPARATOR_WIN )
153    {
154       name += SEPARATOR;
155    }
156    return name;
157 }
158
159 /**
160  * \ingroup Globals
161  * \brief   Get the (directory) path from a full path file name
162  * @param   fullName file/directory name to extract Path from
163  */
164 std::string Util::GetPath(std::string const & fullName)
165 {
166    std::string res = fullName;
167    int pos1 = res.rfind("/");
168    int pos2 = res.rfind("\\");
169    if( pos1 > pos2)
170    {
171       res.resize(pos1);
172    }
173    else
174    {
175       res.resize(pos2);
176    }
177
178    return res;
179 }
180
181 /**
182  * \ingroup Util
183  * \brief   Get the (last) name of a full path file name
184  * @param   fullName file/directory name to extract end name from
185  */
186 std::string Util::GetName(std::string const & fullName)
187 {   
188   std::string filename = fullName;
189
190   std::string::size_type slash_pos = filename.rfind("/");
191   std::string::size_type backslash_pos = filename.rfind("\\");
192   slash_pos = slash_pos > backslash_pos ? slash_pos : backslash_pos;
193   if(slash_pos != std::string::npos)
194     {
195     return filename.substr(slash_pos + 1);
196     }
197   else
198     {
199     return filename;
200     }
201
202
203 /**
204  * \ingroup Util
205  * \brief   Get the current date of the system in a dicom string
206  */
207 std::string Util::GetCurrentDate()
208 {
209     char tmp[512];
210     time_t tloc;
211     time (&tloc);    
212     strftime(tmp,512,"%Y%m%d", localtime(&tloc) );
213     return tmp;
214 }
215
216 /**
217  * \ingroup Util
218  * \brief   Get the current time of the system in a dicom string
219  */
220 std::string Util::GetCurrentTime()
221 {
222     char tmp[512];
223     time_t tloc;
224     time (&tloc);
225     strftime(tmp,512,"%H%M%S", localtime(&tloc) );
226     return tmp;  
227 }
228
229 /**
230  * \brief Create a /DICOM/ string:
231  * It should a of even length (no odd length ever)
232  * It can contain as many (if you are reading this from your
233  * editor the following character is is backslash followed by zero
234  * that needed to be escaped with an extra backslash for doxygen) \\0
235  * as you want.
236  */
237 std::string Util::DicomString(const char* s, size_t l)
238 {
239    std::string r(s, s+l);
240    assert( !(r.size() % 2) ); // == basically 'l' is even
241    return r;
242 }
243
244 /**
245  * \ingroup Util
246  * \brief Create a /DICOM/ string:
247  * It should a of even lenght (no odd length ever)
248  * It can contain as many (if you are reading this from your
249  * editor the following character is is backslash followed by zero
250  * that needed to be escaped with an extra backslash for doxygen) \\0
251  * as you want.
252  * This function is similar to DicomString(const char*), 
253  * except it doesn't take a lenght. 
254  * It only pad with a null character if length is odd
255  */
256 std::string Util::DicomString(const char* s)
257 {
258    size_t l = strlen(s);
259    if( l%2 )
260    {
261       l++;
262    }
263    std::string r(s, s+l);
264    assert( !(r.size() % 2) );
265    return r;
266 }
267
268 /**
269  * \ingroup Util
270  * \brief Safely compare two Dicom String:
271  *        - Both string should be of even lenght
272  *        - We allow padding of even lenght string by either a null 
273  *          character of a space
274  */
275 bool Util::DicomStringEqual(const std::string& s1, const char *s2)
276 {
277   // s2 is the string from the DICOM reference: 'MONOCHROME1'
278   std::string s1_even = s1; //Never change input parameter
279   std::string s2_even = DicomString( s2 );
280   if( s1_even[s1_even.size()-1] == ' ')
281   {
282     s1_even[s1_even.size()-1] = '\0'; //replace space character by null
283   }
284   return s1_even == s2_even;
285 }
286
287 /**
288  * \ingroup Util
289  * \brief   Return the IP adress of the machine writting the DICOM image
290  */
291 std::string Util::GetIPAddress()
292 {
293   // This is a rip from http://www.codeguru.com/Cpp/I-N/internet/network/article.php/c3445/
294 #ifndef HOST_NAME_MAX
295   // SUSv2 guarantees that `Host names are limited to 255 bytes'.
296   // POSIX 1003.1-2001 guarantees that `Host names (not including the
297   // terminating NUL) are limited to HOST_NAME_MAX bytes'.
298 #  define HOST_NAME_MAX 255
299   // In this case we should maybe check the string was not truncated.
300   // But I don't known how to check that...
301 #endif //HOST_NAME_MAX
302
303   std::string str;
304   char szHostName[HOST_NAME_MAX+1];
305   int r = gethostname(szHostName, HOST_NAME_MAX);
306
307   if( r == 0 )
308   {
309     // Get host adresses
310     struct hostent * pHost = gethostbyname(szHostName);
311
312     for( int i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
313     {
314       for( int j = 0; j<pHost->h_length; j++ )
315       {
316         if( j > 0 ) str += ".";
317
318         str += Util::Format("%u", 
319             (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);
320       }
321       // str now contains one local IP address 
322     }
323   }
324   // If an error occur r == -1
325   // Most of the time it will return 127.0.0.1...
326   return str;
327 }
328
329 /**
330  * \ingroup Util
331  * \brief Creates a new UID. As stipulate in the DICOM ref
332  *        each time a DICOM image is create it should have 
333  *        a unique identifier (URI)
334  */
335 std::string Util::CreateUniqueUID(const std::string& root)
336 {
337   // The code works as follow:
338   // echo "gdcm" | od -b
339   // 0000000 147 144 143 155 012
340   // Therefore we return
341   // radical + 147.144.143.155 + IP + time()
342   std::string radical = root;
343   if( !root.size() ) //anything better ?
344   {
345     radical = "0.0."; // Is this really usefull ?
346   }
347   // else
348   // A root was specified use it to forge our new UID:
349   radical += "147.144.143.155"; // gdcm
350   radical += ".";
351   radical += Util::GetIPAddress();
352   radical += ".";
353   radical += Util::GetCurrentDate();
354   radical += ".";
355   radical += Util::GetCurrentTime();
356
357   return radical;
358 }
359
360 template <class T>
361 std::ostream& binary_write(std::ostream& os, const T& val)
362 {
363     return os.write(reinterpret_cast<const char*>(&val), sizeof val);
364 }
365
366 std::ostream& binary_write(std::ostream& os, const uint16_t& val)
367 {
368 #ifdef GDCM_WORDS_BIGENDIAN
369     uint16_t swap;
370     swap = ((( val << 8 ) & 0x0ff00 ) | (( val >> 8 ) & 0x00ff ) );
371     return os.write(reinterpret_cast<const char*>(&swap), 2);
372 #else
373     return os.write(reinterpret_cast<const char*>(&val), 2);
374 #endif //GDCM_WORDS_BIGENDIAN
375 }
376
377 std::ostream& binary_write(std::ostream& os, const uint32_t& val)
378 {
379 #ifdef GDCM_WORDS_BIGENDIAN
380     uint32_t swap;
381     swap = ( ((val<<24) & 0xff000000) | ((val<<8)  & 0x00ff0000) | 
382              ((val>>8)  & 0x0000ff00) | ((val>>24) & 0x000000ff) );
383     return os.write(reinterpret_cast<const char*>(&swap), 4);
384 #else
385     return os.write(reinterpret_cast<const char*>(&val), 4);
386 #endif //GDCM_WORDS_BIGENDIAN
387 }
388
389 std::ostream& binary_write(std::ostream& os, const char* val)
390 {
391     return os.write(val, strlen(val));
392 }
393
394 std::ostream& binary_write(std::ostream& os, std::string const & val)
395 {
396     return os.write(val.c_str(), val.size());
397 }
398
399 } // end namespace gdcm
400