Browse Source

some additional helpers

master
boB Rudis 3 years ago
parent
commit
dad7e73ab5
No known key found for this signature in database GPG Key ID: 1D7529BE14E2BBA9
  1. 4
      DESCRIPTION
  2. 3
      R/swift-function.R
  3. 57
      inst/include/utils.swift

4
DESCRIPTION

@ -1,8 +1,8 @@
Package: swiftr Package: swiftr
Type: Package Type: Package
Title: Seamless R and Swift Integration Title: Seamless R and Swift Integration
Version: 0.1.0 Version: 0.2.0
Date: 2021-01-24 Date: 2021-04-14
Authors@R: c( Authors@R: c(
person("Bob", "Rudis", email = "bob@rud.is", role = c("aut", "cre"), person("Bob", "Rudis", email = "bob@rud.is", role = c("aut", "cre"),
comment = c(ORCID = "0000-0001-5670-2640")) comment = c(ORCID = "0000-0001-5670-2640"))

3
R/swift-function.R

@ -28,6 +28,7 @@ swift_function <- function(code, env = globalenv(), imports = c("Foundation"), c
writeLines( writeLines(
text = c( text = c(
sprintf("import %s", imports), sprintf("import %s", imports),
readLines(system.file("include", "utils.swift", package = "swiftr"), warn = FALSE),
code code
), ),
con = file.path(cache_dir, source_file) con = file.path(cache_dir, source_file)
@ -165,7 +166,7 @@ swift_function <- function(code, env = globalenv(), imports = c("Foundation"), c
message("SYNTAX ERROR") message("SYNTAX ERROR")
# cat(readLines(stderr)) invisible(readLines(stderr))
} }

57
inst/include/utils.swift

@ -0,0 +1,57 @@
extension SEXP {
var count: R_len_t {
Rf_length(self)
}
var typeOf: SEXPTYPE {
SEXPTYPE(TYPEOF(self))
}
var isSTRING: Bool {
self.typeOf == STRSXP
}
}
extension String {
init?(_ sexp: SEXP) {
if ((sexp != R_NilValue) && (Rf_length(sexp) == 1)) {
switch (TYPEOF(sexp)) {
case STRSXP: self = String(cString: R_CHAR(STRING_ELT(sexp, 0)))
default: return(nil)
}
} else {
return(nil)
}
}
}
extension Array where Element == String {
init?(_ sexp: SEXP) {
if (sexp.isSTRING) {
var val : [String] = [String]()
val.reserveCapacity(Int(sexp.count))
for idx in 0..<sexp.count {
val.append(String(cString: R_CHAR(STRING_ELT(sexp, R_xlen_t(idx)))))
}
self = val
} else {
return(nil)
}
}
var SEXP: SEXP? {
let charVec = Rf_protect(Rf_allocVector(SEXPTYPE(STRSXP), count))
defer { Rf_unprotect(1) }
for (idx, elem) in enumerated() { SET_STRING_ELT(charVec, idx, Rf_mkChar(elem)) }
return(charVec)
}
}
Loading…
Cancel
Save