From: Hannu Niemistö Date: Mon, 23 Apr 2018 12:02:59 +0000 (+0300) Subject: Function to read and write bytes from streams X-Git-Tag: v1.43.0~136^2~489 X-Git-Url: https://gerrit.simantics.org/r/gitweb?a=commitdiff_plain;h=e3ee31da93393a7338ebfbc71620d124eedea946;p=simantics%2Fplatform.git Function to read and write bytes from streams Change-Id: I5aa133cbdda3acaf36ed4cb0d7175a7ec1e8caff --- diff --git a/bundles/org.simantics.scl.data/scl/Data/Binary.scl b/bundles/org.simantics.scl.data/scl/Data/Binary.scl new file mode 100644 index 000000000..382528a8c --- /dev/null +++ b/bundles/org.simantics.scl.data/scl/Data/Binary.scl @@ -0,0 +1,49 @@ +import "Stream" + +importJava "java.io.InputStream" where + """Reads bytes from the stream to a mutable vector. The maximum number of bytes read is the dimension of the vector. Returns the actual number of bytes read or -1, if the stream has finished.""" + @JavaName read + readBytesM :: InputStream -> MVector Byte -> Integer + + """Reads a range of bytes from the stream to a mutable vector. The first integer is the offset the second integer is the maximum length of the range. Returns the actual number of bytes read or -1, if the stream has finished.""" + @JavaName read + readRangeOfBytesM :: InputStream -> MVector Byte -> Integer -> Integer -> Integer + +"""Reads bytes from the stream. The integer parameter is the maximum number of bytes. Returns Nothing if stream has finished or a vector of bytes read.""" +readBytes :: InputStream -> Integer -> Maybe (Vector Byte) +readBytes stream length = + if count == (-1) + then Nothing + else if count == length + then Just (freezeMVector result) + else Just (take count (freezeMVector result)) + where + result = createMVector length + count = readBytesM stream result + +importJava "java.io.OutputStream" where + """Writes given vector of bytes to output stream.""" + @JavaName write + writeBytes :: OutputStream -> Vector Byte -> () + + @JavaName write + writeBytesM :: OutputStream -> MVector Byte -> () + + """Writes a range of bytes from the vector to output stream. The first integer is the offset the second integer is the length of the range.""" + @JavaName write + writeRangeOfBytes :: OutputStream -> Vector Byte -> Integer -> Integer -> () + + @JavaName write + writeRangeOfBytesM :: OutputStream -> MVector Byte -> Integer -> Integer -> () + +"""Copy all available bytes from output stream to input stream.""" +copyAllBytes :: OutputStream -> InputStream -> () +copyAllBytes output input = loop () + where + buffer = createMVector 4096 + loop () = let count = readBytesM input buffer + in if count == (-1) + then () + else do + writeRangeOfBytesM output buffer 0 count + loop ()