1 : #include <string>
2 : #include <vector>
3 : #include <iostream>
4 : #include <sstream>
5 : #include <stdexcept>
6 : #include <cctype>
7 :
8 : const char *get_home_directory(void);
9 : int copy_file(const char *src, const char *dest);
10 : int create_dir(const char *dir);
11 : void tokenize(const std::string& str, std::vector<std::string>& tokens,
12 : const std::string& delimiters);
13 : bool find_executable(const char *name, std::string& retpath);
14 : const std::string cmdstr_quoted(const std::string& cmd);
15 :
16 :
17 : // stringification generics
18 :
19 :
20 : template <typename T>
21 : inline std::string
22 73342 : stringify(T t)
23 : {
24 73342 : std::ostringstream s;
25 73342 : s << t;
26 73342 : return s.str ();
27 : }
28 :
29 :
30 : template <typename OUT, typename IN>
31 2379064 : inline OUT lex_cast(IN const & in)
32 : {
33 2379064 : std::stringstream ss;
34 2379054 : OUT out;
35 : // NB: ss >> string out assumes that "in" renders to one word
36 2379064 : if (!(ss << in && ss >> out))
37 0 : throw std::runtime_error("bad lexical cast");
38 2379064 : return out;
39 : }
40 :
41 :
42 : template <typename OUT, typename IN>
43 : inline OUT
44 91 : lex_cast_hex(IN const & in)
45 : {
46 91 : std::stringstream ss;
47 91 : OUT out;
48 : // NB: ss >> string out assumes that "in" renders to one word
49 91 : if (!(ss << "0x" << std::hex << in && ss >> out))
50 0 : throw std::runtime_error("bad lexical cast");
51 91 : return out;
52 : }
53 :
54 :
55 : // Return as quoted string, so that when compiled as a C literal, it
56 : // would print to the user out nicely.
57 : template <typename IN>
58 : inline std::string
59 148850 : lex_cast_qstring(IN const & in)
60 : {
61 148850 : std::stringstream ss;
62 148850 : std::string out, out2;
63 148850 : if (!(ss << in))
64 0 : throw std::runtime_error("bad lexical cast");
65 148850 : out = ss.str(); // "in" is expected to render to more than one word
66 148850 : out2 += '"';
67 2283211 : for (unsigned i=0; i<out.length(); i++)
68 : {
69 2134361 : char c = out[i];
70 2134361 : if (! isprint(c))
71 : {
72 2 : out2 += '\\';
73 : // quick & dirty octal converter
74 2 : out2 += "01234567" [(c >> 6) & 0x07];
75 2 : out2 += "01234567" [(c >> 3) & 0x07];
76 2 : out2 += "01234567" [(c >> 0) & 0x07];
77 : }
78 2252655 : else if (c == '"' || c == '\\')
79 : {
80 118296 : out2 += '\\';
81 118296 : out2 += c;
82 : }
83 : else
84 2016063 : out2 += c;
85 : }
86 148850 : out2 += '"';
87 148850 : return out2;
88 : }
|