1 /* LBS: An LFS-inspired filesystem backup system
2 * Copyright (C) 2007 Michael Vrable
4 * Utility functions for converting various datatypes to text format (and
5 * later, for parsing them back, perhaps).
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)
27 for (size_t i = 0; i < in.length(); i++) {
28 unsigned char c = in[i];
30 if (c >= '+' && c < 0x7f && c != '@') {
34 sprintf(buf, "%%%02x", c);
42 /* Decoding of strings produced by uri_encode. */
43 string uri_decode(const string &in)
45 char *buf = new char[in.size() + 1];
47 const char *input = in.c_str();
50 while (*input != '\0') {
53 if (isxdigit(input[1]) && isxdigit(input[2])) {
57 *output++ = strtol(hexbuf, NULL, 16);
74 /* Return the string representation of an integer. Will try to produce output
75 * in decimal, hexadecimal, or octal according to base, though this is just
76 * advisory. For negative numbers, will always use decimal. */
77 string encode_int(long long n, int base)
81 if (n >= 0 && base == 16) {
82 sprintf(buf, "0x%llx", n);
86 if (n > 0 && base == 8) {
87 sprintf(buf, "0%llo", n);
91 sprintf(buf, "%lld", n);
95 /* Parse the string representation of an integer. Accepts decimal, octal, and
96 * hexadecimal, just as C would (recognizes the 0 and 0x prefixes). */
97 long long parse_int(const string &s)
99 return strtoll(s.c_str(), NULL, 0);