Skip to content

Instantly share code, notes, and snippets.

@jeroen
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeroen/9edf97f873f17a4ce5d3 to your computer and use it in GitHub Desktop.
Save jeroen/9edf97f873f17a4ce5d3 to your computer and use it in GitHub Desktop.
Test encoding/recoding of strings in Rcpp
# UTF8 tests on Windows
# Using R 3.1.2 for win64 with LC_CTYPE=English_United States.1252
library(Rcpp)
# Part 1: simply echo a string
echo1src <- "#include <Rcpp.h>
// [[Rcpp::export]]
std::string echo1(std::string src){
return src;
}"
echo2src <- "#include <Rcpp.h>
// [[Rcpp::export]]
std::wstring echo2(std::wstring src){
return src;
}"
echo3src <- "#include <Rcpp.h>
// [[Rcpp::export]]
Rcpp::String echo3(Rcpp::String src){
return src;
}"
sourceCpp(code = echo1src)
sourceCpp(code = echo2src)
sourceCpp(code = echo3src)
x1 <- enc2native("Zürich")
x2 <- enc2utf8("Zürich")
x3 <- "東京"
echo1(x1) #OK
echo1(x2) #FAIL
echo1(x3) #FAIL
echo2(x1) #FAIL
echo2(x2) #FAIL
echo2(x3) #FAIL
echo3(x1) #OK
echo3(x2) #OK
echo3(x3) #ok
# Part 2: actually manipulating the string
replacesrc <- "#include <Rcpp.h>
// [[Rcpp::export]]
Rcpp::String replace_first( Rcpp::String z, Rcpp::String x, Rcpp::String y){
z.replace_first( x, y ) ;
return z ;
}"
sourceCpp(code = replacesrc)
replace_first(paste("I like", x1), x1, x3) #FAIL
replace_first(paste("I like", x2), x2, x3) #FAIL
replace_first(paste("I like", x3), x3, x2) #FAIL
replace_first(paste("I like", x3), x3, x1) #OK
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment