Miscellaneous changes.
[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 <iostream>
12 #include <map>
13 #include <string>
14 #include <sstream>
15
16 using std::map;
17 using std::ostream;
18 using std::string;
19
20 /* Perform URI-style escaping of a string.  Bytes which cannot be represented
21  * directly are encoded in the form %xx (where "xx" is a string of two
22  * hexadecimal digits). */
23 string uri_encode(const string &in)
24 {
25     string out;
26
27     for (size_t i = 0; i < in.length(); i++) {
28         unsigned char c = in[i];
29
30         if (c > '%' && c <= 0x7f) {
31             out += c;
32         } else {
33             char buf[4];
34             sprintf(buf, "%%%02x", c);
35             out += buf;
36         }
37     }
38
39     return out;
40 }
41
42 /* Return the string representation of an integer. */
43 string encode_int(long long n)
44 {
45     char buf[64];
46     sprintf(buf, "%lld", n);
47     return buf;
48 }
49
50 /* Output a dictionary of string key/value pairs to the given output stream.
51  * The format is a sequence of lines of the form "key: value". */
52 void dict_output(ostream &o, map<string, string> dict)
53 {
54     for (map<string, string>::const_iterator i = dict.begin();
55          i != dict.end(); ++i) {
56         o << i->first << ": " << i->second << "\n";
57     }
58 }