Wayland-OCaml/protocol/lib/socket.ml

38 lines
1.5 KiB
OCaml
Raw Normal View History

2024-11-08 12:53:32 +01:00
type address = Unix.sockaddr
type socket = Unix.file_descr
let create () : socket IO.t =
try IO.return Unix.(socket PF_UNIX SOCK_STREAM 0) with
| Unix.Unix_error (code, call, param) -> IO.error code call param
let bind socket address : unit IO.t =
try IO.return (Unix.bind socket address) with
| Unix.Unix_error (code, call, param) -> IO.error code call param
let connect socket address : unit IO.t =
try IO.return (Unix.connect socket address) with
| Unix.Unix_error (code, call, param) -> IO.error code call param
let listen socket limit : unit IO.t =
try IO.return (Unix.listen socket limit) with
| Unix.Unix_error (code, call, param) -> IO.error code call param
let accept socket : socket IO.t =
try IO.return (Unix.accept socket |> fst) with
| Unix.Unix_error (code, call, param) -> IO.error code call param
let close socket : unit IO.t =
try IO.return (Unix.close socket) with
| Unix.Unix_error (code, call, param) -> IO.error code call param
let address () : address IO.t =
let open IO.Operators in
let runtime = IO.environment_variable "XDG_RUNTIME_DIR" in
let display = IO.environment_variable "WAYLAND_DISPLAY" in
let socket = IO.environment_variable "WAYLAND_SOCKET" in
let display = IO.recover display ~using:!"wayland-0" ~on:Unix.ENOENT in
let concat runtime display = Format.asprintf "%s/%s" runtime display in
let fallback = let* runtime in let+ display in concat runtime display in
let+ filename = IO.recover socket ~using:fallback ~on:Unix.ENOENT in
Unix.ADDR_UNIX filename