From 564e6f4d4357318e4abf25741f11325b67095ff8 Mon Sep 17 00:00:00 2001 From: Yihui Xie Date: Sat, 20 Jun 2020 16:50:21 -0500 Subject: [PATCH] move the R implementation of base64 encoding from knitr (https://github.com/yihui/knitr/pull/324) to xfun --- R/base64.R | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/R/base64.R b/R/base64.R index 06d3bcb..6016cbc 100644 --- a/R/base64.R +++ b/R/base64.R @@ -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