home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 2 / Apprentice-Release2.iso / Tools / Languages / Caml Light 0.61 / Source / src / lib / fstring.ml < prev    next >
Encoding:
Text File  |  1993-09-24  |  1.9 KB  |  68 lines  |  [TEXT/MPS ]

  1. (* Operations on strings, without sanity checks *)
  2.  
  3. #open "int";;
  4. #open "eq";;
  5. #open "ref";;
  6. #open "fchar";;
  7.  
  8. let make_string len init =
  9.   let s = create_string len in
  10.     fill_string s 0 len init; s
  11. ;;
  12.  
  13. let prefix ^ s1 s2 =
  14.   let l1 = string_length s1
  15.   and l2 = string_length s2 in
  16.   let s = create_string (l1 + l2) in
  17.     blit_string s1 0 s 0 l1;
  18.     blit_string s2 0 s l1 l2;
  19.     s
  20. ;;
  21.  
  22. let sub_string s start len =
  23.   let res = create_string len in
  24.     blit_string s start res 0 len; res
  25. ;;
  26.  
  27. let replace_string dest src pos =
  28.   blit_string src 0 dest pos (string_length src)
  29. ;;
  30.  
  31. let string_for_read s =
  32.   let n = ref 0 in
  33.     for i = 0 to string_length s - 1 do
  34.       n := !n +
  35.         (match nth_char s i with
  36.            `"` | `\\` | `\n` | `\t` -> 2
  37.           | c -> if is_printable c then 1 else 4)
  38.     done;
  39.     if !n == string_length s then s else begin
  40.       let s' = create_string !n in
  41.         n := 0;
  42.         for i = 0 to string_length s - 1 do
  43.           begin
  44.             match nth_char s i with
  45.               `"` -> set_nth_char s' !n `\\`; incr n; set_nth_char s' !n `"`
  46.             | `\\` -> set_nth_char s' !n `\\`; incr n; set_nth_char s' !n `\\`
  47.             | `\n` -> set_nth_char s' !n `\\`; incr n; set_nth_char s' !n `n`
  48.             | `\t` -> set_nth_char s' !n `\\`; incr n; set_nth_char s' !n `t`
  49.             | c ->
  50.                 if is_printable c then
  51.                   set_nth_char s' !n c
  52.                 else begin
  53.                   let a = int_of_char c in
  54.                   set_nth_char s' !n `\\`;
  55.                   incr n;
  56.                   set_nth_char s' !n (char_of_int (48 + a / 100));
  57.                   incr n;
  58.                   set_nth_char s' !n (char_of_int (48 + (a / 10) mod 10));
  59.                   incr n;
  60.                   set_nth_char s' !n (char_of_int (48 + a mod 10))
  61.                 end
  62.           end;
  63.           incr n
  64.         done;
  65.         s'
  66.       end
  67. ;;
  68.