Commits

Anonymous committed a3aa289

+ I.bytes

  • Participants
  • Parent commits e86b82c

Comments (0)

Files changed (2)

 ;
 
 
+value rec into_substring_step str ofs len =
+  if len = 0
+  then
+    ie_doneM ()
+  else
+    fun
+    [ Chunk c ->
+        let clen = S.length c in
+        if len < clen
+        then
+          let (to_blit, to_leave) = S.split_at len c in
+          ( S.to_substring to_blit str ofs len
+          ; ie_doneM () (Chunk to_leave)
+          )
+        else
+          ( S.to_substring c str ofs clen
+          ; ie_contM (into_substring_step str ofs len)
+          )
+    | EOF None -> IO.error End_of_file
+    | EOF (Some e) -> IO.error e
+    ]
+;
+
+value into_substring str ofs len : iteratee char unit =
+  IE_cont None (into_substring_step str ofs len)
+;
+
+(* +
+   [bytes sz] reads exactly [sz] bytes into new string.
+   [End_of_file] is thrown when input has less than [sz] bytes.
+ *)
+value bytes sz : iteratee char string =
+  prepend
+    (fun () -> String.make sz '\x00')
+    (fun res ->
+       into_substring res 0 sz >>= fun () ->
+       return res
+    )
+;
+
+
 end
 ;  (* `Make' functor *)
 
     s
 ;
 
-value rec to_string_loop arr str sub_ofs str_ofs left =
-  if left = 0
+value rec to_substring_loop ~arr ~str ~sub_ofs ~str_ofs ~len =
+  if len = 0
   then
-    str
+    ()
   else
     ( str.[str_ofs] := arr.(sub_ofs)
-    ; to_string_loop arr str (sub_ofs + 1) (str_ofs + 1) (left - 1)
+    ; to_substring_loop ~arr ~str ~sub_ofs:(sub_ofs + 1)
+        ~str_ofs:(str_ofs + 1) ~len:(len - 1)
     )
 ;
 
+value to_substring s str ofs len =
+  if ofs < 0 || len < 0 || ofs + len > String.length str
+  then invalid_arg "Subarray.to_substring: str/ofs/len"
+  else
+  if len > s.len
+  then invalid_arg "Subarray.to_substring: not enough elements in subarray"
+  else
+    to_substring_loop ~arr:s.arr ~str ~sub_ofs:s.ofs ~str_ofs:ofs ~len
+;
+
 value to_string s =
-  to_string_loop s.arr (String.make s.len '\x00') s.ofs 0 s.len
+  let str = String.make s.len '\x00'in
+  ( to_substring_loop ~arr:s.arr ~str ~sub_ofs:s.ofs ~str_ofs:0 ~len:s.len
+  ; str
+  )
 ;
 
 value append_to_list_rev s lst =