-
-
Notifications
You must be signed in to change notification settings - Fork 373
/
Socket.pm
62 lines (54 loc) · 1.8 KB
/
Socket.pm
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
58
59
60
61
62
my role IO::Socket {
has $!PIO;
has $!buffer = '';
method recv (Cool $chars = $Inf) {
fail('Socket not available') unless $!PIO;
if $!buffer.chars < $chars {
my str $r = $!PIO.recv;
$r = pir::trans_encoding__Ssi($r,
pir::find_encoding__Is('utf8'));
$!buffer ~= nqp::p6box_s($r);
}
if $!buffer.chars > $chars {
my $rec = $!buffer.substr(0, $chars);
$!buffer = $!buffer.substr($chars);
$rec
} else {
my $rec = $!buffer;
$!buffer = '';
$rec;
}
}
method read(IO::Socket:D: Cool $bufsize as Int) {
fail('Socket not available') unless $!PIO;
my $res = Buf.new;
my $buf;
repeat {
$buf := nqp::create(Buf);
my Mu $parrot_buf := pir::new__PS('ByteBuffer');
pir::set__vPS($parrot_buf, $!PIO.read(nqp::unbox_i($bufsize - $res.elems)));
nqp::bindattr_s($buf, Buf, '$!buffer',
$parrot_buf.get_string('binary'));
$res = $res ~ $buf;
} while $res.elems < $bufsize && $buf.elems;
$res;
}
method poll(Int $bitmask, $seconds) {
$!PIO.poll(
nqp::unbox_i($bitmask), nqp::unbox_i($seconds.floor),
nqp::unbox_i((($seconds - $seconds.floor) * 1000).Int)
);
}
method send (Cool $string as Str) {
fail("Not connected") unless $!PIO;
$!PIO.send(nqp::unbox_s($string)).Bool;
}
method write(Buf:D $buf) {
fail('Socket not available') unless $!PIO;
$!PIO.send(nqp::getattr(nqp::p6decont($buf), Buf, '$!buffer').get_string('binary'));
}
method close () {
fail("Not connected!") unless $!PIO;
$!PIO.close().Bool
}
}