]> sourceware.org Git - systemtap.git/blame - util.h
2007-10-19 Masami Hiramatsu <mhiramat@redhat.com>
[systemtap.git] / util.h
CommitLineData
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 8const char *get_home_directory(void);
1b78aef5 9int copy_file(const char *src, const char *dest);
1b78aef5 10int create_dir(const char *dir);
1b78aef5
DS
11void tokenize(const std::string& str, std::vector<std::string>& tokens,
12 const std::string& delimiters);
1b78aef5 13bool find_executable(const char *name, std::string& retpath);
8c711d30 14const std::string cmdstr_quoted(const std::string& cmd);
72dbc915
FCE
15
16
17// stringification generics
18
19
20template <typename T>
21inline std::string
22stringify(T t)
23{
24 std::ostringstream s;
25 s << t;
26 return s.str ();
27}
28
29
30template <typename OUT, typename IN>
31inline 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
42template <typename OUT, typename IN>
43inline OUT
44lex_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.
57template <typename IN>
58inline std::string
59lex_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}
This page took 0.040601 seconds and 5 git commands to generate.