| 1 |
namespace Xmpp { |
| 2 |
|
| 3 |
public class StanzaWriter { |
| 4 |
private Cancellable? connection_cancellable; |
| 5 |
private OutputStream output; |
| 6 |
|
| 7 |
private Queue<SourceFuncWrapper> queue = new Queue<SourceFuncWrapper>(); |
| 8 |
private bool running = false; |
| 9 |
|
| 10 |
public StanzaWriter.for_stream(OutputStream output, Cancellable? cancellable = null) { |
| 11 |
this.output = output; |
| 12 |
this.connection_cancellable = cancellable; |
| 13 |
} |
| 14 |
|
| 15 |
public async void write_node(StanzaNode node, int io_priority = Priority.DEFAULT, Cancellable? cancellable = null) throws IOError { |
| 16 |
yield write_data(node.to_xml().data, io_priority, cancellable ?? connection_cancellable); |
| 17 |
} |
| 18 |
|
| 19 |
public async void write_nodes(StanzaNode node1, StanzaNode node2, int io_priority = Priority.DEFAULT, Cancellable? cancellable = null) throws IOError { |
| 20 |
var data1 = node1.to_xml().data; |
| 21 |
var data2 = node2.to_xml().data; |
| 22 |
|
| 23 |
uint8[] concat = new uint8[data1.length + data2.length]; |
| 24 |
int i = 0; |
| 25 |
foreach (var datum in data1) { |
| 26 |
concat[i++] = datum; |
| 27 |
} |
| 28 |
foreach (var datum in data2) { |
| 29 |
concat[i++] = datum; |
| 30 |
} |
| 31 |
|
| 32 |
yield write_data(concat, io_priority, cancellable ?? connection_cancellable); |
| 33 |
} |
| 34 |
|
| 35 |
public async void write(string s, int io_priority = Priority.DEFAULT, Cancellable? cancellable = null) throws IOError { |
| 36 |
yield write_data(s.data, io_priority, cancellable ?? connection_cancellable); |
| 37 |
} |
| 38 |
|
| 39 |
private async void write_data(owned uint8[] data, int io_priority = Priority.DEFAULT, Cancellable? cancellable = null) throws IOError { |
| 40 |
if (running) { |
| 41 |
queue.push_tail(new SourceFuncWrapper(write_data.callback)); |
| 42 |
yield; |
| 43 |
} |
| 44 |
running = true; |
| 45 |
try { |
| 46 |
yield output.write_all_async(data, io_priority, cancellable, null); |
| 47 |
} catch (IOError e) { |
| 48 |
if (!(e is IOError.CANCELLED)) { |
| 49 |
connection_cancellable.cancel(); |
| 50 |
} |
| 51 |
throw e; |
| 52 |
} catch (GLib.Error e) { |
| 53 |
connection_cancellable.cancel(); |
| 54 |
throw new IOError.FAILED("Error in GLib: %s".printf(e.message)); |
| 55 |
} finally { |
| 56 |
SourceFuncWrapper? sfw = queue.pop_head(); |
| 57 |
if (sfw != null) { |
| 58 |
sfw.sfun(); |
| 59 |
} else { |
| 60 |
running = false; |
| 61 |
} |
| 62 |
} |
| 63 |
} |
| 64 |
} |
| 65 |
|
| 66 |
public class SourceFuncWrapper : Object { |
| 67 |
|
| 68 |
public SourceFunc sfun; |
| 69 |
|
| 70 |
public SourceFuncWrapper(owned SourceFunc sfun) { |
| 71 |
this.sfun = (owned)sfun; |
| 72 |
} |
| 73 |
} |
| 74 |
|
| 75 |
} |