paleolimbot commented on code in PR #279:
URL: https://github.com/apache/arrow-nanoarrow/pull/279#discussion_r1300212953
##########
r/R/convert-array-stream.R:
##########
@@ -62,26 +68,52 @@ convert_array_stream <- function(array_stream, to = NULL,
size = NULL, n = Inf)
)
}
+ # Collect all batches into a list()
+ batches <- collect_array_stream(
+ array_stream,
+ n,
+ schema = schema,
+ validate = FALSE
+ )
+
+ # If there is exactly one batch, use convert_array()
+ if (length(batches) == 1L) {
+ return(.Call(nanoarrow_c_convert_array, batches[[1]], to))
+ }
+
+ # Otherwise, compute the final size, create another array stream,
+ # and call convert_array_stream() with a known size.
+ lengths <- vapply(
+ batches,
+ # Use custom accessor because array$length in a loop is slow
+ function(array) {
+ .Call(nanoarrow_c_array_proxy, array, NULL, FALSE)$length
+ },
+ double(1)
+ )
+ basic_stream <- .Call(nanoarrow_c_basic_array_stream, batches, schema, FALSE)
+ convert_array_stream(basic_stream, to = to, size = sum(lengths))
+}
+
+#' @rdname convert_array_stream
+#' @export
+collect_array_stream <- function(array_stream, n = Inf, schema = NULL,
+ validate = TRUE) {
+ stopifnot(
+ inherits(array_stream, "nanoarrow_array_stream")
+ )
+
+ if (is.null(schema)) {
+ schema <- .Call(nanoarrow_c_array_stream_get_schema, array_stream)
+ }
+
batches <- vector("list", 1024L)
n_batches <- 0L
get_next <- array_stream$get_next
- while (!is.null(array <- get_next(schema, validate = FALSE)) && (n_batches <
n)) {
+ while (!is.null(array <- get_next(schema, validate = validate)) &&
(n_batches < n)) {
Review Comment:
Done!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]