File: stream.d

package info (click to toggle)
sambamba 1.0.1%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,900 kB
  • sloc: javascript: 552; sh: 220; python: 166; ruby: 147; makefile: 104; lisp: 85
file content (57 lines) | stat: -rw-r--r-- 1,160 bytes parent folder | download
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
51
52
53
54
55
56
57
// Written in the D programming language.

/**
 * Stream deserialization usage
 */

import std.array;
import std.concurrency;
import std.exception;
import std.stdio;

import msgpack;


void deserializer()
{
    auto unpacker = StreamingUnpacker(cast(ubyte[])null);
    bool endLoop;

    while (true) {
        receive((immutable(ubyte)[] data) { unpacker.feed(data); },
                (bool end) { endLoop = end; });

        if (endLoop)
            break;

        while (unpacker.execute()) {
            auto unpacked = unpacker.purge();
            writeln("Type:  ", unpacked.type);
            writeln("Value: ", unpacked.as!(string));
        }

        if (unpacker.size >= 100)
            throw new Exception("Too large!");
    }
}


void main()
{
    string message = "Hell";
    foreach (i; 0..93)  // Throws Exception if 94
        message ~= 'o';

    auto packed = pack(message);
    auto data   = packed.assumeUnique();
    auto tid    = spawn(&deserializer);

    while (!data.empty) {
        auto limit = data.length >= 10 ? 10 : data.length;

        tid.send(data[0..limit]);
        data = data[limit..$];
    }

    tid.send(true);
}