Marshalling of R connections

# S3 method for connection
marshal(con, ...)

# S3 method for connection
marshallable(con, ...)

Arguments

con

A connection.

...

Not used.

Value

A marshalled object as described in marshal().

Limitations

Not all connections can be marshalled, specifically we:

  • cannot marshal connections stdin (0), stdout (1), and stderr (2)

  • can only marshal read-only connections

  • can only marshal unopened or seekable connections

Examples

tf <- tempfile()
cat(file = tf, letters, sep = "")

## Read-only connection
con <- file(tf, open = "rb")

bfr <- readChar(con, nchars = 4L)
print(bfr)  ## "abcd"
#> [1] "abcd"

## Marshal read-only connection, which records the
## current state, including the current file position.
con_ <- marshal(con)

## Unmarshal connection, which restores the state
## of the original connection, including the current
## file position
con2 <- unmarshal(con_)
stopifnot(
  all.equal(summary(con2), summary(con)),
  identical(seek(con2), seek(con))
)

bfr <- readChar(con, nchars = 4L)
print(bfr)
#> [1] "efgh"
bfr2 <- readChar(con2, nchars = 4L)
print(bfr2)
#> [1] "efgh"
stopifnot(identical(bfr2, bfr))

## Cleanup
close(con)
close(con2)
file.remove(tf)
#> [1] TRUE
con <- url("https://www.r-project.org")
print(con)
#> A connection with                                       
#> description "https://www.r-project.org"
#> class       "url-libcurl"              
#> mode        "r"                        
#> text        "text"                     
#> opened      "closed"                   
#> can read    "yes"                      
#> can write   "no"                       

## Marshal read-only connection, which records the
## current state, including the current file position.
con_ <- marshal(con)

## Unmarshal connection, which restores the state
## of the original connection
con2 <- unmarshal(con_)
print(con2)
#> A connection with                                       
#> description "https://www.r-project.org"
#> class       "url-libcurl"              
#> mode        "r"                        
#> text        "text"                     
#> opened      "closed"                   
#> can read    "yes"                      
#> can write   "no"                       

stopifnot(all.equal(summary(con2), summary(con)))

bfr <- readChar(con, nchars = 100L)
print(bfr)
#> [1] "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\">\n    <meta http-equiv=\"X-UA-Comp"
bfr2 <- readChar(con2, nchars = 100L)
print(bfr2)
#> [1] "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\">\n    <meta http-equiv=\"X-UA-Comp"
stopifnot(identical(bfr2, bfr))

## Cleanup
close(con)
close(con2)