summaryrefslogtreecommitdiff
path: root/dalos-luahandle.lua
blob: d3615fc31f613fc72fee97956c0badabe1fbce7d (plain)
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
dalosp.luahandle = {
    create = function (tab)
        local obj = {
            offset = 0,
            canread = function (self) return true end,
            canwrite = function (self) return false end,
            canseek = function (self) return true end,
            canwatch = function (self) return false end,
            tell = function (self) return self.offset end,
            getsize = function (self) return self.size end,
            getmodif = function (self) return 0 end,
            flush = function (self) return true end,
            seek = function (self, offset, wheel) 
                if wheel == SEEK_SET then
                    self.offset = offset
                elseif wheel == SEEK_CUR then
                    self.offset = self.offset + offset
                elseif wheel == SEEK_END then
                    self.offset = self.size + offset
                else
                    error "Unknown wheel"
                end
                if self.offset < 0 then self.offset = 0 end
                if self.offset >= self.size then self.offset = self.size end
                if self.do_seek then self:do_seek() end
                return self.offset
            end,
            read = function (self, userdata, count)
                count = math.min(count, self.size - self.offset)
                
                if count == 0 then
                    if self.got_eof then self.lh:close() end
                    self.got_eof = true
                    return 0
                end
                
                self.got_eof = false
                
                local r, t = self:do_read(count, userdata)
                self.offset = self.offset + r
                if self.post_read then self:post_read(r) end
                return r, t
            end,
        }
        for k, v in pairs(tab) do obj[k] = v end
        local newh = HandleLua(obj)
        obj.lh = newh
        return newh
    end,
}

dalos.luahandle = dalosp.luahandle.create