From 8261c941c244f2f97a2fe8bf04bf40a5a4050674 Mon Sep 17 00:00:00 2001 From: Joe Groff Date: Wed, 12 Oct 2011 11:59:10 -0700 Subject: [PATCH] io: non-copying each-block and contents variants each-(stream-)block* is like each-block but takes a buffer object and reads into it repeatedly. (stream-)contents* determines the stream length then does a single stream-read-unsafe into a preallocated buffers. Both functions currently only work for byte-arrays (and contents* only for seekable streams), so they can't replace the non-starred versions completely just yet. --- core/io/io.factor | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/core/io/io.factor b/core/io/io.factor index 589790a551..6954c82469 100644 --- a/core/io/io.factor +++ b/core/io/io.factor @@ -1,6 +1,6 @@ ! Copyright (C) 2003, 2010 Slava Pestov. ! See http://factorcode.org/license.txt for BSD license. -USING: accessors byte-arrays combinators continuations destructors +USING: accessors alien byte-arrays combinators continuations destructors kernel math namespaces sequences sequences.private ; IN: io @@ -105,20 +105,39 @@ PRIVATE> input-stream get stream-lines ; inline : each-stream-block ( ... stream quot: ( ... block -- ... ) -- ... ) - swap 65536 swap [ stream-read-partial ] 2curry each-morsel ; inline + swap [ 65536 swap stream-read-partial ] curry each-morsel ; inline + +: each-stream-block* ( ... buffer stream quot: ( ... n ptr -- ... ) -- ... ) + -rot [ [ byte-length ] [ >c-ptr ] bi ] dip + [ [ stream-read-partial-unsafe ] curry keep ] 3curry each-morsel ; inline : each-block ( ... quot: ( ... block -- ... ) -- ... ) input-stream get swap each-stream-block ; inline +: each-block* ( ... quot: ( ... block -- ... ) -- ... ) + input-stream get swap each-stream-block* ; inline + : stream-contents ( stream -- seq ) [ [ [ ] collector [ each-stream-block ] dip { } like ] [ stream-element-exemplar concat-as ] bi ] with-disposal ; +: stream-contents-length ( stream -- n ) + [ stream-tell ] + [ [ 0 seek-end ] dip [ stream-seek ] [ stream-tell ] bi ] + [ [ swap seek-absolute ] dip stream-seek ] tri ; + +: stream-contents* ( stream -- seq ) + [ stream-contents-length dup (byte-array) ] + [ [ stream-read-unsafe drop ] curry keep ] bi ; + : contents ( -- seq ) input-stream get stream-contents ; inline +: contents* ( -- seq ) + input-stream get stream-contents* ; inline + : stream-copy ( in out -- ) [ [ [ write ] each-block ] with-output-stream ] curry with-input-stream ;