blob: ee3f5bddccaadd2837c553cba44bd3511e3c14a6 [file] [log] [blame]
Alexander Afanasyevaf283d82014-01-03 13:23:34 -08001/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
2/**
3 * Copyright (C) 2013 Regents of the University of California.
4 * @author: Jeff Thompson <jefft0@remap.ucla.edu>
5 * See COPYING for copyright and distribution information.
6 */
7
8#ifndef NDN_STRING_HELPER_HPP
9#define NDN_STRING_HELPER_HPP
10
11#include <string>
12#include <sstream>
13
14namespace ndn {
15
16const char *WHITESPACE_CHARS = " \n\r\t";
17
18/**
19 * Modify str in place to erase whitespace on the left.
20 * @param str
21 */
22inline void
23trimLeft(std::string& str)
24{
25 size_t found = str.find_first_not_of(WHITESPACE_CHARS);
26 if (found != std::string::npos) {
27 if (found > 0)
28 str.erase(0, found);
29 }
30 else
31 // All whitespace
32 str.clear();
33}
34
35/**
36 * Modify str in place to erase whitespace on the right.
37 * @param str
38 */
39inline void
40trimRight(std::string& str)
41{
42 size_t found = str.find_last_not_of(WHITESPACE_CHARS);
43 if (found != std::string::npos) {
44 if (found + 1 < str.size())
45 str.erase(found + 1);
46 }
47 else
48 // All whitespace
49 str.clear();
50}
51
52/**
53 * Modify str in place to erase whitespace on the left and right.
54 * @param str
55 */
56inline void
57trim(std::string& str)
58{
59 trimLeft(str);
60 trimRight(str);
61}
62
63/**
64 * Convert the hex character to an integer from 0 to 15, or -1 if not a hex character.
65 * @param c
66 * @return
67 */
68inline int
69fromHexChar(uint8_t c)
70{
71 if (c >= '0' && c <= '9')
72 return (int)c - (int)'0';
73 else if (c >= 'A' && c <= 'F')
74 return (int)c - (int)'A' + 10;
75 else if (c >= 'a' && c <= 'f')
76 return (int)c - (int)'a' + 10;
77 else
78 return -1;
79}
80
81/**
82 * Return a copy of str, converting each escaped "%XX" to the char value.
83 * @param str
84 */
85inline std::string
86unescape(const std::string& str)
87{
88 std::ostringstream result;
89
90 for (size_t i = 0; i < str.size(); ++i) {
91 if (str[i] == '%' && i + 2 < str.size()) {
92 int hi = fromHexChar(str[i + 1]);
93 int lo = fromHexChar(str[i + 2]);
94
95 if (hi < 0 || lo < 0)
96 // Invalid hex characters, so just keep the escaped string.
97 result << str[i] << str[i + 1] << str[i + 2];
98 else
99 result << (uint8_t)(16 * hi + lo);
100
101 // Skip ahead past the escaped value.
102 i += 2;
103 }
104 else
105 // Just copy through.
106 result << str[i];
107 }
108
109 return result.str();
110}
111
112} // namespace ndn
113
114#endif // NDN_STRING_HELPER_HPP