### HTTP GET Request Example Source: https://ocaml-multicore.github.io/eio/eio/Eio/Net/index An example demonstrating how to perform an HTTP GET request using Eio.Net. It connects to a specified address, sends a GET request, and copies the response to standard output. ```ocaml let addr = `Tcp (Ipaddr.V4.loopback, 8080) let http_get ~net ~stdout addr = Switch.run @@ fun sw -> let flow = Net.connect ~sw net addr in Flow.copy_string "GET / HTTP/1.0\r\n\n" flow; Flow.shutdown flow `Send; Flow.copy flow stdout ``` -------------------------------- ### Example: Echo with Eio.Process Source: https://ocaml-multicore.github.io/eio/eio/Eio/Process/index An example demonstrating how to use Eio.Process to run an 'echo' command and capture its output line by line. ```ocaml # Eio_main.run @@ fun env -> let proc_mgr = Eio.Stdenv.process_mgr env in Eio.Process.parse_out proc_mgr Eio.Buf_read.line ["echo"; "hello"] ``` -------------------------------- ### Example usage of Eio.Fiber.fork_seq Source: https://ocaml-multicore.github.io/eio/eio/Eio/Fiber/index This example demonstrates how to use `fork_seq` to create a fiber that yields numbers from 1 to 3, and then iterates over the resulting sequence to print each number. ```ocaml Switch.run @@ fun sw -> let seq = Fiber.fork_seq ~sw (fun yield -> for i = 1 to 3 do traceln "Yielding %d" i; yield i done ) in Seq.iter (traceln "Got: %d") seq ``` -------------------------------- ### Accessing Current Working Directory and Saving Data Source: https://ocaml-multicore.github.io/eio/eio/Eio/Path/index Demonstrates how to get the current working directory using `Eio.Stdenv.cwd` and save data to a file named 'output.txt' in that directory. The `Eio.Path.( / )` operator is used for path concatenation, and `Eio.Path.save` writes the content. The example is executed using `Eio_main.run`. ```ocaml let ( / ) = Eio.Path.( / ) let run dir = Eio.Path.save ~create:(`Exclusive 0o600) (dir / "output.txt") "the data" let () = Eio_main.run @@ fun env -> run (Eio.Stdenv.cwd env) ``` -------------------------------- ### Eio Buf_write Example Usage Source: https://ocaml-multicore.github.io/eio/eio/Eio/Buf_write/index Demonstrates the basic usage of Eio.Buf_write by writing strings to a mock stdout flow. It shows how to initialize a writer, write multiple strings, and observe the output after yielding and writing more data. ```ocaml module Write = Eio.Buf_write let () = Eio_mock.Backend.run @@ fun () -> let stdout = Eio_mock.Flow.make "stdout" in Write.with_flow stdout (fun w -> Write.string w "foo"; Write.string w "bar"; Eio.Fiber.yield (); Write.string w "baz"; ) ``` -------------------------------- ### OCaml Eio Stream Basic Usage Source: https://ocaml-multicore.github.io/eio/eio/Eio/Stream/index Demonstrates the basic usage of Eio.Stream, including creating a stream, adding elements, and taking elements. This example highlights the queue's behavior when elements are added and retrieved. ```ocaml let t = Stream.create 100 in Stream.add t 1; Stream.add t 2; assert (Stream.take t = 1); assert (Stream.take t = 2) ``` -------------------------------- ### Create Mock Domain Manager (Eio_mock) Source: https://ocaml-multicore.github.io/eio/eio/Eio_mock/Domain_manager/index Creates a mock Eio Domain Manager that executes all tasks within the parent domain. It assigns sequential domain IDs starting from 1. ```ocaml val create : unit -> Eio.Domain_manager.ty Eio.Std.r ``` -------------------------------- ### Loading File Content Source: https://ocaml-multicore.github.io/eio/eio/Eio/Path/index Shows how to load the content of a file using `Eio.Path.load`. This function is a convenience wrapper for opening and reading a file. The example accesses the '/etc/passwd' file, assuming it's accessible via the `fs` object. ```ocaml Eio.Path.load (fs / "/etc/passwd") ``` -------------------------------- ### Spawn Child Process with Eio_linux Source: https://ocaml-multicore.github.io/eio/eio_linux/Eio_linux/Low_level/Process/index Spawns a child process that executes a list of setup actions. The last action must be `Fork_action.execve`. The child process is managed by a switch, ensuring it's terminated if the switch is cancelled. It's recommended to await the exit status after spawning. ```ocaml val spawn : sw:Eio.Std.Switch.t -> Fork_action.t list -> t spawn ~sw actions --- -- The child will be sent Sys.sigkill if sw finishes. ``` -------------------------------- ### Run Raw Function in New Domain with Eio Source: https://ocaml-multicore.github.io/eio/eio/Eio/Domain_manager/index The `run_raw` function is similar to `run` but does not start an event loop in the new domain. This means it cannot perform I/O operations or fork fibers, making it suitable for CPU-bound tasks. ```ocaml val run_raw : _ t -> (unit -> 'a) -> 'a run_raw t f is like `run`, but does not run an event loop in the new domain, and so cannot perform IO, fork fibers, etc. ``` -------------------------------- ### Get File Metadata - OCaml Source: https://ocaml-multicore.github.io/eio/eio/Eio/Path/index Retrieves metadata about a file or directory. The `follow` parameter determines whether to follow symbolic links. `kind` specifically returns the type of the file system entry. ```ocaml val stat : follow:bool -> _ t -> File.Stat.t `stat ~follow t` returns metadata about the file `t`. If `t` is a symlink, the information returned is about the target if `follow = true`, otherwise it is about the link itself. val kind : follow:bool -> _ t -> [ File.Stat.kind | `Not_found ] `kind ~follow t` is the type of `t`, or ``Not_found` if it doesn't exist. * parameter follow If `true` and `t` is a symlink, return the type of the target rather than ``Symbolic_link`. ``` -------------------------------- ### Configure Server Listening - Eio_mock.Net Source: https://ocaml-multicore.github.io/eio/eio/Eio_mock/Net/index Configures the behavior when a server starts listening for incoming connections on a mock network. This is used to define how the mock server reacts to listening events. ```ocaml val on_listen : t -> _ Eio.Net.listening_socket Handler.actions -> unit on_listen t actions configures what to do when a server starts listening for incoming connections. ``` -------------------------------- ### Spawn Child Process with Eio_posix Source: https://ocaml-multicore.github.io/eio/eio_posix/Eio_posix/Low_level/Process/index Forks a child process that executes a list of setup actions. The last action must be `Fork_action.execve`. The child process will receive `Sys.sigkill` if the provided switch `sw` is terminated. Typically, you would await the exit status of the child process after spawning. ```ocaml val spawn : sw:Eio.Std.Switch.t -> Fork_action.t list -> t spawn ~sw actions --- (* Example usage (conceptual): let actions = [ (* setup actions like setting environment variables, changing directory, etc. *) Fork_action.execve (~path: "/bin/ls") (~argv: [|"ls"; "-l"|]) (~env: [||]) ] Eio_main.run @@ fun switch -> let child = Low_level.Process.spawn ~sw actions in (* Do something with the child process, e.g., wait for it to finish *) match Eio.Std.Promise.await (Low_level.Process.exit_status child) with | Ok status -> Printf.printf "Child exited with status: %s\n" (Unix.string_of_process_status status) | Error exn -> Printf.eprintf "Error waiting for child: %s\n" (Printexc.to_string exn) *) ``` -------------------------------- ### Run Eio Event Loop with io_uring (Eio_linux) Source: https://ocaml-multicore.github.io/eio/eio_linux/Eio_linux/index The 'run' function in Eio_linux starts an event loop using io_uring. It allows configuration of queue depth, buffer size, and a fallback mechanism for when io_uring is unavailable. For portable code, Eio_main.run is recommended. ```ocaml val run : ?queue_depth:int -> ?n_blocks:int -> ?block_size:int -> ?polling_timeout:int -> ?fallback:([ `Msg of string ] -> 'a) -> (stdenv -> 'a) -> 'a ``` -------------------------------- ### Mocking Eio Flow with Custom Read Behavior Source: https://ocaml-multicore.github.io/eio/eio/Eio_mock/index Demonstrates how to create mock Eio Flow resources and define their read behavior using `Eio_mock.Flow.make` and `Eio_mock.Flow.on_read`. This allows simulating data chunks and end-of-file conditions for testing purposes. The example then uses `Eio.Flow.copy` to transfer data between the mock flows, showing the interaction. ```ocaml let stdin = Eio_mock.Flow.make "stdin" in let stdout = Eio_mock.Flow.make "stdout" in Eio_mock.Flow.on_read stdin [ `Return "chunk1"; `Return "chunk2"; `Raise End_of_file ]; Eio.Flow.copy stdin stdout ``` -------------------------------- ### OCaml: Get Sink Interface Implementation Source: https://ocaml-multicore.github.io/eio/eio/Eio/Resource/index This OCaml snippet demonstrates how to retrieve the implementation of the `Sink` interface for a given resource. It uses `Resource.get` to obtain the implementation from the resource's handler (`ops`) and then calls the `write` method on the obtained implementation. ```ocaml let write (Resource.T (t, ops)) bufs = let module X = (val (Resource.get ops Sink)) in X.write t bufs ``` -------------------------------- ### Splitting Path Components Source: https://ocaml-multicore.github.io/eio/eio/Eio/Path/index Illustrates the `Eio.Path.split` function, which separates a path into its directory and base name. It returns `Some (dir, basename)` if the path can be split, and `None` otherwise. Examples show various splitting scenarios. ```ocaml val split : 'a t -> ('a t * string) option split t returns Some (dir, basename), where basename is the last path component in t and dir is t without basename. dir / basename refers to the same path as t. split t = None if there is nothing to split. For example: * split (root, "foo/bar") = Some ((root, "foo"), "bar") * split (root, "/foo/bar") = Some ((root, "/foo"), "bar") * split (root, "/foo/bar/baz") = Some ((root, "/foo/bar"), "baz") * split (root, "/foo/bar//baz/") = Some ((root, "/foo/bar"), "baz") * split (root, "bar") = Some ((root, ""), "bar") * split (root, ".") = Some ((root, ""), ".") * split (root, "") = None * split (root, "/") = None ``` -------------------------------- ### OCaml Eio.Cancel: Create and Manage Nested Cancellation Contexts Source: https://ocaml-multicore.github.io/eio/eio/Eio/Cancel/index Demonstrates how to use `Eio.Cancel.sub` to install a new cancellation context, run a function within it, and restore the previous context. This is crucial for managing cancellation scopes in concurrent operations. ```ocaml val sub : (t -> 'a) -> 'a sub fn installs a new cancellation context t, runs fn t inside it, and then restores the old context. ``` -------------------------------- ### Parse a sequence of items with eio Source: https://ocaml-multicore.github.io/eio/eio/Eio/Buf_read/index Creates a sequence parser that uses a given parser 'p' to get each item. The sequence can optionally stop based on a 'stop' parser. Example shows parsing the first 4 lines of input. ```ocaml val seq : ?stop:bool parser -> 'a parser -> 'a Stdlib.Seq.t parser let head n r = r |> Buf_read.(seq line) |> Seq.take n |> List.of_seq ``` -------------------------------- ### Running Eio with Standard Environment Source: https://ocaml-multicore.github.io/eio/eio/Eio/Stdenv/index This snippet demonstrates how to run the Eio event loop and access the standard environment. It shows how to open a directory and serve files using the provided file system and network interfaces. ```ocaml let () = Eio_main.run @@ fun env -> Eio.Path.with_open_dir env#fs "/srv/www" @@ fun www -> serve_files www ~net:env#net ``` -------------------------------- ### Creating an Io Exception with Empty Context Source: https://ocaml-multicore.github.io/eio/eio/Eio/Exn/index Demonstrates how to create a generic `Io` exception with an empty context using the `create` function. ```ocaml val create : err -> exn ``` -------------------------------- ### Custom Trace Logging with Eio.Debug Source: https://ocaml-multicore.github.io/eio/eio/Eio/Debug/index This example demonstrates how to define and use a custom trace logging function using Eio.Debug. It overrides the default `traceln` function to prepend a custom prefix to trace messages. The `Fiber.with_binding` function is used to apply this custom tracing within a specific fiber context. ```ocaml open Eio.Std let my_traceln = { Eio.Debug.traceln = fun ?__POS__:_ fmt -> Fmt.epr ("[custom-trace] " ^^ fmt ^^ "@.") } let () = Eio_main.run @@ fun env -> let debug = Eio.Stdenv.debug env in Fiber.with_binding debug#traceln my_traceln @@ fun () -> traceln "Traced with custom function" ``` -------------------------------- ### Get Process ID Source: https://ocaml-multicore.github.io/eio/eio/Eio/Process/index Retrieves the process ID (PID) of a given process. ```ocaml val pid : _ t -> int ``` -------------------------------- ### Get Datagram Address Info (OCaml) Source: https://ocaml-multicore.github.io/eio/eio/Eio/Net/index Similar to getaddrinfo, but specifically filters for datagram protocols. ```ocaml val getaddrinfo_datagram : ?service:string -> _ t -> string -> Sockaddr.datagram list ``` -------------------------------- ### Get Stream Address Info (OCaml) Source: https://ocaml-multicore.github.io/eio/eio/Eio/Net/index Similar to getaddrinfo, but specifically filters for stream protocols. ```ocaml val getaddrinfo_stream : ?service:string -> _ t -> string -> Sockaddr.stream list ``` -------------------------------- ### Create Directory Source: https://ocaml-multicore.github.io/eio/eio_linux/Eio_linux/Low_level/index Creates a new directory at the specified path relative to a directory file descriptor. Requires file permissions to be set. ```ocaml val mkdir : perm:int -> dir_fd -> string -> unit mkdir ~perm dir path creates directory dir / path. ``` -------------------------------- ### OCaml Eio Get Listening Socket Address Source: https://ocaml-multicore.github.io/eio/eio/Eio/Net/index Retrieves the local address of a listening socket. ```ocaml val listening_addr : [> 'tag listening_socket_ty ] Std.r -> Sockaddr.stream ``` -------------------------------- ### Running an Eio Event Loop with a Full Mock Environment Source: https://ocaml-multicore.github.io/eio/eio/Eio_mock/Backend/index The `run_full` function is similar to `run` but additionally provides a mock environment, including a monotonic clock that advances automatically when idle and a wall clock synchronized with the monotonic time. ```ocaml val run_full : (stdenv -> 'a) -> 'a ``` -------------------------------- ### Get File Status (fstat) Source: https://ocaml-multicore.github.io/eio/eio_linux/Eio_linux/Low_level/index Retrieves status information for a file descriptor, similar to `Unix.LargeFile.fstat`. ```ocaml val fstat : fd -> Eio.File.Stat.t Like Unix.LargeFile.fstat. ``` -------------------------------- ### Get Name Info (OCaml) Source: https://ocaml-multicore.github.io/eio/eio/Eio/Net/index Retrieves the hostname and service name corresponding to a given socket address. ```ocaml val getnameinfo : _ t -> Sockaddr.t -> string * string ``` -------------------------------- ### Create and Use Resource Pool - OCaml Eio Source: https://ocaml-multicore.github.io/eio/eio/Eio/Pool/index Demonstrates how to create a resource pool with a specified capacity and an allocation function, and then use a resource from the pool. The `create` function takes the pool size and an allocation function, while `use` takes the pool and a function to apply to a resource. ```ocaml let buffer_pool = Eio.Pool.create 10 (fun () -> Bytes.create 1024) in Eio.Pool.use buffer_pool (fun buf -> ...) ``` -------------------------------- ### Create Directory - OCaml Source: https://ocaml-multicore.github.io/eio/eio/Eio/Path/index Creates a new directory with specified permissions. The `mkdirs` function extends this to create parent directories recursively if they don't exist. ```ocaml val mkdir : perm:File.Unix_perm.t -> _ t -> unit `mkdir ~perm t` creates a new directory `t` with permissions `perm`. val mkdirs : ?exists_ok:bool -> perm:File.Unix_perm.t -> _ t -> unit `mkdirs ~perm t` creates directory `t` along with any missing ancestor directories, recursively. All created directories get permissions `perm`, but existing directories do not have their permissions changed. * parameter exist_ok If `false` (the default) then we raise `Fs.error.Already_exists` if `t` is already a directory. ``` -------------------------------- ### Get Process ID with Eio_posix Source: https://ocaml-multicore.github.io/eio/eio_posix/Eio_posix/Low_level/Process/index Retrieves the process ID (PID) of a child process managed by the `Low_level.Process` module. ```ocaml val pid : t -> int --- (* Example usage (conceptual): let pid_value = Low_level.Process.pid child Printf.printf "Child PID: %d\n" pid_value *) ``` -------------------------------- ### Opening a File for Reading and Writing Source: https://ocaml-multicore.github.io/eio/eio/Eio/Path/index Explains `Eio.Path.open_out` for opening files for both reading and writing. It supports parameters like `append` to control write behavior and `create` to manage file creation and permissions. Files are opened in binary mode. ```ocaml val open_out : sw:Switch.t -> ?append:bool -> create:Fs.create -> _ t -> File.rw_ty Resource.t open_out ~sw t opens t for reading and writing. Note: files are always opened in binary mode. * parameter append Open for appending: always write at end of file. * parameter create Controls whether to create the file, and what permissions to give it if so. ``` -------------------------------- ### Get Process ID in Eio_linux Source: https://ocaml-multicore.github.io/eio/eio_linux/Eio_linux/Low_level/Process/index Retrieves the process ID (PID) of a child process managed by the Eio_linux library. ```ocaml val pid : t -> int ``` -------------------------------- ### Get or Set Domain ID (Eio_mock) Source: https://ocaml-multicore.github.io/eio/eio/Eio_mock/Domain_manager/index Provides access to the current mock domain's ID, used for prefixing trace messages. ```ocaml val id : string Eio.Std.Fiber.key ``` -------------------------------- ### Run Function with Mock Domain Manager (Eio_mock) Source: https://ocaml-multicore.github.io/eio/eio/Eio_mock/Domain_manager/index Runs a provided function `fn` with a new mock domain manager. It also enables domain tracing to display domain IDs and sets the initial domain ID to '0'. ```ocaml val run : (Eio.Domain_manager.ty Eio.Std.r -> 'a) -> 'a ``` -------------------------------- ### Get Address Info (OCaml) Source: https://ocaml-multicore.github.io/eio/eio/Eio/Net/index Resolves a hostname or IP address to a list of IP addresses. An optional service name can be provided. ```ocaml val getaddrinfo : ?service:string -> _ t -> string -> Sockaddr.t list ``` -------------------------------- ### OCaml Get Pending Write Size Source: https://ocaml-multicore.github.io/eio/eio/Eio/Buf_write/index Returns the size, in bytes, of the next write that will be surfaced to the caller via `await_batch`. ```OCaml val pending_bytes : t -> int ``` -------------------------------- ### Getting Backend Identifier Source: https://ocaml-multicore.github.io/eio/eio/Eio/Stdenv/index This OCaml code snippet retrieves the name of the Eio backend being used. It returns a string, which can be 'Eio_unix' or 'Eio_windows'. ```ocaml `val backend_id : < backend_id : string.. > -> string` ``` -------------------------------- ### OCaml: Pretty-Printing Backend Exceptions with Eio Source: https://ocaml-multicore.github.io/eio/eio/Eio/Exn/Backend/index This snippet describes the `pp` function in the Eio Exn.Backend module, which is used for pretty-printing backend-specific exceptions. It highlights the `show` flag's control over the output, allowing for placeholder printing when errors are hidden. ```ocaml val show : bool Stdlib.ref val pp : t Fmt.t (* The 'pp' function formats exceptions. If 'show' is false, it prints a placeholder. *) ``` -------------------------------- ### Create an Executor Pool Source: https://ocaml-multicore.github.io/eio/eio/Eio/Executor_pool/index Demonstrates how to create an Eio.Executor_pool with a specified number of domains. The pool is initialized with a switch and the domain manager from the environment. ```ocaml let () = Eio_main.run @@ fun env -> Switch.run @@ fun sw -> let pool = Eio.Executor_pool.create ~sw (Eio.Stdenv.domain_mgr env) ~domain_count:4 in main ~pool ``` -------------------------------- ### OCaml Eio Get File Metadata Source: https://ocaml-multicore.github.io/eio/eio/Eio/File/index Retrieves the Stat.t record associated with a read-only file descriptor and returns the size of the file. ```ocaml val stat : _ ro -> Stat.t val size : _ ro -> Optint.Int63.t ``` -------------------------------- ### Create Mock Listening Socket - Eio_mock.Net Source: https://ocaml-multicore.github.io/eio/eio/Eio_mock/Net/index Creates a mock listening socket, optionally configured with a listening address. If no address is provided, a dummy address is used. This is used to simulate server sockets. ```ocaml val listening_socket : ?listening_addr:Eio.Net.Sockaddr.stream -> string -> listening_socket listening_socket label can be configured to provide mock connections. If `listening_addr` is not provided, a dummy value will be reported. ``` -------------------------------- ### Eio_unix.Net: Get underlying file descriptor Source: https://ocaml-multicore.github.io/eio/eio/Eio_unix/Net/index The `fd` function retrieves the underlying file descriptor (FD) of a given socket, useful for low-level operations. ```ocaml val fd : [> `Platform of [> `Unix ] | `Socket ] Eio.Std.r -> Fd.t ``` -------------------------------- ### Open and Read Directory - OCaml Source: https://ocaml-multicore.github.io/eio/eio/Eio/Path/index Opens a directory for access within a given switch context. `read_dir` lists the entries within a directory, excluding '.' and '..'. ```ocaml val open_dir : sw:Switch.t -> _ t -> [< `Close | Fs.dir_ty ] t `open_dir ~sw t` opens `t`. This can be passed to functions to grant access only to the subtree `t`. val with_open_dir : _ t -> ([< `Close | Fs.dir_ty ] t -> 'a) -> 'a `with_open_dir` is like `open_dir`, but calls `fn dir` with the new directory and closes it automatically when `fn` returns (if it hasn't already been closed by then). val read_dir : _ t -> string list `read_dir t` reads directory entries for `t`. The entries are sorted using `String.compare`. Note: The special Unix entries "." and ".." are not included in the results. ``` -------------------------------- ### OCaml Eio Stream Length Source: https://ocaml-multicore.github.io/eio/eio/Eio/Stream/index Provides the `length` function to get the current number of items in the stream. This is useful for monitoring the stream's state. ```ocaml val length : 'a t -> int ``` -------------------------------- ### Get Fiber-Local Variable Value (Ocaml) Source: https://ocaml-multicore.github.io/eio/eio/Eio/Fiber/index Retrieves the value associated with a given fiber-local variable key. Returns `Some value` if bound, otherwise `None`. ```ocaml val get : 'a key -> 'a option get key ``` -------------------------------- ### Parse a specific string with eio Source: https://ocaml-multicore.github.io/eio/eio/Eio/Buf_read/index Checks if the input stream starts with the given string 's' and consumes it. Raises 'Failure' if 's' is not a prefix of the stream. ```ocaml val string : string -> unit parser ``` -------------------------------- ### Standard Input File Descriptor Source: https://ocaml-multicore.github.io/eio/eio/Eio_unix/Fd/index Provides the Eio wrapper for the standard input Unix file descriptor. ```ocaml val stdin : t ``` -------------------------------- ### Pretty-Printing Eio Exceptions Source: https://ocaml-multicore.github.io/eio/eio/Eio/Exn/index Provides a formatter (`pp`) for Eio exceptions, which is optimized for `Io` exceptions compared to the standard `Fmt.exn`. ```ocaml val pp : exn Fmt.t ``` -------------------------------- ### Eio DNS Get Address Info Source: https://ocaml-multicore.github.io/eio/eio_linux/Eio_linux/Low_level/index Resolves a hostname or IP address to a list of network addresses. The 'service' parameter specifies the port or service name. ```ocaml val getaddrinfo : service:string -> string -> Eio.Net.Sockaddr.t list ``` -------------------------------- ### OCaml Eio.Time Get Current Time Source: https://ocaml-multicore.github.io/eio/eio/Eio/Time/index Provides a function to retrieve the current time from a given clock. The time is returned in seconds since the Unix epoch. ```ocaml val now : _ clock -> float (* now t is the current time since 00:00:00 GMT, Jan. 1, 1970 - in seconds - according to t. *) ``` -------------------------------- ### Create Symbolic Link Source: https://ocaml-multicore.github.io/eio/eio_linux/Eio_linux/Low_level/index Creates a new symbolic link at a specified path, pointing to a target path. Operates relative to a directory file descriptor. ```ocaml val symlink : link_to:string -> dir_fd -> string -> unit symlink ~link_to dir path creates a new symlink at dir / path pointing to link_to. ``` -------------------------------- ### Ocaml Eio: Get Consumed Bytes Count Source: https://ocaml-multicore.github.io/eio/eio/Eio/Buf_read/index Returns the total number of bytes that have been consumed from the buffer. This represents the offset into the stream for the next byte to be parsed. ```ocaml val consumed_bytes : t -> int ``` -------------------------------- ### OCaml Get Free Buffer Space Source: https://ocaml-multicore.github.io/eio/eio/Eio/Buf_write/index Returns the amount of free space in the serializer's write buffer. If a write exceeds this, a new buffer will be allocated. ```OCaml val free_bytes_in_buffer : t -> int ``` -------------------------------- ### Configure Socket Accept - Eio_mock.Net Source: https://ocaml-multicore.github.io/eio/eio/Eio_mock/Net/index Configures how the mock server handles the 'accept' call on a listening socket. This allows defining the behavior when a new client connection is established. ```ocaml val on_accept : listening_socket -> (Flow.t * Eio.Net.Sockaddr.stream) Handler.actions -> unit on_accept socket actions configures how to respond when the server calls "accept". ``` -------------------------------- ### Define Get Context Effect in OCaml Source: https://ocaml-multicore.github.io/eio/eio/Eio/Private/Effects/index Defines the `Get_context` effect, which allows immediate retrieval of the current fiber's context without switching fibers. ```ocaml type Stdlib.Effect.t += | Get_context : Fiber_context.t Stdlib.Effect.t ``` -------------------------------- ### Standard Output File Descriptor Source: https://ocaml-multicore.github.io/eio/eio/Eio_unix/Fd/index Provides the Eio wrapper for the standard output Unix file descriptor. ```ocaml val stdout : t ``` -------------------------------- ### Get Network Address Info in OCaml Source: https://ocaml-multicore.github.io/eio/eio/Eio_unix/Net/index The `getnameinfo` function retrieves the domain name and service associated with a given network socket address. It is part of the Eio.Net module. ```ocaml val getnameinfo : Eio.Net.Sockaddr.t -> string * string getnameinfo sockaddr (* returns domain name and service for sockaddr *) ``` -------------------------------- ### Mock Network Creation - Eio_mock.Net Source: https://ocaml-multicore.github.io/eio/eio/Eio_mock/Net/index Creates a new mock network with a given label. This function is fundamental for setting up mock network environments for testing purposes. ```ocaml val make : string -> t make label is a new mock network. ``` -------------------------------- ### Accessing System Clock Source: https://ocaml-multicore.github.io/eio/eio/Eio/Stdenv/index This OCaml code snippet demonstrates how to access the system clock for getting the current time and date within the Eio environment. It returns a Time.clock. ```ocaml `val clock : < clock : _ Time.clock as 'a.. > -> 'a` ``` -------------------------------- ### Open File with openat Source: https://ocaml-multicore.github.io/eio/eio_linux/Eio_linux/Low_level/index Opens a file at a given path relative to a directory file descriptor. Supports various access modes, flags, and permissions. Requires a switch for managing the operation's lifecycle. ```ocaml val openat : sw:Eio.Std.Switch.t -> ?seekable:bool -> access:[ `R | `W | `RW ] -> flags:Uring.Open_flags.t -> perm:Unix.file_perm -> dir_fd -> string -> fd openat ~sw ~access ~flags ~perm dir path opens dir/path. ``` -------------------------------- ### Accessing Current Working Directory Source: https://ocaml-multicore.github.io/eio/eio/Eio/Stdenv/index This OCaml code snippet shows how to get the current working directory (cwd) of the process using the Eio environment. It returns a Path.t. ```ocaml `val cwd : < cwd : _ Path.t as 'a.. > -> 'a` ``` -------------------------------- ### Map a function over a parser's result with eio Source: https://ocaml-multicore.github.io/eio/eio/Eio/Buf_read/index Parses the stream using parser 'a' to get a value 'v', then applies function 'f' to 'v' and returns the result. ```ocaml val map : ('a -> 'b) -> 'a parser -> 'b parser ``` -------------------------------- ### Read Data Up To a Limit Source: https://ocaml-multicore.github.io/eio/eio_linux/Eio_linux/Low_level/index Reads at most a specified number of bytes from a file descriptor into a chunk. Returns as soon as some data is available. Can optionally specify a starting file offset. ```ocaml val read_upto : ?file_offset:Optint.Int63.t -> fd -> Uring.Region.chunk -> int -> int read_upto fd chunk len reads at most len bytes from fd, returning as soon as some data is available. * parameter file_offset Read from the given position in fd (default: 0). * raises End_of_file Raised if all data has already been read. ``` -------------------------------- ### OCaml Eio Run Concurrent Server Source: https://ocaml-multicore.github.io/eio/eio/Eio/Net/index Establishes and runs a concurrent socket server. It accepts incoming connections using `accept_fork` and handles them with a provided connection handler. Supports running on multiple domains and stopping the server gracefully. ```ocaml val run_server : ?max_connections:int -> ?additional_domains:(_ Domain_manager.t * int) -> ?stop:'a Promise.t -> on_error:(exn -> unit) -> [> 'tag listening_socket_ty ] Std.r -> [< 'tag stream_socket_ty ] connection_handler -> 'a run_server ~on_error sock connection_handler ``` -------------------------------- ### Get Exit Status of Child Process with Eio_posix Source: https://ocaml-multicore.github.io/eio/eio_posix/Eio_posix/Low_level/Process/index Returns a promise that will resolve to the exit status of the child process. This allows for asynchronous waiting and handling of process termination. ```ocaml val exit_status : t -> Unix.process_status Eio.Std.Promise.t exit_status t --- (* Example usage (conceptual): match Eio.Std.Promise.await (Low_level.Process.exit_status child) with | Ok status -> Printf.printf "Child exited with status: %s\n" (Unix.string_of_process_status status) | Error exn -> Printf.eprintf "Error waiting for child: %s\n" (Printexc.to_string exn) *) ``` -------------------------------- ### Eio Process Module Source: https://ocaml-multicore.github.io/eio/eio_linux/Eio_linux/Low_level/index Provides functionality for managing and interacting with system processes. ```ocaml module Process : sig ... end ``` -------------------------------- ### Ocaml Eio: Get Buffered Bytes Source: https://ocaml-multicore.github.io/eio/eio/Eio/Buf_read/index Retrieves the number of bytes available for reading without accessing the underlying flow. This is useful for understanding the current state of the internal buffer. ```ocaml val buffered_bytes : t -> int ``` -------------------------------- ### Seek File Position Source: https://ocaml-multicore.github.io/eio/eio_linux/Eio_linux/Low_level/index Sets and/or gets the current file position for a file descriptor, similar to `Unix.lseek`. Supports seeking relative to the beginning, current position, or end of the file. ```ocaml val lseek : fd -> Optint.Int63.t -> [ `Set | `Cur | `End ] -> Optint.Int63.t Set and/or get the current file position. Like Unix.lseek. ``` -------------------------------- ### Create and Resolve a Promise in OCaml Source: https://ocaml-multicore.github.io/eio/eio/Eio/Promise/index Demonstrates the creation of a promise and its associated resolver, and then concurrently awaits the promise while resolving it with a value. This showcases basic promise usage for inter-domain communication. ```ocaml let promise, resolver = Promise.create () in Fiber.both (fun () -> traceln "Got %d" (Promise.await promise)) (fun () -> Promise.resolve resolver 42) ``` -------------------------------- ### Get Monotonic Clock Effect - OCaml Source: https://ocaml-multicore.github.io/eio/eio/Eio_unix/Private/index Defines an effect to retrieve the monotonic clock. Monotonic clocks are essential for measuring time intervals reliably, unaffected by system time changes. ```ocaml type Stdlib.Effect.t += `Get_monotonic_clock : Eio.Time.Mono.ty Eio.Std.r Stdlib.Effect.t ``` -------------------------------- ### Accessing File System Source: https://ocaml-multicore.github.io/eio/eio/Eio/Stdenv/index This OCaml code snippet demonstrates how to access the entire file system from the Eio environment. It returns a Path.t which can be used for file operations. ```ocaml `val fs : < fs : _ Path.t as 'a.. > -> 'a` ``` -------------------------------- ### Create Pipe Source: https://ocaml-multicore.github.io/eio/eio_linux/Eio_linux/Low_level/index Creates a new pipe, returning a pair of file descriptors representing the readable and writable ends. Requires a switch for managing the operation's lifecycle. ```ocaml val pipe : sw:Eio.Std.Switch.t -> fd * fd pipe ~sw returns a pair r, w with the readable and writeable ends of a new pipe. ``` -------------------------------- ### Eio Get Random Bytes Source: https://ocaml-multicore.github.io/eio/eio_linux/Eio_linux/Low_level/index Fills a buffer with random bytes using the Linux getrandom system call. It may block if the system's random number generator is not yet initialized. ```ocaml val getrandom : Cstruct.t -> unit ``` -------------------------------- ### Configure Client Connection - Eio_mock.Net Source: https://ocaml-multicore.github.io/eio/eio/Eio_mock/Net/index Configures the behavior when a client attempts to connect to a mock network. This allows defining custom actions for incoming connections. ```ocaml val on_connect : t -> _ Eio.Net.stream_socket Handler.actions -> unit on_connect t actions configures what to do when a client tries to connect somewhere. ``` -------------------------------- ### Get switch error Source: https://ocaml-multicore.github.io/eio/eio/Eio/Switch/index Retrieves any exception associated with a switch's cancellation without raising it. Returns `None` if the switch is active or has no associated error. Also returns `Invalid_argument` if the switch is already finished. ```ocaml val get_error : t -> exn option ``` -------------------------------- ### OCaml Read All Convenience Wrapper Source: https://ocaml-multicore.github.io/eio/eio/Eio/Flow/index Provides a convenience wrapper read_all in OCaml to read an entire flow into a string, equivalent to Buf_read.(parse_exn take_all). ```ocaml val read_all : _ source -> string read_all src is a convenience wrapper to read an entire flow. It is the same as `Buf_read.(parse_exn take_all) src ~max_size:max_int` ``` -------------------------------- ### Eio Process Make_mgr Spawn Unix Source: https://ocaml-multicore.github.io/eio/eio/Eio_unix/Process/Make_mgr/index Provides the signature for `spawn_unix`, a specific function for spawning processes on Unix-like systems, with parameters for file descriptors and executable path. ```ocaml val spawn_unix : t -> sw:Eio.Std.Switch.t -> ?cwd:Eio.Fs.dir_ty Eio.Path.t -> env:string array -> fds:(int * Fd.t * Private.Fork_action.blocking) list -> executable:string -> string list -> ty Eio.Std.r ``` -------------------------------- ### Eio Time Mono: Get Current Monotonic Time Source: https://ocaml-multicore.github.io/eio/eio/Eio/Time/Mono/index Retrieves the current time from a monotonic clock. This is useful for measuring time intervals where accuracy is important and unaffected by system time changes. ```ocaml val now : _ t -> Mtime.t (* now t is the current time according to t. *) ```