forth-stuff/InputStream.tl

83 lines
1.5 KiB
Plaintext

local type InputStream = record
str: string
offset: number
refill: function(): string
new: function(InputStream, function(): string): InputStream
setRefill: function(InputStream, function(): string)
readCurrentCharacter: function(): string
advanceOffset: function(): string
end
local istream_mt = {__index = InputStream}
function InputStream:_manageBuffer()
if not self.str then
self.str = self.refill()
self.offset = 1
end
if self.offset > #self.str then
self.str = self.refill()
self.offset = 1
end
end
local function initial_stream(): string
return "DUMMY"
end
-- constructors
function InputStream:new(): InputStream
local mt = setmetatable(
{
string = "",
offset = 1,
refill = initial_stream
} as InputStream,
istream_mt)
mt:setRefill(initial_stream)
return mt
end
function InputStream:new(refill: function(): string): InputStream
refill = refill or initial_stream
local mt = setmetatable(
{
string = "",
offset = 1,
refill = function(): string return "DUMMY" end
} as InputStream,
istream_mt)
mt:setRefill(refill)
return mt
end
-- setters/getters
function InputStream:setRefill(func: function(): string)
self.refill = func
self:_manageBuffer()
end
--
function InputStream:readCurrentCharacter(): string
self:_manageBuffer()
return self.str:sub(self.offset, self.offset)
end
function InputStream:advanceOffset(): string
self:_manageBuffer()
local current_char = self.str:sub(self.offset, self.offset)
self.offset = self.offset + 1
return current_char
end
return InputStream