Browse Source

some additional helpers

master
boB Rudis 3 weeks ago
parent
commit
dad7e73ab5
No known key found for this signature in database GPG Key ID: 1D7529BE14E2BBA9
3 changed files with 61 additions and 3 deletions
  1. +2
    -2
      DESCRIPTION
  2. +2
    -1
      R/swift-function.R
  3. +57
    -0
      inst/include/utils.swift

+ 2
- 2
DESCRIPTION View File

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


+ 2
- 1
R/swift-function.R View File

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

+ 57
- 0
inst/include/utils.swift View File

@ -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