Turi Create  4.0
rcpp_serialization.hpp
1 /* Copyright © 2017 Apple Inc. All rights reserved.
2  *
3  * Use of this source code is governed by a BSD-3-clause license that can
4  * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
5  */
6 #ifndef RCPP_SERIALIZE_HPP
7 #define RCPP_SERIALIZE_HPP
8 
9 #undef HAVE_VISIBILITY_ATTRIBUTE
10 
11 #include <stdlib.h>
12 #include <string.h>
13 // most of functions used here are included from Rinternals.h
14 //#include <Rcpp.h>
15 
16 #include <RApiSerializeAPI.h>
17 
18 #include <boost/regex.hpp>
19 #include <boost/algorithm/string.hpp>
20 
21 // the serialization function from SEXP to std::string
22 inline std::string serializeToStr(SEXP object) {
23  // using R's C API, all SEXP objects will be serialized into a raw vector
24  Rcpp::RawVector val = serializeToRaw(object);
25 
26  // convert R raw vector into a std::string
27  std::string res;
28 
29  for (size_t i = 0; i < val.size(); i++) {
30  res = res + std::to_string(int(val[i])) + "\t";
31  }
32 
33  return res;
34 }
35 
36 // unserialize from the std::string
37 inline SEXP unserializeFromStr(std::string s) {
38  // parse the std::string into a raw vector
39  std::vector<std::string> strs;
40  boost::regex e("^\\d.+");
41  if (boost::regex_match(s, e)) {
42  boost::split(strs,s,boost::is_any_of("\t"));
43  }
44 
45  Rcpp::RawVector object(strs.size() - 1);
46 
47  for (size_t i = 0; i < strs.size() - 1; i++) {
48  object[i] = static_cast<unsigned char>(std::stoi(strs[i]));
49  }
50 
51  return unserializeFromRaw(object);
52 }
53 
54 #endif
void split(S &&input, T &&output1, T &&output2, FilterFn filterfn, size_t random_seed=std::time(NULL))
Definition: algorithm.hpp:293