From 36557f3b5da8d85027f5156debd4aa7daecc4150 Mon Sep 17 00:00:00 2001 From: Thomas Lin Pedersen Date: Fri, 5 Jan 2024 08:47:42 +0100 Subject: [PATCH] backports of hashtable functionality --- R/collect_axes.R | 25 +++++++++++++++++++++++-- R/zzz.R | 12 +++++++----- 2 files changed, 30 insertions(+), 7 deletions(-) diff --git a/R/collect_axes.R b/R/collect_axes.R index 234064b..952e34b 100644 --- a/R/collect_axes.R +++ b/R/collect_axes.R @@ -284,6 +284,28 @@ grob_layout <- function(gt, idx) { new } +# Backports of hash table functionality +hashtab <- function(type, size) { + new_environment() +} +gethash <- function(h, key, nomatch = NULL) { + get0(hash(key), envir = h, ifnotfound = nomatch) +} +sethash <- function(h, key, value) { + assign(hash(key), value, envir = h) +} +on_load({ + if ("hashtab" %in% getNamespaceExports("utils")) { + hashtab <- utils::hashtab + } + if ("gethash" %in% getNamespaceExports("utils")) { + gethash <- utils::gethash + } + if ("sethash" %in% getNamespaceExports("utils")) { + sethash <- utils::sethash + } +}) + # 2D equivalent of run-length encoding. # Essentially, it tries to look for rectangular arrangements of cells in a # matrix that have the same values, and reports back their positions. @@ -307,7 +329,6 @@ grob_layout <- function(gt, idx) { # #> 2 1 2 3 3 2 # #> 5 3 3 1 2 3 # #> 6 3 3 3 3 1 -#' @importFrom utils hashtab gethash sethash rle_2d <- function(m, byrow = FALSE) { n <- length(m) @@ -413,7 +434,7 @@ rle_2d <- function(m, byrow = FALSE) { # Initialise hash table no longer than number of runs # Inspiration for using hash tables for this problem taken from TimTaylor: # https://fosstodon.org/@_TimTaylor/111266682218212785 - htab <- hashtab(size = length(values)) + htab <- hashtab("identical", size = length(values)) for (i in seq_along(values)) { diff --git a/R/zzz.R b/R/zzz.R index f29c083..0d0b3e7 100644 --- a/R/zzz.R +++ b/R/zzz.R @@ -1,3 +1,7 @@ +.onLoad <- function(...) { + run_on_load() +} + print_plot.patchwork <- function(p, title = '') { if (is.null(p$patches$annotation$title)) { p <- p + plot_annotation(title = title) @@ -5,11 +9,6 @@ print_plot.patchwork <- function(p, title = '') { print(p) } -.onLoad <- function(...) { - register_s3_method("vdiffr", "print_plot", "patchwork") - invisible() -} - register_s3_method <- function(pkg, generic, class, fun = NULL) { check_string(pkg) check_string(generic) @@ -33,3 +32,6 @@ register_s3_method <- function(pkg, generic, class, fun = NULL) { } ) } +on_load( + register_s3_method("vdiffr", "print_plot", "patchwork") +)