Debian Codegraph @

inst/include/sourcetools/r/RUtils.h

raw
1 #ifndef SOURCETOOLS_R_R_UTILS_H
2 #define SOURCETOOLS_R_R_UTILS_H
3
4 #include <vector>
5
6 #include <sourcetools/core/core.h>
7
8 #include <sourcetools/r/RHeaders.h>
9
10 namespace sourcetools {
11 namespace r {
12
13 class Protect : noncopyable
14 {
15 public:
16 Protect(): n_(0) {}
17 ~Protect() { UNPROTECT(n_); }
18
19 SEXP operator()(SEXP objectSEXP)
20 {
21 ++n_;
22 return PROTECT(objectSEXP);
23 }
24
25 private:
26 int n_;
27 };
28
29 class RObjectFactory : noncopyable
30 {
31 public:
32
33 RObjectFactory()
34 : n_(0)
35 {
36 }
37
38 template <typename T, typename F>
39 SEXP create(SEXPTYPE type, const std::vector<T>& vector, F f)
40 {
41 ++n_;
42 std::size_t n = vector.size();
43 SEXP resultSEXP = PROTECT(Rf_allocVector(type, n));
44 for (std::size_t i = 0; i < n; ++i)
45 f(resultSEXP, i, vector[i]);
46 return resultSEXP;
47 }
48
49 SEXP create(SEXPTYPE type, std::size_t n)
50 {
51 ++n_;
52 return PROTECT(Rf_allocVector(type, n));
53 }
54
55 ~RObjectFactory()
56 {
57 UNPROTECT(n_);
58 }
59
60 private:
61 std::size_t n_;
62 };
63
64 class ListBuilder : noncopyable
65 {
66 public:
67
68 void add(const std::string& name, SEXP value)
69 {
70 names_.push_back(name);
71 data_.push_back(protect_(value));
72 }
73
74 operator SEXP() const
75 {
76 std::size_t n = data_.size();
77
78 SEXP resultSEXP = protect_(Rf_allocVector(VECSXP, n));
79 SEXP namesSEXP = protect_(Rf_allocVector(STRSXP, n));
80
81 for (std::size_t i = 0; i < n; ++i)
82 {
83 SET_VECTOR_ELT(resultSEXP, i, data_[i]);
84 SET_STRING_ELT(namesSEXP, i, Rf_mkCharLen(names_[i].c_str(), names_[i].size()));
85 }
86
87 Rf_setAttrib(resultSEXP, R_NamesSymbol, namesSEXP);
88 return resultSEXP;
89 }
90
91 private:
92 std::vector<std::string> names_;
93 std::vector<SEXP> data_;
94 mutable Protect protect_;
95 };
96
97 } // namespace r
98 } // namespace sourcetools
99
100 #endif /* SOURCETOOLS_R_R_UTILS_H */