library(sodium)
library(bench)
inputs <- c(
random = bin2hex(random(32)),
valid = strrep("a", 64),
short = strrep("a", 32),
long = strrep("a", 66),
upper = strrep("A", 64),
bad_char = strrep("z", 64),
extra = paste0(strrep("a", 64), "zz"),
na = NA_character_
)
expected <- c(
random = TRUE,
valid = TRUE,
short = FALSE,
long = FALSE,
upper = TRUE,
bad_char = FALSE,
extra = FALSE,
na = FALSE
)
check <- function(method) {
stopifnot(identical(expected, method(inputs)))
}
method_hex2bin <- function(x) {
nchar(x) == 64 & vapply(x, function(x) {
bin <- sodium::hex2bin(x)
length(bin) == 32
}, logical(1))
}
method_grepl_1 <- function(x) {
out <- grepl("^[a-f0-9]{64}$", x, ignore.case = TRUE)
names(out) <- names(x)
out
}
method_grepl_2 <- function(x) {
out <- grepl("^[a-f0-9]{64}$", tolower(x))
names(out) <- names(x)
out
}
method_grepl_3 <- function(x) {
out <- grepl("^[A-Fa-f0-9]{64}$", x)
names(out) <- names(x)
out
}
method_setdiff <- function(x) {
y <- c(letters[1:6], 0:9, LETTERS[1:6])
nchar(x) == 64 & vapply(strsplit(inputs, "", fixed = TRUE), function(x) {
!length(setdiff(x, y))
}, logical(1))
}
method_str_detect_1 <- function(x) {
pattern <- stringr::regex("^[a-f0-9]{64}$", ignore_case = TRUE)
out <- stringr::str_detect(x, pattern)
out[is.na(out)] <- FALSE
names(out) <- names(x)
out
}
method_str_detect_2 <- function(x) {
pattern <- "^[a-f0-9]{64}$"
out <- stringr::str_detect(tolower(x), pattern)
out[is.na(out)] <- FALSE
names(out) <- names(x)
out
}
method_str_detect_3 <- function(x) {
pattern <- "^[A-Fa-f0-9]{64}$"
out <- stringr::str_detect(x, pattern)
out[is.na(out)] <- FALSE
names(out) <- names(x)
out
}
bnch <- bench::mark(
method_hex2bin(inputs),
method_grepl_1(inputs),
method_grepl_2(inputs),
method_grepl_3(inputs),
method_setdiff(inputs),
method_str_detect_1(inputs),
method_str_detect_2(inputs),
method_str_detect_3(inputs)
)
bnch
summary(bnch, relative = TRUE)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.