@@ -529,3 +529,69 @@ let add_substitute =
529529 }
530530 }
531531 // end | }]
532+
533+ let % expect_test " Bytes.trim" =
534+ let program =
535+ compile_and_parse_whole_program
536+ {|
537+ let is_space = function
538+ | ' ' | '\012' | '\n' | '\r' | '\t' -> true
539+ | _ -> false
540+
541+ let trim s =
542+ let open Bytes in
543+ let len = length s in
544+ let i = ref 0 in
545+ while ! i < len && is_space (unsafe_get s ! i) do
546+ incr i
547+ done ;
548+ let j = ref (len - 1 ) in
549+ while ! j > = ! i && is_space (unsafe_get s ! j) do
550+ decr j
551+ done ;
552+ if ! j > = ! i then
553+ sub s ! i (! j - ! i + 1 )
554+ else
555+ empty
556+
557+ let trim x = x |> Bytes. of_string |> trim |> Bytes. to_string
558+
559+ let () = print_endline (trim " " )
560+ let () = print_endline (trim " " )
561+ | }
562+ in
563+ print_fun_decl program (Some " trim" );
564+ [% expect
565+ {|
566+ function trim(x){
567+ var
568+ s$ 0 = copy(caml_bytes_of_string(x)),
569+ len = caml_ml_bytes_length(s$ 0 ),
570+ i = [0 , 0 ];
571+ for (;;){
572+ if (i[1 ] < len && is_space(caml_bytes_unsafe_get(s$ 0 , i[1 ]))){i[1 ]++ ; continue;}
573+ var j = [0 , len - 1 | 0 ];
574+ for (;;){
575+ if (i[1 ] > j[1 ]) break;
576+ if (! is_space(caml_bytes_unsafe_get(s$ 0 , j[1 ]))) break;
577+ j[1 ] += - 1 ;
578+ }
579+ a:
580+ {
581+ if (i[1 ] < = j[1 ]){
582+ var len$ 0 = (j[1 ] - i[1 ] | 0 ) + 1 | 0 , ofs = i[1 ];
583+ if
584+ (0 < = ofs && 0 < = len$ 0 && (caml_ml_bytes_length(s$ 0 ) - len$ 0 | 0 ) > = ofs){
585+ var r = caml_create_bytes(len$ 0 );
586+ caml_blit_bytes(s$ 0 , ofs, r, 0 , len$ 0 );
587+ var b = r;
588+ break a;
589+ }
590+ throw caml_maybe_attach_backtrace([0 , Invalid_argument , s], 1 );
591+ }
592+ var b = empty;
593+ }
594+ return caml_string_of_bytes(copy(b));
595+ }
596+ }
597+ // end | }]
0 commit comments