]>
Commit | Line | Data |
---|---|---|
1b78aef5 DS |
1 | #include <string> |
2 | #include <vector> | |
72dbc915 FCE |
3 | #include <iostream> |
4 | #include <sstream> | |
5 | #include <stdexcept> | |
3f99432c | 6 | #include <cctype> |
1b78aef5 | 7 | |
72dbc915 | 8 | const char *get_home_directory(void); |
1b78aef5 | 9 | int copy_file(const char *src, const char *dest); |
1b78aef5 | 10 | int create_dir(const char *dir); |
1b78aef5 DS |
11 | void tokenize(const std::string& str, std::vector<std::string>& tokens, |
12 | const std::string& delimiters); | |
1b78aef5 | 13 | bool find_executable(const char *name, std::string& retpath); |
8c711d30 | 14 | const std::string cmdstr_quoted(const std::string& cmd); |
72dbc915 FCE |
15 | |
16 | ||
17 | // stringification generics | |
18 | ||
19 | ||
20 | template <typename T> | |
21 | inline std::string | |
22 | stringify(T t) | |
23 | { | |
24 | std::ostringstream s; | |
25 | s << t; | |
26 | return s.str (); | |
27 | } | |
28 | ||
29 | ||
30 | template <typename OUT, typename IN> | |
31 | inline OUT lex_cast(IN const & in) | |
32 | { | |
33 | std::stringstream ss; | |
34 | OUT out; | |
7e41d3dc | 35 | // NB: ss >> string out assumes that "in" renders to one word |
72dbc915 FCE |
36 | if (!(ss << in && ss >> out)) |
37 | throw std::runtime_error("bad lexical cast"); | |
38 | return out; | |
39 | } | |
40 | ||
41 | ||
42 | template <typename OUT, typename IN> | |
43 | inline OUT | |
44 | lex_cast_hex(IN const & in) | |
45 | { | |
46 | std::stringstream ss; | |
47 | OUT out; | |
7e41d3dc FCE |
48 | // NB: ss >> string out assumes that "in" renders to one word |
49 | if (!(ss << "0x" << std::hex << in && ss >> out)) | |
72dbc915 FCE |
50 | throw std::runtime_error("bad lexical cast"); |
51 | 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 | lex_cast_qstring(IN const & in) | |
60 | { | |
61 | std::stringstream ss; | |
62 | std::string out, out2; | |
63 | if (!(ss << in)) | |
64 | throw std::runtime_error("bad lexical cast"); | |
7e41d3dc | 65 | out = ss.str(); // "in" is expected to render to more than one word |
72dbc915 FCE |
66 | out2 += '"'; |
67 | for (unsigned i=0; i<out.length(); i++) | |
68 | { | |
3f99432c FCE |
69 | char c = out[i]; |
70 | if (! isprint(c)) | |
71 | { | |
72 | out2 += '\\'; | |
73 | // quick & dirty octal converter | |
74 | out2 += "01234567" [(c >> 6) & 0x07]; | |
75 | out2 += "01234567" [(c >> 3) & 0x07]; | |
76 | out2 += "01234567" [(c >> 0) & 0x07]; | |
77 | } | |
78 | else if (c == '"' || c == '\\') | |
79 | { | |
80 | out2 += '\\'; | |
81 | out2 += c; | |
82 | } | |
83 | else | |
84 | out2 += c; | |
72dbc915 FCE |
85 | } |
86 | out2 += '"'; | |
87 | return out2; | |
88 | } |