text
stringlengths
12
786k
let link_archive output_fun currpos_fun file_name units_required = let inchan = open_in_bin file_name in try List . iter ( fun cu -> let name = file_name ^ " ( " ^ cu . cu_name ^ " ) " in try link_compunit output_fun currpos_fun inchan name cu with Symtable . Error msg -> raise ( Error ( Symbol_error ( name , msg ) ) ) ) units_required ; close_in inchan with x -> close_in inchan ; raise x
let link_file output_fun currpos_fun = function Link_object ( file_name , unit ) -> link_object output_fun currpos_fun file_name unit | Link_archive ( file_name , units ) -> link_archive output_fun currpos_fun file_name units
let output_debug_info oc = output_binary_int oc ( List . length ! debug_info ) ; List . iter ( fun ( ofs , evl , debug_dirs ) -> output_binary_int oc ofs ; output_value oc evl ; output_value oc debug_dirs ) ! debug_info ; debug_info := [ ]
let output_stringlist oc l = List . iter ( fun s -> output_string oc s ; output_byte oc 0 ) l
let make_absolute file = if not ( Filename . is_relative file ) then file else Location . rewrite_absolute_path ( Filename . concat ( Sys . getcwd ( ) ) file )
let link_bytecode ? final_name tolink exec_name standalone = let final_name = Option . value final_name ~ default : exec_name in List . iter ( function | Link_object ( file_name , _ ) when file_name = exec_name -> raise ( Error ( Wrong_object_name exec_name ) ) ; | _ -> ( ) ) tolink ; Misc . remove_file exec_name ; let outperm = if ! Clflags . with_runtime then 0o777 else 0o666 in let outchan = open_out_gen [ Open_wronly ; Open_trunc ; Open_creat ; Open_binary ] outperm exec_name in Misc . try_finally ~ always ( : fun ( ) -> close_out outchan ) ~ exceptionally ( : fun ( ) -> remove_file exec_name ) ( fun ( ) -> if standalone && ! Clflags . with_runtime then begin let header = if String . length ! Clflags . use_runtime > 0 then " camlheader_ur " else " camlheader " ^ ! Clflags . runtime_variant in try let inchan = open_in_bin ( Load_path . find header ) in copy_file inchan outchan ; close_in inchan with | Not_found -> raise ( Error ( File_not_found header ) ) | Sys_error msg -> raise ( Error ( Camlheader ( header , msg ) ) ) end ; Bytesections . init_record outchan ; if String . length ! Clflags . use_runtime > 0 && ! Clflags . with_runtime then begin let runtime = make_absolute ! Clflags . use_runtime in let runtime = if String . length runtime > 125 then " / bin / sh \ n \ exec " " \ ^ runtime ^ " " \ " \$ 0 " \ " " " \$@\ else runtime in output_string outchan runtime ; output_char outchan ' \ n ' ; Bytesections . record outchan " RNTM " end ; let start_code = pos_out outchan in Symtable . init ( ) ; clear_crc_interfaces ( ) ; let sharedobjs = List . map Dll . extract_dll_name ! Clflags . dllibs in let check_dlls = standalone && Config . target = Config . host in if check_dlls then begin Dll . init_compile ! Clflags . no_std_include ; Dll . add_path ( Load_path . get_paths ( ) ) ; try Dll . open_dlls Dll . For_checking sharedobjs with Failure reason -> raise ( Error ( Cannot_open_dll reason ) ) end ; let output_fun = output_bytes outchan and currpos_fun ( ) = pos_out outchan - start_code in List . iter ( link_file output_fun currpos_fun ) tolink ; if check_dlls then Dll . close_all_dlls ( ) ; output_byte outchan Opcodes . opSTOP ; output_byte outchan 0 ; output_byte outchan 0 ; output_byte outchan 0 ; Bytesections . record outchan " CODE " ; if standalone then begin output_stringlist outchan ! Clflags . dllpaths ; Bytesections . record outchan " DLPT " ; output_stringlist outchan sharedobjs ; Bytesections . record outchan " DLLS " end ; Symtable . output_primitive_names outchan ; Bytesections . record outchan " PRIM " ; Emitcode . marshal_to_channel_with_possibly_32bit_compat ~ filename : final_name ~ kind " : bytecode executable " outchan ( Symtable . initial_global_table ( ) ) ; Bytesections . record outchan " DATA " ; Symtable . output_global_map outchan ; Bytesections . record outchan " SYMB " ; output_value outchan ( extract_crc_interfaces ( ) ) ; Bytesections . record outchan " CRCS " ; if ! Clflags . debug then begin output_debug_info outchan ; Bytesections . record outchan " DBUG " end ; Bytesections . write_toc_and_trailer outchan ; )
let output_code_string_counter = ref 0
let output_code_string outchan code = let pos = ref 0 in let len = Bytes . length code in while ! pos < len do let c1 = Char . code ( Bytes . get code ! pos ) in let c2 = Char . code ( Bytes . get code ( ! pos + 1 ) ) in let c3 = Char . code ( Bytes . get code ( ! pos + 2 ) ) in let c4 = Char . code ( Bytes . get code ( ! pos + 3 ) ) in pos := ! pos + 4 ; Printf . fprintf outchan " 0x % 02x % 02x % 02x % 02x , " c4 c3 c2 c1 ; incr output_code_string_counter ; if ! output_code_string_counter >= 6 then begin output_char outchan ' \ n ' ; output_code_string_counter := 0 end done
let output_data_string outchan data = let counter = ref 0 in for i = 0 to String . length data - 1 do Printf . fprintf outchan " % d , " ( Char . code ( data . [ i ] ) ) ; incr counter ; if ! counter >= 12 then begin output_string outchan " \ n " ; counter := 0 end done
let output_cds_file outfile = Misc . remove_file outfile ; let outchan = open_out_gen [ Open_wronly ; Open_trunc ; Open_creat ; Open_binary ] 0o777 outfile in Misc . try_finally ~ always ( : fun ( ) -> close_out outchan ) ~ exceptionally ( : fun ( ) -> remove_file outfile ) ( fun ( ) -> Bytesections . init_record outchan ; Symtable . output_global_map outchan ; Bytesections . record outchan " SYMB " ; output_debug_info outchan ; Bytesections . record outchan " DBUG " ; Bytesections . write_toc_and_trailer outchan ; )
let link_bytecode_as_c tolink outfile with_main = let outchan = open_out outfile in Misc . try_finally ~ always ( : fun ( ) -> close_out outchan ) ~ exceptionally ( : fun ( ) -> remove_file outfile ) ( fun ( ) -> output_string outchan " \ \ n \ \ n # endif \ output_string outchan " static int caml_code [ ] = { \ n " ; Symtable . init ( ) ; clear_crc_interfaces ( ) ; let currpos = ref 0 in let output_fun code = output_code_string outchan code ; currpos := ! currpos + Bytes . length code and currpos_fun ( ) = ! currpos in List . iter ( link_file output_fun currpos_fun ) tolink ; Printf . fprintf outchan " \ n0x % x } ; \ n \ n " Opcodes . opSTOP ; output_string outchan " static char caml_data [ ] = { \ n " ; output_data_string outchan ( Marshal . to_string ( Symtable . initial_global_table ( ) ) [ ] ) ; output_string outchan " \ n } ; \ n \ n " ; let sections = [ " SYMB " , Symtable . data_global_map ( ) ; " PRIM " , Obj . repr ( Symtable . data_primitive_names ( ) ) ; " CRCS " , Obj . repr ( extract_crc_interfaces ( ) ) ] in output_string outchan " static char caml_sections [ ] = { \ n " ; output_data_string outchan ( Marshal . to_string sections [ ] ) ; output_string outchan " \ n } ; \ n \ n " ; Symtable . output_primitive_table outchan ; if with_main then begin output_string outchan " \ \ n # else \ \ n # endif \ \ n { \ \ n } \ n " end else begin output_string outchan " \ \ n { \ \ n } \ \ n \ \ n { \ \ n } \ \ n \ \ n { \ \ n } \ \ n \ \ n { \ \ n } \ n " end ; output_string outchan " \ \ n } \ \ n # endif \ n " ; ) ; if ! Clflags . debug then output_cds_file ( ( Filename . chop_extension outfile ) ^ " . cds " )
let build_custom_runtime prim_name exec_name = let runtime_lib = if not ! Clflags . with_runtime then " " else " - lcamlrun " ^ ! Clflags . runtime_variant in let debug_prefix_map = if Config . c_has_debug_prefix_map && not ! Clflags . keep_camlprimc_file then let flag = [ Printf . sprintf " - fdebug - prefix - map =% s = camlprim . c " prim_name ] in if Ccomp . linker_is_flexlink then " - link " :: flag else flag else [ ] in let exitcode = ( Clflags . std_include_flag " - I " ^ " " ^ Config . bytecomp_c_libraries ) in Ccomp . call_linker Ccomp . Exe exec_name ( debug_prefix_map @ [ prim_name ] @ List . rev ! Clflags . ccobjs @ [ runtime_lib ] ) exitcode = 0
let append_bytecode bytecode_name exec_name = let oc = open_out_gen [ Open_wronly ; Open_append ; Open_binary ] 0 exec_name in let ic = open_in_bin bytecode_name in copy_file ic oc ; close_in ic ; close_out oc
let fix_exec_name name = match Sys . os_type with " Win32 " | " Cygwin " -> if String . contains name ' . ' then name else name ^ " . exe " | _ -> name
let link objfiles output_name = let objfiles = match ! Clflags . nopervasives , ! Clflags . output_c_object , ! Clflags . output_complete_executable with | true , _ , _ -> objfiles | false , true , false -> " stdlib . cma " :: objfiles | _ -> " stdlib . cma " :: objfiles @ [ " std_exit . cmo " ] in let tolink = List . fold_right scan_file objfiles [ ] in let missing_modules = Ident . Map . filter ( fun id _ -> not ( Ident . is_predef id ) ) ! missing_globals in begin match Ident . Map . bindings missing_modules with | [ ] -> ( ) | ( id , cu_name ) :: _ -> raise ( Error ( Required_module_unavailable ( Ident . name id , cu_name ) ) ) end ; Clflags . ccobjs := ! Clflags . ccobjs @ ! lib_ccobjs ; Clflags . all_ccopts := ! lib_ccopts @ ! Clflags . all_ccopts ; Clflags . dllibs := ! lib_dllibs @ ! Clflags . dllibs ; if not ! Clflags . custom_runtime then link_bytecode tolink output_name true else if not ! Clflags . output_c_object then begin let bytecode_name = Filename . temp_file " camlcode " " " in let prim_name = if ! Clflags . keep_camlprimc_file then output_name ^ " . camlprim . c " else Filename . temp_file " camlprim " " . c " in Misc . try_finally ~ always ( : fun ( ) -> remove_file bytecode_name ; if not ! Clflags . keep_camlprimc_file then remove_file prim_name ) ( fun ( ) -> link_bytecode ~ final_name : output_name tolink bytecode_name false ; let poc = open_out prim_name in output_string poc " \ # ifdef __cplusplus \ n \ extern " \ C " \ { \ n \ # endif \ n \ # ifdef _WIN64 \ n \ # ifdef __MINGW32__ \ n \ typedef long long value ; \ n \ # else \ n \ typedef __int64 value ; \ n \ # endif \ n \ # else \ n \ typedef long value ; \ n \ # endif \ n " ; Symtable . output_primitive_table poc ; output_string poc " \ # ifdef __cplusplus \ n \ } \ n \ # endif \ n " ; close_out poc ; let exec_name = fix_exec_name output_name in if not ( build_custom_runtime prim_name exec_name ) then raise ( Error Custom_runtime ) ; if not ! Clflags . make_runtime then append_bytecode bytecode_name exec_name ) end else begin let basename = Filename . remove_extension output_name in let c_file , stable_name = if ! Clflags . output_complete_object && not ( Filename . check_suffix output_name " . c " ) then Filename . temp_file " camlobj " " . c " , Some " camlobj . c " else begin let f = basename ^ " . c " in if Sys . file_exists f then raise ( Error ( File_exists f ) ) ; f , None end in let obj_file = if ! Clflags . output_complete_object then ( Filename . chop_extension c_file ) ^ Config . ext_obj else basename ^ Config . ext_obj in let temps = ref [ ] in Misc . try_finally ~ always ( : fun ( ) -> List . iter remove_file ! temps ) ( fun ( ) -> link_bytecode_as_c tolink c_file ! Clflags . output_complete_executable ; if ! Clflags . output_complete_executable then begin temps := c_file :: ! temps ; if not ( build_custom_runtime c_file output_name ) then raise ( Error Custom_runtime ) end else if not ( Filename . check_suffix output_name " . c " ) then begin temps := c_file :: ! temps ; if Ccomp . compile_file ~ output : obj_file ? stable_name c_file <> 0 then raise ( Error Custom_runtime ) ; if not ( Filename . check_suffix output_name Config . ext_obj ) || ! Clflags . output_complete_object then begin temps := obj_file :: ! temps ; let mode , c_libs = if Filename . check_suffix output_name Config . ext_obj then Ccomp . Partial , " " else Ccomp . MainDll , Config . bytecomp_c_libraries in if not ( let runtime_lib = if not ! Clflags . with_runtime then " " else " - lcamlrun " ^ ! Clflags . runtime_variant in Ccomp . call_linker mode output_name ( [ obj_file ] @ List . rev ! Clflags . ccobjs @ [ runtime_lib ] ) c_libs = 0 ) then raise ( Error Custom_runtime ) ; end end ; ) end
let report_error ppf = function | File_not_found name -> fprintf ppf " Cannot find file % a " Location . print_filename name | Not_an_object_file name -> fprintf ppf " The file % a is not a bytecode object file " Location . print_filename name | Wrong_object_name name -> fprintf ppf " The output file % s has the wrong name . The extension implies \ \ an object file but the link step was requested " name | Symbol_error ( name , err ) -> fprintf ppf " Error while linking % a :@ % a " Location . print_filename name Symtable . report_error err | Inconsistent_import ( intf , file1 , file2 ) -> fprintf ppf " [ @< hov > Files % a @ and % a @ \ make inconsistent assumptions over interface % s ] " @ Location . print_filename file1 Location . print_filename file2 intf | Custom_runtime -> fprintf ppf " Error while building custom runtime system " | File_exists file -> fprintf ppf " Cannot overwrite existing file % a " Location . print_filename file | Cannot_open_dll file -> fprintf ppf " Error on dynamically loaded library : % a " Location . print_filename file | Required_module_unavailable ( s , m ) -> fprintf ppf " Module ` % s ' is unavailable ( required by ` % s ' ) " s m | Camlheader ( msg , header ) -> fprintf ppf " System error while copying file % s : % s " header msg
let ( ) = Location . register_error_of_exn ( function | Error err -> Some ( Location . error_of_printer_file report_error err ) | _ -> None )
let reset ( ) = lib_ccobjs := [ ] ; lib_ccopts := [ ] ; lib_dllibs := [ ] ; missing_globals := Ident . Map . empty ; Consistbl . clear crc_interfaces ; implementations_defined := [ ] ; debug_info := [ ] ; output_code_string_counter := 0
type error = Forward_reference of string * Ident . t | Multiple_definition of string * Ident . t | Not_an_object_file of string | Illegal_renaming of string * string * string | File_not_found of string
let relocs = ref ( [ ] : ( reloc_info * int ) list )
let events = ref ( [ ] : debug_event list )
let debug_dirs = ref String . Set . empty
let primitives = ref ( [ ] : string list )
let force_link = ref false
let rename_relocation packagename objfile mapping defined base ( rel , ofs ) = let rel ' = match rel with Reloc_getglobal id -> begin try let id ' = List . assoc id mapping in if List . mem id defined then Reloc_getglobal id ' else raise ( Error ( Forward_reference ( objfile , id ) ) ) with Not_found -> let name = Ident . name id in if String . contains name ' . ' then Reloc_getglobal ( Ident . create_persistent ( packagename ^ " . " ^ name ) ) else rel end | Reloc_setglobal id -> begin try let id ' = List . assoc id mapping in if List . mem id defined then raise ( Error ( Multiple_definition ( objfile , id ) ) ) else Reloc_setglobal id ' with Not_found -> let name = Ident . name id in if String . contains name ' . ' then Reloc_setglobal ( Ident . create_persistent ( packagename ^ " . " ^ name ) ) else rel end | _ -> rel in relocs := ( rel ' , base + ofs ) :: ! relocs
let relocate_debug base prefix subst ev = let ev ' = { ev with ev_pos = base + ev . ev_pos ; ev_module = prefix ^ " . " ^ ev . ev_module ; ev_typsubst = Subst . compose ev . ev_typsubst subst } in events := ev ' :: ! events
type pack_member_kind = PM_intf | PM_impl of compilation_unit
type pack_member = { pm_file : string ; pm_name : string ; pm_kind : pack_member_kind }
let read_member_info file = ( let name = String . capitalize_ascii ( Filename . basename ( chop_extensions file ) ) in let kind = if Filename . check_suffix file " . cmi " then PM_intf else begin let ic = open_in_bin file in try let buffer = really_input_string ic ( String . length Config . cmo_magic_number ) in if buffer <> Config . cmo_magic_number then raise ( Error ( Not_an_object_file file ) ) ; let compunit_pos = input_binary_int ic in seek_in ic compunit_pos ; let compunit = ( input_value ic : compilation_unit ) in if compunit . cu_name <> name then raise ( Error ( Illegal_renaming ( name , file , compunit . cu_name ) ) ) ; close_in ic ; PM_impl compunit with x -> close_in ic ; raise x end in { pm_file = file ; pm_name = name ; pm_kind = kind } )
let rename_append_bytecode packagename oc mapping defined ofs prefix subst objfile compunit = let ic = open_in_bin objfile in try Bytelink . check_consistency objfile compunit ; List . iter ( rename_relocation packagename objfile mapping defined ofs ) compunit . cu_reloc ; primitives := compunit . cu_primitives @ ! primitives ; if compunit . cu_force_link then force_link := true ; seek_in ic compunit . cu_pos ; Misc . copy_file_chunk ic oc compunit . cu_codesize ; if ! Clflags . debug && compunit . cu_debug > 0 then begin seek_in ic compunit . cu_debug ; List . iter ( relocate_debug ofs prefix subst ) ( input_value ic ) ; debug_dirs := List . fold_left ( fun s e -> String . Set . add e s ) ! debug_dirs ( input_value ic ) ; end ; close_in ic ; compunit . cu_codesize with x -> close_in ic ; raise x
let rec rename_append_bytecode_list packagename oc mapping defined ofs prefix subst = function [ ] -> ofs | m :: rem -> match m . pm_kind with | PM_intf -> rename_append_bytecode_list packagename oc mapping defined ofs prefix subst rem | PM_impl compunit -> let size = rename_append_bytecode packagename oc mapping defined ofs prefix subst m . pm_file compunit in let id = Ident . create_persistent m . pm_name in let root = Path . Pident ( Ident . create_persistent prefix ) in rename_append_bytecode_list packagename oc mapping ( id :: defined ) ( ofs + size ) prefix ( Subst . add_module id ( Path . Pdot ( root , Ident . name id ) ) subst ) rem
let build_global_target ~ ppf_dump oc target_name members mapping pos coercion = let components = List . map2 ( fun m ( _id1 , id2 ) -> match m . pm_kind with | PM_intf -> None | PM_impl _ -> Some id2 ) members mapping in let lam = Translmod . transl_package components ( Ident . create_persistent target_name ) coercion in let lam = Simplif . simplify_lambda lam in if ! Clflags . dump_lambda then Format . fprintf ppf_dump " % a . " @ Printlambda . lambda lam ; let instrs = Bytegen . compile_implementation target_name lam in let rel = Emitcode . to_packed_file oc instrs in relocs := List . map ( fun ( r , ofs ) -> ( r , pos + ofs ) ) rel @ ! relocs
let package_object_files ~ ppf_dump files targetfile targetname coercion = let members = map_left_right read_member_info files in let required_globals = List . fold_right ( fun compunit required_globals -> match compunit with | { pm_kind = PM_intf } -> required_globals | { pm_kind = PM_impl { cu_required_globals ; cu_reloc } } -> let remove_required ( rel , _pos ) required_globals = match rel with Reloc_setglobal id -> Ident . Set . remove id required_globals | _ -> required_globals in let required_globals = List . fold_right remove_required cu_reloc required_globals in List . fold_right Ident . Set . add cu_required_globals required_globals ) members Ident . Set . empty in let unit_names = List . map ( fun m -> m . pm_name ) members in let mapping = List . map ( fun name -> ( Ident . create_persistent name , Ident . create_persistent ( targetname ^ " . " ^ name ) ) ) unit_names in let oc = open_out_bin targetfile in try output_string oc Config . cmo_magic_number ; let pos_depl = pos_out oc in output_binary_int oc 0 ; let pos_code = pos_out oc in let ofs = rename_append_bytecode_list targetname oc mapping [ ] 0 targetname Subst . identity members in build_global_target ~ ppf_dump oc targetname members mapping ofs coercion ; let pos_debug = pos_out oc in if ! Clflags . debug && ! events <> [ ] then begin output_value oc ( List . rev ! events ) ; output_value oc ( String . Set . elements ! debug_dirs ) ; end ; let pos_final = pos_out oc in let imports = List . filter ( fun ( name , _crc ) -> not ( List . mem name unit_names ) ) ( Bytelink . extract_crc_interfaces ( ) ) in let compunit = { cu_name = targetname ; cu_pos = pos_code ; cu_codesize = pos_debug - pos_code ; cu_reloc = List . rev ! relocs ; cu_imports = ( targetname , Some ( Env . crc_of_unit targetname ) ) :: imports ; cu_primitives = ! primitives ; cu_required_globals = Ident . Set . elements required_globals ; cu_force_link = ! force_link ; cu_debug = if pos_final > pos_debug then pos_debug else 0 ; cu_debugsize = pos_final - pos_debug } in Emitcode . marshal_to_channel_with_possibly_32bit_compat ~ filename : targetfile ~ kind " : bytecode unit " oc compunit ; seek_out oc pos_depl ; output_binary_int oc pos_final ; close_out oc with x -> close_out oc ; raise x
let package_files ~ ppf_dump initial_env files targetfile = let files = List . map ( fun f -> try Load_path . find f with Not_found -> raise ( Error ( File_not_found f ) ) ) files in let prefix = chop_extensions targetfile in let targetcmi = prefix ^ " . cmi " in let targetname = String . capitalize_ascii ( Filename . basename prefix ) in Misc . try_finally ( fun ( ) -> let coercion = Typemod . package_units initial_env files targetcmi targetname in package_object_files ~ ppf_dump files targetfile targetname coercion ) ~ exceptionally ( : fun ( ) -> remove_file targetfile )
let report_error ppf = function Forward_reference ( file , ident ) -> fprintf ppf " Forward reference to % s in file % a " ( Ident . name ident ) Location . print_filename file | Multiple_definition ( file , ident ) -> fprintf ppf " File % a redefines % s " Location . print_filename file ( Ident . name ident ) | Not_an_object_file file -> fprintf ppf " % a is not a bytecode object file " Location . print_filename file | Illegal_renaming ( name , file , id ) -> fprintf ppf " Wrong file naming : % a @ contains the code for \ @ % s when % s was expected " Location . print_filename file name id | File_not_found file -> fprintf ppf " File % s not found " file
let ( ) = Location . register_error_of_exn ( function | Error err -> Some ( Location . error_of_printer_file report_error err ) | _ -> None )
let reset ( ) = relocs := [ ] ; events := [ ] ; primitives := [ ] ; force_link := false
[ @@@ ocaml . flambda_o3 ] = " caml_fill_bytes " [ @@ noalloc ] = " caml_blit_bytes " [ @@ noalloc ] = " caml_blit_string " [ @@ noalloc ]
let make n c = let s = create n in unsafe_fill s 0 n c ; s
let init n f = let s = create n in for i = 0 to n - 1 do unsafe_set s i ( f i ) done ; s
let empty = create 0
let copy s = let len = length s in let r = create len in unsafe_blit s 0 r 0 len ; r
let to_string b = unsafe_to_string ( copy b )
let of_string s = copy ( unsafe_of_string s )
let sub s ofs len = if ofs < 0 || len < 0 || ofs > length s - len then invalid_arg " String . sub / Bytes . sub " else begin let r = create len in unsafe_blit s ofs r 0 len ; r end
let sub_string b ofs len = unsafe_to_string ( sub b ofs len )
let ( ) ++ a b = let c = a + b in match a < 0 , b < 0 , c < 0 with | true , true , false | false , false , true -> invalid_arg " Bytes . extend " | _ -> c
let extend s left right = let len = length s ++ left ++ right in let r = create len in let ( srcoff , dstoff ) = if left < 0 then - left , 0 else 0 , left in let cpylen = min ( length s - srcoff ) ( len - dstoff ) in if cpylen > 0 then unsafe_blit s srcoff r dstoff cpylen ; r
let fill s ofs len c = if ofs < 0 || len < 0 || ofs > length s - len then invalid_arg " String . fill / Bytes . fill " else unsafe_fill s ofs len c
let blit s1 ofs1 s2 ofs2 len = if len < 0 || ofs1 < 0 || ofs1 > length s1 - len || ofs2 < 0 || ofs2 > length s2 - len then invalid_arg " Bytes . blit " else unsafe_blit s1 ofs1 s2 ofs2 len
let blit_string s1 ofs1 s2 ofs2 len = if len < 0 || ofs1 < 0 || ofs1 > string_length s1 - len || ofs2 < 0 || ofs2 > length s2 - len then invalid_arg " String . blit / Bytes . blit_string " else unsafe_blit_string s1 ofs1 s2 ofs2 len
let iter f a = for i = 0 to length a - 1 do f ( unsafe_get a i ) done
let iteri f a = for i = 0 to length a - 1 do f i ( unsafe_get a i ) done
let ensure_ge ( x : int ) y = if x >= y then x else invalid_arg " Bytes . concat "
let rec sum_lengths acc seplen = function | [ ] -> acc | hd :: [ ] -> length hd + acc | hd :: tl -> sum_lengths ( ensure_ge ( length hd + seplen + acc ) acc ) seplen tl
let rec unsafe_blits dst pos sep seplen = function [ ] -> dst | hd :: [ ] -> unsafe_blit hd 0 dst pos ( length hd ) ; dst | hd :: tl -> unsafe_blit hd 0 dst pos ( length hd ) ; unsafe_blit sep 0 dst ( pos + length hd ) seplen ; unsafe_blits dst ( pos + length hd + seplen ) sep seplen tl
let concat sep = function [ ] -> empty | l -> let seplen = length sep in unsafe_blits ( create ( sum_lengths 0 seplen l ) ) 0 sep seplen l
let cat s1 s2 = let l1 = length s1 in let l2 = length s2 in let r = create ( l1 + l2 ) in unsafe_blit s1 0 r 0 l1 ; unsafe_blit s2 0 r l1 l2 ; r
let is_space = function | ' ' | ' \ 012 ' | ' \ n ' | ' \ r ' | ' \ t ' -> true | _ -> false
let trim s = let len = length s in let i = ref 0 in while ! i < len && is_space ( unsafe_get s ! i ) do incr i done ; let j = ref ( len - 1 ) in while ! j >= ! i && is_space ( unsafe_get s ! j ) do decr j done ; if ! j >= ! i then sub s ! i ( ! j - ! i + 1 ) else empty
let escaped s = let n = ref 0 in for i = 0 to length s - 1 do n := ! n + ( match unsafe_get s i with | ' " ' \ | ' ' \\ | ' \ n ' | ' \ t ' | ' \ r ' | ' \ b ' -> 2 | ' ' . . ' ' ~ -> 1 | _ -> 4 ) done ; if ! n = length s then copy s else begin let s ' = create ! n in n := 0 ; for i = 0 to length s - 1 do begin match unsafe_get s i with | ( ' " ' \ | ' ' ) \\ as c -> unsafe_set s ' ! n ' ' ; \\ incr n ; unsafe_set s ' ! n c | ' \ n ' -> unsafe_set s ' ! n ' ' ; \\ incr n ; unsafe_set s ' ! n ' n ' | ' \ t ' -> unsafe_set s ' ! n ' ' ; \\ incr n ; unsafe_set s ' ! n ' t ' | ' \ r ' -> unsafe_set s ' ! n ' ' ; \\ incr n ; unsafe_set s ' ! n ' r ' | ' \ b ' -> unsafe_set s ' ! n ' ' ; \\ incr n ; unsafe_set s ' ! n ' b ' | ( ' ' . . ' ' ) ~ as c -> unsafe_set s ' ! n c | c -> let a = char_code c in unsafe_set s ' ! n ' ' ; \\ incr n ; unsafe_set s ' ! n ( char_chr ( 48 + a / 100 ) ) ; incr n ; unsafe_set s ' ! n ( char_chr ( 48 + ( a / 10 ) mod 10 ) ) ; incr n ; unsafe_set s ' ! n ( char_chr ( 48 + a mod 10 ) ) ; end ; incr n done ; s ' end
let map f s = let l = length s in if l = 0 then s else begin let r = create l in for i = 0 to l - 1 do unsafe_set r i ( f ( unsafe_get s i ) ) done ; r end
let mapi f s = let l = length s in if l = 0 then s else begin let r = create l in for i = 0 to l - 1 do unsafe_set r i ( f i ( unsafe_get s i ) ) done ; r end
let uppercase_ascii s = map Char . uppercase_ascii s
let lowercase_ascii s = map Char . lowercase_ascii s
let apply1 f s = if length s = 0 then s else begin let r = copy s in unsafe_set r 0 ( f ( unsafe_get s 0 ) ) ; r end
let capitalize_ascii s = apply1 Char . uppercase_ascii s
let uncapitalize_ascii s = apply1 Char . lowercase_ascii s
let rec index_rec s lim i c = if i >= lim then raise Not_found else if unsafe_get s i = c then i else index_rec s lim ( i + 1 ) c
let index s c = index_rec s ( length s ) 0 c
let rec index_rec_opt s lim i c = if i >= lim then None else if unsafe_get s i = c then Some i else index_rec_opt s lim ( i + 1 ) c
let index_opt s c = index_rec_opt s ( length s ) 0 c
let index_from s i c = let l = length s in if i < 0 || i > l then invalid_arg " String . index_from / Bytes . index_from " else index_rec s l i c
let index_from_opt s i c = let l = length s in if i < 0 || i > l then invalid_arg " String . index_from_opt / Bytes . index_from_opt " else index_rec_opt s l i c
let rec rindex_rec s i c = if i < 0 then raise Not_found else if unsafe_get s i = c then i else rindex_rec s ( i - 1 ) c
let rindex s c = rindex_rec s ( length s - 1 ) c
let rindex_from s i c = if i < - 1 || i >= length s then invalid_arg " String . rindex_from / Bytes . rindex_from " else rindex_rec s i c
let rec rindex_rec_opt s i c = if i < 0 then None else if unsafe_get s i = c then Some i else rindex_rec_opt s ( i - 1 ) c
let rindex_opt s c = rindex_rec_opt s ( length s - 1 ) c
let rindex_from_opt s i c = if i < - 1 || i >= length s then invalid_arg " String . rindex_from_opt / Bytes . rindex_from_opt " else rindex_rec_opt s i c
let contains_from s i c = let l = length s in if i < 0 || i > l then invalid_arg " String . contains_from / Bytes . contains_from " else try ignore ( index_rec s l i c ) ; true with Not_found -> false
let contains s c = contains_from s 0 c
let rcontains_from s i c = if i < 0 || i >= length s then invalid_arg " String . rcontains_from / Bytes . rcontains_from " else try ignore ( rindex_rec s i c ) ; true with Not_found -> false
let compare ( x : t ) ( y : t ) = Stdlib . compare x y
let uppercase s = map Char . uppercase s
let lowercase s = map Char . lowercase s
let capitalize s = apply1 Char . uppercase s
let uncapitalize s = apply1 Char . lowercase s
let to_seq s = let rec aux i ( ) = if i = length s then Seq . Nil else let x = get s i in Seq . Cons ( x , aux ( i + 1 ) ) in aux 0
let to_seqi s = let rec aux i ( ) = if i = length s then Seq . Nil else let x = get s i in Seq . Cons ( ( i , x ) , aux ( i + 1 ) ) in aux 0
let of_seq i = let n = ref 0 in let buf = ref ( make 256 ' \ 000 ' ) in let resize ( ) = let new_len = min ( 2 * length ! buf ) Sys . max_string_length in if length ! buf = new_len then failwith " Bytes . of_seq : cannot grow bytes " ; let new_buf = make new_len ' \ 000 ' in blit ! buf 0 new_buf 0 ! n ; buf := new_buf in Seq . iter ( fun c -> if ! n = length ! buf then resize ( ) ; set ! buf ! n c ; incr n ) i ; sub ! buf 0 ! n
let get_int8 b i = ( ( get_uint8 b i ) lsl ( Sys . int_size - 8 ) ) asr ( Sys . int_size - 8 )
let get_uint16_le b i = if Sys . big_endian then swap16 ( get_uint16_ne b i ) else get_uint16_ne b i
let get_uint16_be b i = if not Sys . big_endian then swap16 ( get_uint16_ne b i ) else get_uint16_ne b i
let get_int16_ne b i = ( ( get_uint16_ne b i ) lsl ( Sys . int_size - 16 ) ) asr ( Sys . int_size - 16 )
let get_int16_le b i = ( ( get_uint16_le b i ) lsl ( Sys . int_size - 16 ) ) asr ( Sys . int_size - 16 )
let get_int16_be b i = ( ( get_uint16_be b i ) lsl ( Sys . int_size - 16 ) ) asr ( Sys . int_size - 16 )
let get_int32_le b i = if Sys . big_endian then swap32 ( get_int32_ne b i ) else get_int32_ne b i
let get_int32_be b i = if not Sys . big_endian then swap32 ( get_int32_ne b i ) else get_int32_ne b i
let get_int64_le b i = if Sys . big_endian then swap64 ( get_int64_ne b i ) else get_int64_ne b i