File: futures.R

package info (click to toggle)
r-cran-future 1.11.1.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 1,380 kB
  • sloc: sh: 14; makefile: 2
file content (76 lines) | stat: -rw-r--r-- 1,740 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#' Gets all futures in an object
#'
#' Gets all futures in an environment, a list, or a list environment
#' and returns an object of the same class (and dimensions).
#' Non-future elements are returned as is.
#'
#' @param x An environment, a list, or a list environment.
#' @param \dots Not used.
#'
#' @return An object of same type as \code{x} and with the same names
#' and/or dimensions, if set.
#'
#' @details
#' This function is useful for retrieve futures that were created via
#' future assignments (\code{\%<-\%}) and therefore stored as promises.
#' This function turns such promises into standard \code{Future}
#' objects.
#'
#' @export
futures <- function(x, ...) UseMethod("futures")

#' @export
futures.list <- function(x, ...) {
  x
}

#' @export
futures.environment <- function(x, ...) {
  fs <- futureOf(envir = x, mustExist = FALSE, drop = FALSE)

  ## Create object of same class as 'x'
  res <- new.env()
  for (key in names(fs)) {
    f <- fs[[key]]
    if (inherits(f, "Future")) {
      res[[key]] <- f
    } else {
      res[[key]] <- x[[key]]
    }
  }

  res
}

#' @export
#' @importFrom listenv listenv
futures.listenv <- function(x, ...) {
  fs <- futureOf(envir = x, mustExist = FALSE, drop = FALSE)

  ## Create object of same class as 'x'
  res <- listenv()
  length(res) <- length(fs)
  for (ii in seq_along(fs)) {
    f <- fs[[ii]]
    if (inherits(f, "Future")) {
      res[[ii]] <- f
    } else {
      value <- x[[ii]]
      if (is.null(value)) {
        res[ii] <- list(value)
      } else {
        res[[ii]] <- value
      }
    }
  }

  dim <- dim(x)
  if (!is.null(dim)) {
    dim(res) <- dim
    ## Preserve dimnames and names
    dimnames(res) <- dimnames(x)
  }
  names(res) <- names(x)

  res
}