Add ipc module
This commit is contained in:
59
src/ipc.gleam
Normal file
59
src/ipc.gleam
Normal file
@@ -0,0 +1,59 @@
|
||||
import gleam/bytes_tree
|
||||
|
||||
pub type Socket
|
||||
|
||||
// https://www.erlang.org/doc/apps/kernel/inet#t:address_family/0
|
||||
// local socket
|
||||
type Local {
|
||||
Local(socket_path: String)
|
||||
}
|
||||
|
||||
type ModeValue {
|
||||
Binary
|
||||
}
|
||||
|
||||
type IPCOption {
|
||||
Active(Bool)
|
||||
Mode(ModeValue)
|
||||
}
|
||||
|
||||
pub type IPCError {
|
||||
IPCError(reason: String)
|
||||
}
|
||||
|
||||
pub fn connect(socket_path: String) -> Result(Socket, IPCError) {
|
||||
let options = [Mode(Binary), Active(False)]
|
||||
|
||||
// timeout in ms
|
||||
let timeout = 1000
|
||||
|
||||
gen_tcp_connect(Local(socket_path), 0, options, timeout)
|
||||
}
|
||||
|
||||
pub fn send(socket: Socket, message: String) -> Result(Nil, IPCError) {
|
||||
gen_tcp_send(socket, bytes_tree.from_string(message))
|
||||
}
|
||||
|
||||
pub fn close(socket: Socket) -> Nil {
|
||||
gen_tcp_close(socket)
|
||||
}
|
||||
|
||||
// https://www.erlang.org/doc/apps/kernel/gen_tcp.html#connect/4
|
||||
@external(erlang, "gen_tcp", "connect")
|
||||
fn gen_tcp_connect(
|
||||
address: Local,
|
||||
port: Int,
|
||||
options: List(IPCOption),
|
||||
timeout: Int,
|
||||
) -> Result(Socket, IPCError)
|
||||
|
||||
// https://www.erlang.org/doc/apps/kernel/gen_tcp.html#send/2
|
||||
@external(erlang, "ipc_ffi", "send")
|
||||
fn gen_tcp_send(
|
||||
socket: Socket,
|
||||
packet: bytes_tree.BytesTree,
|
||||
) -> Result(Nil, IPCError)
|
||||
|
||||
// https://www.erlang.org/doc/apps/kernel/gen_tcp.html#close/1
|
||||
@external(erlang, "gen_tcp", "close")
|
||||
fn gen_tcp_close(socket: Socket) -> Nil
|
||||
8
src/ipc_ffi.erl
Normal file
8
src/ipc_ffi.erl
Normal file
@@ -0,0 +1,8 @@
|
||||
-module(ipc_ffi).
|
||||
-export([send/2]).
|
||||
|
||||
send(Socket, Packet) ->
|
||||
case gen_tcp:send(Socket, Packet) of
|
||||
ok -> {ok, nil};
|
||||
Res -> Res
|
||||
end.
|
||||
Reference in New Issue
Block a user