-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathstring_stream.lua
76 lines (58 loc) · 1.49 KB
/
string_stream.lua
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
--
-- A "string stream" class that provides file-like operations on a string.
-- Inspired by https://gist.github.com/MikuAuahDark/e6428ac49248dd436f67c6c64fcec604
--
local class = require("class")
local StringStream = class.class()
function StringStream:_init(s)
self._buf = s
self._pos = 0
end
function StringStream:close()
-- Nothing to do here
end
function StringStream:seek(whence, offset)
local len = #self._buf
whence = whence or "cur"
if whence == "set" then
self._pos = offset or 0
elseif whence == "cur" then
self._pos = self._pos + (offset or 0)
elseif whence == "end" then
self._pos = len + (offset or 0)
else
error("bad argument #1 to 'seek' (invalid option '" .. tostring(whence) .. "')", 2)
end
if self._pos < 0 then
self._pos = 0
elseif self._pos > len then
self._pos = len
end
return self._pos
end
function StringStream:read(num)
local len = #self._buf
if num == "*all" then
if self._pos == len then
return nil
end
local ret = self._buf:sub(self._pos + 1)
self._pos = len
return ret
elseif num <= 0 then
return ""
end
local ret = self._buf:sub(self._pos + 1, self._pos + num)
if #ret == 0 then
return nil
end
self._pos = self._pos + num
if self._pos > len then
self._pos = len
end
return ret
end
function StringStream:pos()
return self._pos
end
return StringStream