From 8f175f31f102f4a492da231ac0e6ecc8da808248 Mon Sep 17 00:00:00 2001 From: Joe Cheng Date: Tue, 3 Sep 2024 15:35:36 -0700 Subject: [PATCH] Handle errors properly when `req_perform_connection(mode="text")` Fixes #532 --- R/req-perform-stream.R | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/R/req-perform-stream.R b/R/req-perform-stream.R index 96fceeba..2612c95c 100644 --- a/R/req-perform-stream.R +++ b/R/req-perform-stream.R @@ -329,11 +329,24 @@ as_round_function <- function(round = c("byte", "line"), } read_con <- function(con, buffer = 32 * 1024) { - bytes <- raw() - repeat { - new <- readBin(con, "raw", n = buffer) - if (length(new) == 0) break - bytes <- c(bytes, new) + if (identical(summary(con)$text, "text")) { + # The connection is in text mode; readBin will error. So we must read it as + # characters and then convert to bytes. + chars <- character() + repeat { + new <- readChar(con, nchars = buffer) + if (length(new) == 0) break + chars <- c(chars, new) + } + # TODO: Seems wrong that there's no mention of encodings here?? + bytes <- charToRaw(chars) + } else { + bytes <- raw() + repeat { + new <- readBin(con, "raw", n = buffer) + if (length(new) == 0) break + bytes <- c(bytes, new) + } } if (length(bytes) == 0) { NULL