AceUtils  0.1
Small and light Arduino utilties and libraries.
url_encoding.cpp
1 /*
2 MIT License
3 
4 Copyright (c) 2020 Brian T. Park
5 
6 Permission is hereby granted, free of charge, to any person obtaining a copy
7 of this software and associated documentation files (the "Software"), to deal
8 in the Software without restriction, including without limitation the rights
9 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 copies of the Software, and to permit persons to whom the Software is
11 furnished to do so, subject to the following conditions:
12 
13 The above copyright notice and this permission notice shall be included in all
14 copies or substantial portions of the Software.
15 
16 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 SOFTWARE.
23 */
24 
25 #include <Print.h>
26 #include "url_encoding.h"
27 
28 // Inspired by
29 // https://github.com/zenmanenergy/ESP8266-Arduino-Examples/blob/master/helloWorld_urlencoded/urlencode.ino.
30 // Rewritten to use MemPrint instead of String.
31 
32 namespace url_encoding {
33 
38 static void intToHex(char c, char& code0, char& code1) {
39  char c1 = (c & 0xf);
40  char c0 = (c >> 4) & 0xf;
41  code1 = (c1 > 9) ? c1 - 10 + 'A' : c1 + '0';
42  code0 = (c0 > 9) ? c0 - 10 + 'A' : c0 + '0';
43 }
44 
45 void formUrlEncode(Print& output, const char* str) {
46  while (true) {
47  char c = *str;
48  if (c == '\0') break;
49 
50  if (c == ' ') {
51  output.print('+');
52  } else if (isalnum(c)) {
53  output.print(c);
54  } else {
55  char code0;
56  char code1;
57  intToHex(c, code0, code1);
58  output.print('%');
59  output.print(code0);
60  output.print(code1);
61  }
62 
63  str++;
64  }
65 }
66 
68 static char hexToInt(char c) {
69  if (c >= '0' && c <= '9') {
70  return c - '0';
71  }
72  if (c >= 'a' && c <= 'f') {
73  return c - 'a' + 10;
74  }
75  if (c >= 'A' && c <= 'F') {
76  return c - 'A' + 10;
77  }
78  return 0;
79 }
80 
81 void formUrlDecode(Print& output, const char* str) {
82  while (true) {
83  char c = *str;
84  if (c == '\0') break;
85 
86  if (c == '+') {
87  c = ' ';
88  } else if (c == '%') {
89  // Convert %{hex} to character
90  str++;
91  char code0 = *str;
92  if (code0 == '\0') break;
93 
94  str++;
95  char code1 = *str;
96  if (code1 == '\0') break;
97 
98  c = (hexToInt(code0) << 4) | hexToInt(code1);
99  }
100  output.print(c);
101  str++;
102  }
103 }
104 
105 }