| 128 | } |
| 129 | |
| 130 | Result Encode(const char* src, char* dst, uint32_t dst_len, uint32_t* bytes_written) |
| 131 | { |
| 132 | assert(src != (const char*) dst); |
| 133 | assert(dst == 0 || dst_len > 0); |
| 134 | |
| 135 | uint32_t dst_left = dst == 0 ? 0 : dst_len - 1; // Make room for null termination |
| 136 | uint32_t dst_used = 0; |
| 137 | const char* s = src; |
| 138 | char* d = dst; |
| 139 | while (*s) |
| 140 | { |
| 141 | char c = *s; |
| 142 | if (IsUnreserved(c)) |
| 143 | { |
| 144 | if (dst == 0 || dst_left >= 1) |
| 145 | { |
| 146 | if (dst) |
| 147 | { |
| 148 | *d = c; |
| 149 | d++; |
| 150 | dst_left--; |
| 151 | } |
| 152 | s++; |
| 153 | dst_used++; |
| 154 | } |
| 155 | else |
| 156 | { |
| 157 | *d = '\0'; |
| 158 | return RESULT_TOO_SMALL_BUFFER; |
| 159 | } |
| 160 | } |
| 161 | else |
| 162 | { |
| 163 | if (dst == 0 || dst_left >= 3) |
| 164 | { |
| 165 | if (dst) |
| 166 | { |
| 167 | dmSnPrintf(d, 4, "%%%02X", c); |
| 168 | d += 3; |
| 169 | dst_left -= 3; |
| 170 | } |
| 171 | s++; |
| 172 | dst_used += 3; |
| 173 | } |
| 174 | else |
| 175 | { |
| 176 | *d = '\0'; |
| 177 | return RESULT_TOO_SMALL_BUFFER; |
| 178 | } |
| 179 | } |
| 180 | } |
| 181 | if (dst) |
| 182 | { |
| 183 | *d = '\0'; |
| 184 | } |
| 185 | if (bytes_written) |
| 186 | { |
| 187 | *bytes_written = dst_used + 1; |