4
-- Sample LGI application for Gio Streams.
7
local lgi = require 'lgi'
8
local bytes = require 'bytes'
12
local log = lgi.log.domain('lgiostream')
14
local app = Gio.Application.new('org.lgi.samples.giostream', 0)
16
local function read_sync(file)
17
local info = assert(file:query_info('standard::size', 0))
18
local buffer = bytes.new(info:get_size())
19
local stream = assert(file:read(nil))
20
local read = assert(stream:read_all(buffer, #buffer))
21
return tostring(buffer):sub(1,read)
24
local function read_async(file)
26
file:query_info_async('standard::size', 0, GLib.PRIORITY_DEFAULT, nil,
28
local info = assert(file.query_info_finish(coroutine.yield()))
29
local buffer = bytes.new(info:get_size())
30
file:read_async(GLib.PRIORITY_DEFAULT, nil, coroutine.running())
31
local stream = assert(file.read_finish(coroutine.yield()))
32
local read_buffers = {}
33
local remaining = #buffer
34
while remaining > 0 do
35
stream:read_async(buffer, remaining, GLib.PRIORITY_DEFAULT, nil,
37
local read_now, err = stream.read_finish(coroutine.yield())
38
assert(read_now >= 0, err)
39
read_buffers[#read_buffers + 1] = tostring(buffer):sub(1, read_now)
40
remaining = remaining - read_now
43
return table.concat(read_buffers)
46
local function write_sync(file, contents)
47
local stream = assert(file:create(0))
48
assert(stream:write_all(contents))
51
local function write_async(file, contents)
52
file:create_async(0, GLib.PRIORITY_DEFAULT, nil, coroutine.running())
53
local stream = assert(file.create_finish(coroutine.yield()))
55
while pos <= #contents do
56
stream:write_async(contents:sub(pos), GLib.PRIORITY_DEFAULT, nil,
58
local wrote, err = stream.write_finish(coroutine.yield())
59
assert(wrote >= 0, err)
64
function app:on_activate()
65
local source_file = Gio.File.new_for_commandline_arg(arg[0])
67
local function perform(read_op, write_op, target_file)
69
print('Starting:', target_file:get_basename())
70
local contents = read_op(source_file)
72
write_op(target_file, contents)
73
local contents_copied = read_op(target_file)
74
assert(contents == contents_copied)
75
assert(target_file:delete())
76
print('Success:', target_file:get_basename())
80
-- Perform sync variant of the test.
81
perform(read_sync, write_sync, Gio.File.new_for_path('test-sync'))
83
-- Perform async variant of the test inside the coroutine; start
86
local coro = coroutine.create(perform)
87
coroutine.resume(coro, read_async, write_async,
88
Gio.File.new_for_path('test-async-' .. i))
92
app:run { arg[0], ... }