1
1
// This file may be redistributed and modified under the terms of the
2
2
// GNU Lesser General Public License (See COPYING for details).
3
// Copyright (C) 2000-2001 Stefanus Du Toit, Michael Day
3
// Copyright (C) 2000 Stefanus Du Toit, Michael Day
5
5
#ifndef ATLAS_CODECS_UTILITY_H
6
6
#define ATLAS_CODECS_UTILITY_H
22
21
namespace Atlas { namespace Codecs {
24
23
/// Convert an ASCII char to its hexadecimal value
25
24
inline const std::string charToHex(char c)
28
// Perhaps this should #ifdef _WIN32 instead?
29
29
_snprintf(hex, 3, "%x", c);
31
31
snprintf(hex, 3, "%x", c);
37
37
inline char hexToChar(const std::string& hex)
40
sscanf(hex.c_str(), "%x", &c);
44
/** Escape a string by converting certain characters to their hexadecimal
47
* @return The escaped message.
48
* @param prefix The string that is to be prepended to the hexadecimal value.
49
* @param special The characters that are to be escaped.
50
* @param message The message that is to be escaped.
53
inline const std::string hexEncode(const std::string& prefix,
54
const std::string& special, const std::string& message)
58
for (std::string::const_iterator i = message.begin();
59
i != message.end(); ++i)
61
if (std::find(special.begin(), special.end(), *i) != special.end())
64
encoded += charToHex(*i);
75
/** Parse a message and replace hexadecimal 'escaped' values with their ASCII
78
* This function does the opposite to hexDecode - it takes a message that was
79
* prepared with hexDecode, searches for occurences of prefix and replaces the
80
* following hexadecimal values with their ASCII counterparts.
82
* @return The unescaped string.
83
* @param prefix The string that is followed by the escaped characters
84
* @param message The escaped message.
86
inline const std::string hexDecode(const std::string& prefix,
87
const std::string& message)
89
std::string newMessage;
90
std::string curFragment;
92
for (size_t i = 0; i < message.size(); i++) {
93
if (std::equal(prefix.begin(),prefix.begin() + curFragment.length() + 1,
94
(curFragment + message[i]).begin())) {
95
curFragment += message[i];
97
newMessage += curFragment + message[i];
100
if (curFragment == prefix) {
104
newMessage += hexToChar(hex);
40
if (sscanf(hex.c_str(), "%x", &c) == 1) {
47
const std::string hexEncodeWithPrefix(const std::string& prefix,
48
const std::string& special,
49
const std::string& message);
51
const std::string hexDecodeWithPrefix(const std::string& prefix,
52
const std::string& message);
112
54
} } // namespace Atlas::Codecs
56
#endif // ATLAS_CODECS_UTILITY_H