]> Creatis software - gdcm.git/blob - src/gdcmUtil.cxx
ENH: Slightly bigger patch:
[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 02:54:35 $
7   Version:   $Revision: 1.64 $
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 name 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  * \ingroup Util
231  * \brief Create a /DICOM/ string:
232  * It should a of even length (no odd length ever)
233  * It can contains as many \0 as you want.
234  */
235 std::string Util::DicomString(const char* s, size_t l)
236 {
237    std::string r(s, s+l);
238    assert( !(r.size() % 2) ); // == basically 'l' is even
239    return r;
240 }
241
242 /**
243  * \ingroup Util
244  * \brief Create a /DICOM/ string:
245  * It should a of even lenght (no odd length ever)
246  * It can contains as many \0 as you want.
247  * This function is similar to DicomString(const char*), 
248  * except it doesn't take a lenght. 
249  * It only pad with a null character if length is odd
250  */
251 std::string Util::DicomString(const char* s)
252 {
253    size_t l = strlen(s);
254    if( l%2 )
255    {
256       l++;
257    }
258    std::string r(s, s+l);
259    assert( !(r.size() % 2) );
260    return r;
261 }
262
263 /**
264  * \ingroup Util
265  * \brief Safely compare two Dicom String:
266  *        - Both string should be of even lenght
267  *        - We allow padding of even lenght string by either a null 
268  *          character of a space
269  */
270 bool Util::DicomStringEqual(const std::string& s1, const char *s2)
271 {
272   // s2 is the string from the DICOM reference: 'MONOCHROME1'
273   std::string s1_even = s1; //Never change input parameter
274   std::string s2_even = DicomString( s2 );
275   if( s1_even[s1_even.size()-1] == ' ')
276   {
277     s1_even[s1_even.size()-1] = '\0'; //replace space character by null
278   }
279   return s1_even == s2_even;
280 }
281
282 /**
283  * \ingroup Util
284  * \brief   Return the IP adress of the machine writting the DICOM image
285  */
286 std::string Util::GetIPAddress()
287 {
288   // This is a rip from http://www.codeguru.com/Cpp/I-N/internet/network/article.php/c3445/
289 #ifndef HOST_NAME_MAX
290   // SUSv2 guarantees that `Host names are limited to 255 bytes'.
291   // POSIX 1003.1-2001 guarantees that `Host names (not including the
292   // terminating NUL) are limited to HOST_NAME_MAX bytes'.
293 #  define HOST_NAME_MAX 255
294   // In this case we should maybe check the string was not truncated.
295   // But I don't known how to check that...
296 #endif //HOST_NAME_MAX
297
298   std::string str;
299   char szHostName[HOST_NAME_MAX+1];
300   int r = gethostname(szHostName, HOST_NAME_MAX);
301
302   if( r == 0 )
303   {
304     // Get host adresses
305     struct hostent * pHost = gethostbyname(szHostName);
306
307     for( int i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
308     {
309       for( int j = 0; j<pHost->h_length; j++ )
310       {
311         if( j > 0 ) str += ".";
312
313         str += Util::Format("%u", 
314             (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);
315       }
316       // str now contains one local IP address 
317     }
318   }
319   // If an error occur r == -1
320   // Most of the time it will return 127.0.0.1...
321   return str;
322 }
323
324 /**
325  * \ingroup Util
326  * \brief Creates a new UID. As stipulate in the DICOM ref
327  *        each time a DICOM image is create it should have 
328  *        a unique identifier (URI)
329  */
330 std::string Util::CreateUniqueUID(const std::string& root)
331 {
332   // The code works as follow:
333   // echo "gdcm" | od -b
334   // 0000000 147 144 143 155 012
335   // Therefore we return
336   // radical + 147.144.143.155 + IP + time()
337   std::string radical = root;
338   if( !root.size() ) //anything better ?
339   {
340     radical = "0.0."; // Is this really usefull ?
341   }
342   // else
343   // A root was specified use it to forge our new UID:
344   radical += "147.144.143.155"; // gdcm
345   radical += ".";
346   radical += Util::GetIPAddress();
347   radical += ".";
348   radical += Util::GetCurrentDate();
349   radical += ".";
350   radical += Util::GetCurrentTime();
351
352   return radical;
353 }
354
355 template <class T>
356 std::ostream& binary_write(std::ostream& os, const T& val)
357 {
358     return os.write(reinterpret_cast<const char*>(&val), sizeof val);
359 }
360
361 std::ostream& binary_write(std::ostream& os, const uint16_t& val)
362 {
363 #ifdef GDCM_WORDS_BIGENDIAN
364     uint16_t swap;
365     swap = ((( val << 8 ) & 0x0ff00 ) | (( val >> 8 ) & 0x00ff ) );
366     return os.write(reinterpret_cast<const char*>(&swap), 2);
367 #else
368     return os.write(reinterpret_cast<const char*>(&val), 2);
369 #endif //GDCM_WORDS_BIGENDIAN
370 }
371
372 std::ostream& binary_write(std::ostream& os, const uint32_t& val)
373 {
374 #ifdef GDCM_WORDS_BIGENDIAN
375     uint32_t swap;
376     swap = ( ((val<<24) & 0xff000000) | ((val<<8)  & 0x00ff0000) | 
377              ((val>>8)  & 0x0000ff00) | ((val>>24) & 0x000000ff) );
378     return os.write(reinterpret_cast<const char*>(&swap), 4);
379 #else
380     return os.write(reinterpret_cast<const char*>(&val), 4);
381 #endif //GDCM_WORDS_BIGENDIAN
382 }
383
384 std::ostream& binary_write(std::ostream& os, const char* val)
385 {
386     return os.write(val, strlen(val));
387 }
388
389 std::ostream& binary_write(std::ostream& os, std::string const & val)
390 {
391     return os.write(val.c_str(), val.size());
392 }
393
394 } // end namespace gdcm
395