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