Add URI-style escaping of filename characters.
[cumulus.git] / format.cc
1 /* LBS: An LFS-inspired filesystem backup system
2  * Copyright (C) 2007  Michael Vrable
3  *
4  * Utility functions for converting various datatypes to text format (and
5  * later, for parsing them back, perhaps).
6  */
7
8 #include <stdio.h>
9 #include <uuid/uuid.h>
10
11 #include <string>
12 #include <sstream>
13
14 using std::string;
15
16 /* Perform URI-style escaping of a string.  Bytes which cannot be represented
17  * directly are encoded in the form %xx (where "xx" is a string of two
18  * hexadecimal digits). */
19 string uri_encode(const string &in)
20 {
21     string out;
22
23     for (size_t i = 0; i < in.length(); i++) {
24         unsigned char c = in[i];
25
26         if (c > '%' && c <= 0x7f) {
27             out += c;
28         } else {
29             char buf[4];
30             sprintf(buf, "%%%02x", c);
31             out += buf;
32         }
33     }
34
35     return out;
36 }