Last active
December 2, 2024 12:45
-
-
Save dx3mod/1999b99d0d26f95705d1641722f474ab to your computer and use it in GitHub Desktop.
Dead simple example of using Lwt_engine to read files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let string_of_buffer buffer = Buffer.to_bytes buffer |> Bytes.unsafe_to_string | |
let read_file ?(perm = 0o777) filename = | |
let promise, resolver = Lwt.task () in | |
let fd = Unix.openfile filename [ O_RDONLY ] perm in | |
let buffer = Buffer.create 1024 in | |
let chunk = Bytes.create 1024 in | |
let chunk_length = Bytes.length chunk in | |
let dispose ev = | |
Lwt_engine.stop_event ev; | |
Unix.close fd | |
in | |
let ev = | |
Lwt_engine.on_readable fd @@ fun ev -> | |
let bytes_read = Unix.read fd chunk 0 chunk_length in | |
Buffer.add_subbytes buffer chunk 0 bytes_read; | |
if bytes_read = 0 then begin | |
dispose ev; | |
Lwt.wakeup resolver (string_of_buffer buffer) | |
end | |
in | |
Lwt.on_cancel promise (fun () -> dispose ev); | |
promise | |
let () = | |
let read_and_print = Fun.compose (Lwt.Infix.( =<< ) Lwt_io.printl) read_file in | |
Lwt_main.run begin | |
Sys.argv |> Array.to_list |> List.tl |> Lwt_list.iter_p read_and_print | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment