Skip to content

Commit

Permalink
feat: Add example json_split in cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
MEO265 committed May 5, 2024
1 parent a77128c commit d91ba40
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 0 deletions.
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@ export(stop)
export(stopifnot)
export(warning)
export(with_loggit)
useDynLib(loggit2, .registration=TRUE)
3 changes: 3 additions & 0 deletions R/loggit.R
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
#' @useDynLib loggit2, .registration=TRUE
NULL

#' Log entries to file
#'
#' Log entries to a [ndjson](https://github.com/ndjson) log file, defined by [set_logfile()].
Expand Down
3 changes: 3 additions & 0 deletions src/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
*.o
*.so
*.dll
43 changes: 43 additions & 0 deletions src/split_json.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#include <R.h>
#include <Rinternals.h>
#include <vector>
#include <string>

extern "C" SEXP splitString(SEXP strSEXP) {
const char* str = CHAR(STRING_ELT(strSEXP, 0));
std::vector<std::string> result;
std::string token;
bool inQuotes = false;
int backslashCount = 0;

for (int i = 0; str[i] != '\0'; ++i) {
char ch = str[i];
if (ch == '\\' && !inQuotes) {
backslashCount++;
token += ch;
} else if (ch == '"' && (backslashCount % 2 == 0)) {
inQuotes = !inQuotes;
token += ch;
backslashCount = 0;
} else if ((ch == ',' || ch == ':') && !inQuotes) {
result.push_back(token);
token.clear();
backslashCount = 0;
} else {
token += ch;
backslashCount = 0;
}
}

if (!token.empty()) {
result.push_back(token);
}

SEXP ans = PROTECT(allocVector(STRSXP, result.size()));
for (size_t j = 0; j < result.size(); ++j) {
SET_STRING_ELT(ans, j, mkChar(result[j].c_str()));
}

UNPROTECT(1);
return ans;
}

0 comments on commit d91ba40

Please sign in to comment.