Commits

Anonymous committed 1fb2ad7

Improve the normalize function and fix so it works even
when compiled with -unsafe.

  • Participants
  • Parent commits e08b060

Comments (0)

Files changed (1)

File cf/cf_message.ml

 type t = (string * int * int) list
 
 let sub_invariant_ (s, pos, len as sub) =
-    let _ = s.[pos] in
-    let _ = s.[pos + len - 1] in
-    len > 0
+    let size = String.length s in
+    pos >= 0 && pos < size && len > 0 && pos + len <= size
 
-let normalize = List.filter sub_invariant_
+let rec test_invariant_ = function
+    | [] -> true
+    | hd :: tl -> if sub_invariant_ hd then test_invariant_ tl else false
+
+let rec filter_for_invariant_ acc = function
+    | [] ->
+        List.rev acc
+    | hd :: tl ->
+        filter_for_invariant_ (if sub_invariant_ hd then hd :: acc else acc) tl
+
+let normalize m =
+    if test_invariant_ m then m else filter_for_invariant_ [] m
 
 let rec sub_blit_loop_ ?(i = 0) dest =
     function
     | [] ->
         ()
     | (s, pos, len as sub) :: tl ->
-        assert begin
-            try sub_invariant_ (dest, i, len)
-            with Invalid_argument _ -> false
-        end;
+        assert (sub_invariant_ (dest, i, len));
         String.blit s pos dest i len;
         let i = i + len in
         sub_blit_loop_ ~i dest tl
     end
 
 let to_seq m = unsafe_to_seq (normalize m)
-let to_seq2 m = unsafe_to_seq2 (normalize m)
+let to_seq2 m = unsafe_to_seq2 (normalize m)    
 
 (*--- End of File [ cf_message.ml ] ---*)