Permalink
Browse files

Added piped-input-stream function and test (see #57)

  • Loading branch information...
1 parent e2eb01f commit 965c1d64f9d8f0f0d771d25c8c7545f65d6fb247 @weavejester weavejester committed Mar 19, 2012
Showing with 30 additions and 0 deletions.
  1. +22 −0 ring-core/src/ring/util/io.clj
  2. +8 −0 ring-core/test/ring/util/test/io.clj
View
22 ring-core/src/ring/util/io.clj
@@ -0,0 +1,22 @@
+(ns ring.util.io
+ "Utility functions for I/O in Ring."
+ (:require [clojure.java.io :as io])
+ (:import [java.io PipedInputStream PipedOutputStream]))
+
+(defn piped-input-stream
+ "Create an input stream from a function that takes an output stream as its
+ argument. The function will be executed in a separate thread. The stream
+ will be automatically closed after the function finishes.
+
+ e.g. (piped-input-stream
+ (fn [ostream]
+ (spit ostream \"Hello\")))"
+ [func]
+ (let [input (PipedInputStream.)
+ output (PipedOutputStream.)]
+ (.connect input output)
+ (future
+ (try
+ (func output)
+ (finally (.close output))))
+ input))
View
8 ring-core/test/ring/util/test/io.clj
@@ -0,0 +1,8 @@
+(ns ring.util.test.io
+ (:use clojure.test
+ ring.util.io)
+ (:require [clojure.java.io :as io]))
+
+(deftest test-piped-input-stream
+ (let [stream (piped-input-stream #(spit % "Hello World"))]
+ (is (= (slurp stream) "Hello World"))))

0 comments on commit 965c1d6

Please sign in to comment.