gxtext.cpp
Go to the documentation of this file.
1 //
2 // Copyright (C) 2001-2013 Graeme Walker <graeme_walker@users.sourceforge.net>
3 //
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with this program. If not, see <http://www.gnu.org/licenses/>.
16 // ===
17 //
18 // gxtext.cpp
19 //
20 
21 #include "gdef.h"
22 #include "gxtext.h"
23 #include "gassert.h"
24 
25 namespace
26 {
27  inline char hex( unsigned int n )
28  {
29  static const char * map = "0123456789ABCDEF" ;
30  return map[n] ;
31  }
32  inline unsigned int unhex( char c )
33  {
34  unsigned int rc = 0U ;
35  switch( c )
36  {
37  case '0': rc = 0U ; break ;
38  case '1': rc = 1U ; break ;
39  case '2': rc = 2U ; break ;
40  case '3': rc = 3U ; break ;
41  case '4': rc = 4U ; break ;
42  case '5': rc = 5U ; break ;
43  case '6': rc = 6U ; break ;
44  case '7': rc = 7U ; break ;
45  case '8': rc = 8U ; break ;
46  case '9': rc = 9U ; break ;
47  case 'A': rc = 10U ; break ;
48  case 'B': rc = 11U ; break ;
49  case 'C': rc = 12U ; break ;
50  case 'D': rc = 13U ; break ;
51  case 'E': rc = 14U ; break ;
52  case 'F': rc = 15U ; break ;
53  }
54  return rc ;
55  }
56 }
57 
58 std::string G::Xtext::encode( const std::string & s )
59 {
60  std::string result ;
61  for( std::string::const_iterator p = s.begin() ; p != s.end() ; ++p )
62  {
63  if( *p >= '!' && *p <= '~' && *p != '=' && *p != '+' )
64  {
65  result.append( 1U , *p ) ;
66  }
67  else
68  {
69  unsigned int n = static_cast<unsigned char>(*p) ;
70  result.append( 1U , '+' ) ;
71  result.append( 1U , hex( n >> 4U ) ) ;
72  result.append( 1U , hex( n & 0x0f ) ) ;
73  }
74  }
75  G_ASSERT( decode(result) == s ) ;
76  return result ;
77 }
78 
79 std::string G::Xtext::decode( const std::string & s )
80 {
81  std::string result ;
82  for( const char * p = s.c_str() ; *p ; p++ )
83  {
84  if( *p == '+' && p[1U] && p[2U] )
85  {
86  unsigned int c = ( unhex(p[1U]) << 4U ) | unhex(p[2U]) ;
87  result.append( 1U , static_cast<char>(static_cast<unsigned char>(c)) ) ;
88  p += 2U ;
89  }
90  else
91  {
92  result.append( 1U , *p ) ;
93  }
94  }
95  return result ;
96 }
97 
static std::string decode(const std::string &)
Decodes the given string.
Definition: gxtext.cpp:79
static std::string encode(const std::string &)
Encodes the given string.
Definition: gxtext.cpp:58
#define G_ASSERT(test)
Definition: gassert.h:30