Skip to content

Commit

Permalink
move the R implementation of base64 encoding from knitr (yihui/knitr#324
Browse files Browse the repository at this point in the history
) to xfun
  • Loading branch information
yihui committed Jun 20, 2020
1 parent 51ac5d9 commit 564e6f4
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions R/base64.R
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,37 @@ base64_encode = function(x) {
.Call('base64_enc', x)
}

# an R implementation of base64 encoding by Wush Wu moved from knitr (of
# historic interest only): https://github.com/yihui/knitr/pull/324
base64_encode_r = function(raw.string) {
chars = c(LETTERS, letters, 0:9, '+', '/')
n = length(s <- as.integer(raw.string))
res = rep(NA, (n + 2) / 3 * 4)
i = 0L # index of res vector
j = 1L # index of base64_table
while (n > 2L) {
res[i <- i + 1L] = chars[s[j] %/% 4L + 1L]
res[i <- i + 1L] = chars[16 * (s[j] %% 4L) + s[j + 1L] %/% 16 + 1L]
res[i <- i + 1L] = chars[4L * (s[j + 1L] %% 16) + s[j + 2L] %/% 64L + 1L]
res[i <- i + 1L] = chars[s[j + 2L] %% 64L + 1L]
j = j + 3L
n = n - 3L
}
if (n) {
res[i <- i + 1L] = chars[s[j] %/% 4L + 1L]
if (n > 1L) {
res[i <- i + 1L] = chars[16 * (s[j] %% 4L) + s[j + 1L] %/% 16 + 1L]
res[i <- i + 1L] = chars[4L * (s[j + 1L] %% 16) + 1L]
res[i <- i + 1L] = '='
} else {
res[i <- i + 1L] = chars[16 * (s[j] %% 4L) + 1L]
res[i <- i + 1L] = '='
res[i <- i + 1L] = '='
}
}
paste(res[!is.na(res)], collapse = '')
}

#' Generate the Data URI for a file
#'
#' Encode the file in the base64 encoding, and add the media type. The data URI
Expand Down

0 comments on commit 564e6f4

Please sign in to comment.