aboutsummaryrefslogtreecommitdiff
path: root/xmpp-vala/src/core/stanza_writer.vala
blob: aa94dec967231529493b956e74e00c4f8bdb6d6f (plain) (blame)
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
namespace Xmpp {

public class StanzaWriter {
    private OutputStream output;

    private Queue<SourceFuncWrapper> queue = new Queue<SourceFuncWrapper>();
    private bool running = false;

    public StanzaWriter.for_stream(OutputStream output) {
        this.output = output;
    }

    public async void write_node(StanzaNode node) throws XmlError {
        yield write_data(node.to_xml().data);
    }

    public async void write(string s) throws XmlError {
        yield write_data(s.data);
    }

    private async void write_data(uint8[] data) throws XmlError {
        if (running) {
            queue.push_tail(new SourceFuncWrapper(write_data.callback));
            yield;
        }
        running = true;
        try {
            yield output.write_all_async(data, 0, null, null);
            SourceFuncWrapper? sfw = queue.pop_head();
            if (sfw != null) {
                sfw.sfun();
            }
        } catch (GLib.Error e) {
            throw new XmlError.IO(@"IOError in GLib: $(e.message)");
        } finally {
            running = false;
        }
    }
}

public class SourceFuncWrapper : Object {

    public SourceFunc sfun;

    public SourceFuncWrapper(owned SourceFunc sfun) {
        this.sfun = (owned)sfun;
    }
}

}