From e3ee31da93393a7338ebfbc71620d124eedea946 Mon Sep 17 00:00:00 2001 From: =?utf8?q?Hannu=20Niemist=C3=B6?= Date: Mon, 23 Apr 2018 15:02:59 +0300 Subject: [PATCH] Function to read and write bytes from streams Change-Id: I5aa133cbdda3acaf36ed4cb0d7175a7ec1e8caff --- .../scl/Data/Binary.scl | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 bundles/org.simantics.scl.data/scl/Data/Binary.scl 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 () -- 2.47.1