2021-05-12 03:58:33 +00:00
|
|
|
local type InputStream = record
|
|
|
|
str: string
|
|
|
|
offset: number
|
|
|
|
refill: function(): string
|
2021-05-13 05:23:42 +00:00
|
|
|
|
|
|
|
new: function(InputStream): InputStream
|
|
|
|
new: function(InputStream, function(): string): InputStream
|
|
|
|
|
|
|
|
setRefill: function(InputStream, function(): string)
|
|
|
|
|
|
|
|
readCurrentCharacter: function(): string
|
|
|
|
advanceOffset: function(): string
|
2021-05-12 03:58:33 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
local istream_mt = {__index = InputStream}
|
|
|
|
|
|
|
|
function InputStream:_manageBuffer()
|
2021-05-13 05:23:42 +00:00
|
|
|
if not self.str then
|
|
|
|
self.str = self.refill()
|
|
|
|
self.offset = 1
|
|
|
|
end
|
|
|
|
if self.offset > #self.str + 1 then
|
2021-05-12 03:58:33 +00:00
|
|
|
self.str = self.refill()
|
|
|
|
self.offset = 1
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
-- constructors
|
|
|
|
function InputStream:new(): InputStream
|
|
|
|
return setmetatable(
|
|
|
|
{
|
|
|
|
string = "",
|
|
|
|
offset = 1
|
|
|
|
} as InputStream,
|
|
|
|
istream_mt)
|
|
|
|
end
|
2021-05-13 05:23:42 +00:00
|
|
|
function InputStream:new(refill: function(): string): InputStream
|
|
|
|
local mt = setmetatable(
|
|
|
|
{
|
|
|
|
string = "",
|
|
|
|
offset = 1
|
|
|
|
} as InputStream,
|
|
|
|
istream_mt)
|
|
|
|
mt:setRefill(refill)
|
|
|
|
return mt
|
|
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
2021-05-12 03:58:33 +00:00
|
|
|
|
|
|
|
-- setters/getters
|
|
|
|
function InputStream:setRefill(func: function(): string)
|
|
|
|
self.refill = func
|
|
|
|
end
|
|
|
|
|
|
|
|
--
|
|
|
|
function InputStream:readCurrentCharacter(): string
|
|
|
|
self:_manageBuffer()
|
2021-05-13 05:23:42 +00:00
|
|
|
return self.str:sub(self.offset, self.offset)
|
2021-05-12 03:58:33 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
function InputStream:advanceOffset(): string
|
|
|
|
self.offset = self.offset + 1
|
|
|
|
self:_manageBuffer()
|
2021-05-13 05:23:42 +00:00
|
|
|
return self.str:sub(self.offset, self.offset)
|
2021-05-12 03:58:33 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
return InputStream
|
|
|
|
|
|
|
|
|
|
|
|
|