]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.scl.data/scl/Data/Binary.scl
Function to read and write bytes from streams
[simantics/platform.git] / bundles / org.simantics.scl.data / scl / Data / Binary.scl
1 import "Stream"
2
3 importJava "java.io.InputStream" where
4     """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."""
5     @JavaName read
6     readBytesM :: InputStream -> MVector Byte -> <Proc> Integer
7
8     """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."""
9     @JavaName read
10     readRangeOfBytesM :: InputStream -> MVector Byte -> Integer -> Integer -> <Proc> Integer
11
12 """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."""
13 readBytes :: InputStream -> Integer -> <Proc> Maybe (Vector Byte)
14 readBytes stream length = 
15     if count == (-1)
16     then Nothing
17     else if count == length
18     then Just (freezeMVector result)
19     else Just (take count (freezeMVector result)) 
20   where
21     result = createMVector length
22     count = readBytesM stream result 
23
24 importJava "java.io.OutputStream" where
25     """Writes given vector of bytes to output stream."""
26     @JavaName write
27     writeBytes :: OutputStream -> Vector Byte -> <Proc> ()
28
29     @JavaName write
30     writeBytesM :: OutputStream -> MVector Byte -> <Proc> ()
31     
32     """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."""
33     @JavaName write
34     writeRangeOfBytes :: OutputStream -> Vector Byte -> Integer -> Integer -> <Proc> ()
35     
36     @JavaName write
37     writeRangeOfBytesM :: OutputStream -> MVector Byte -> Integer -> Integer -> <Proc> ()
38     
39 """Copy all available bytes from output stream to input stream."""
40 copyAllBytes :: OutputStream -> InputStream -> <Proc> ()
41 copyAllBytes output input = loop ()
42   where
43     buffer = createMVector 4096
44     loop () = let count = readBytesM input buffer
45               in if count == (-1) 
46                  then ()
47                  else do
48                      writeRangeOfBytesM output buffer 0 count
49                      loop ()