Debian Codegraph @

R/writer.R

raw
1 #' Lazy File Writer
2 #'
3 #' Generates a closure that writes binary (raw) data to a file.
4 #'
5 #' The writer function automatically opens the file on the first write and closes when
6 #' it goes out of scope, or explicitly by setting `close = TRUE`. This can be used
7 #' for the `data` callback in `multi_add()` or `curl_fetch_multi()` such
8 #' that we only keep open file handles for active downloads. This prevents running out
9 #' of file descriptors when performing thousands of concurrent requests.
10 #'
11 #' @export
12 #' @param path file name or path on disk
13 #' @param append open file in append mode
14 #' @return Function with signature `writer(data = raw(), close = FALSE)`
15 #' @examples
16 #' # Doesn't open yet
17 #' tmp <- tempfile()
18 #' writer <- file_writer(tmp)
19 #'
20 #' # Now it opens
21 #' writer(charToRaw("Hello!\n"))
22 #' writer(charToRaw("How are you?\n"))
23 #'
24 #' # Close it!
25 #' writer(charToRaw("All done!\n"), close = TRUE)
26 #'
27 #' # Check it worked
28 #' readLines(tmp)
29 file_writer <- function(path, append = FALSE){
30 path <- enc2native(normalizePath(path, mustWork = FALSE))
31 fp <- new_file_writer(path, append)
32 structure(function(data = raw(), close = FALSE){
33 stopifnot(is.raw(data))
34 write_file_writer(fp, data, as.logical(close))
35 }, class = "file_writer")
36 }
37
38 #' @useDynLib curl R_new_file_writer
39 new_file_writer <- function(path, append){
40 .Call(R_new_file_writer, list(path, append))
41 }
42
43 #' @useDynLib curl R_write_file_writer
44 write_file_writer <- function(fp, data, close){
45 .Call(R_write_file_writer, fp, data, close)
46 }
47
48 #' @useDynLib curl R_total_writers
49 total_writers <- function(){
50 .Call(R_total_writers)
51 }