Wolodja Wentland <babi...@gmail.com> writes:

>> --8<---------------cut here---------------start------------->8---
>> (defn concat-input-stream
>>   "Gets one or many input streams and returns a new input stream that
>>   concatenates the given streams."
>>    ^java.io.InputStream [^java.io.InputStream is & more]
>>   (proxy [java.io.InputStream] []
>>     (read []
>>       (let [input (.read is)]
>>         (if (and (== -1 input) (seq more))
>>           (.read (apply concat-input-stream (first more) (rest more)))
>>           input)))))
>> 
>> (def mystream (concat-input-stream (java.io.ByteArrayInputStream. (.getBytes 
>> "ab"))
>>                                    (java.io.ByteArrayInputStream. (.getBytes 
>> "cd"))
>>                                    (java.io.ByteArrayInputStream. (.getBytes 
>> "ef"))))
>> 
>
> Great! I think that I would eventually run into the problems detailed
> in http://tech.puredanger.com/2011/08/12/subclassing-in-clojure/ but
> thanks a lot for this inspiration.

Hm, probably yes.  But you can implement the other arities quiet easily.
So that version also accepts the version that reads into a byte array.
The third version is left as an exercise for the reader. ;-)

--8<---------------cut here---------------start------------->8---
(defn concat-input-stream
  "Gets one or many input streams and returns a new input stream that
  concatenates the given streams."
  ^java.io.InputStream [^java.io.InputStream is & more]
  (proxy [java.io.InputStream] []
    (read
      ([]
         (let [input (.read is)]
           (if (and (== -1 input) (seq more))
             (.read (apply concat-input-stream (first more) (rest more)))
             input)))
      ([ary]
         (loop [i 0]
           (if (== i (alength ary))
             i
             (let [input (.read this)]
               (if (== -1 input)
                 i
                 (do
                   (clojure.core/aset ary i (byte input))
                   (recur (inc i)))))))))))

(def mystream (concat-input-stream (java.io.ByteArrayInputStream. (.getBytes 
"ab"))
                                   (java.io.ByteArrayInputStream. (.getBytes 
"cd"))
                                   (java.io.ByteArrayInputStream. (.getBytes 
"ef"))))

(let [ary (byte-array 6)
            retval (.read mystream ary)]
  (println (java.util.Arrays/toString ary))
  retval)
; [97, 98, 99, 100, 101, 102]
;=> 6
--8<---------------cut here---------------end--------------->8---

Bye,
Tassilo

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to