File: socket_stream.lua

package info (click to toggle)
lua-nvim 0.2.4-1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 168 kB
  • sloc: makefile: 67; ansic: 32
file content (52 lines) | stat: -rw-r--r-- 1,028 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
local uv = require('luv')

local SocketStream = {}
SocketStream.__index = SocketStream

function SocketStream.open(file)
  local socket = uv.new_pipe(false)
  local self = setmetatable({
    _socket = socket,
    _stream_error = nil
  }, SocketStream)
  uv.pipe_connect(socket, file, function (err)
    self._stream_error = self._stream_error or err
  end)
  return self
end

function SocketStream:write(data)
  if self._stream_error then
    error(self._stream_error)
  end
  uv.write(self._socket, data, function(err)
    if err then
      error(self._stream_error or err)
    end
  end)
end

function SocketStream:read_start(cb)
  if self._stream_error then
    error(self._stream_error)
  end
  uv.read_start(self._socket, function(err, chunk)
    if err then
      error(err)
    end
    cb(chunk)
  end)
end

function SocketStream:read_stop()
  if self._stream_error then
    error(self._stream_error)
  end
  uv.read_stop(self._socket)
end

function SocketStream:close()
  uv.close(self._socket)
end

return SocketStream