File: connection.R

package info (click to toggle)
r-cran-withr 3.0.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 620 kB
  • sloc: sh: 13; makefile: 2
file content (37 lines) | stat: -rw-r--r-- 973 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
#' Connections which close themselves
#'
#' R file connections which are automatically closed.
#'
#' @template with
#' @param con For `with_connection()` a named list with the connection(s) to
#' create. For `local_connection()` the code to create a single connection,
#' which is then returned.
#' @param .local_envir `[environment]`\cr The environment to use for scoping.
#' @examples
#' with_connection(list(con = file("foo", "w")), {
#'   writeLines(c("foo", "bar"), con)
#' })
#'
#' read_foo <- function() {
#'   readLines(local_connection(file("foo", "r")))
#' }
#' read_foo()
#'
#' unlink("foo")
#' @export
with_connection <- function(con, code) {

  stopifnot(all(is.named(con)))

  on.exit({
    for (connection in con) close(connection)
  })
  eval(substitute(code), envir = con, enclos = parent.frame())
}

#' @rdname with_connection
#' @export
local_connection <- function(con, .local_envir = parent.frame()) {
  defer(close(con), envir = .local_envir)
  con
}