]> git.sesse.net Git - remoteglot/blob - Engine.pm
Small refactoring.
[remoteglot] / Engine.pm
1 #! /usr/bin/perl
2 use strict;
3 use warnings;
4 use IPC::Open2;
5
6 package Engine;
7
8 sub open {
9         my ($class, $cmdline, $tag) = @_;
10
11         my ($uciread, $uciwrite);
12         my $pid = IPC::Open2::open2($uciread, $uciwrite, $cmdline);
13
14         my $engine = {
15                 pid => $pid,
16                 read => $uciread,
17                 readbuf => '',
18                 write => $uciwrite,
19                 info => {},
20                 ids => {},
21                 tag => $tag,
22         };
23
24         return bless $engine;
25 }
26
27 sub print {
28         my ($engine, $msg) = @_;
29         print { $engine->{'write'} } "$msg\n";
30 }
31
32 sub read_lines {
33         my $engine = shift;
34
35         # 
36         # Read until we've got a full line -- if the engine sends part of
37         # a line and then stops we're pretty much hosed, but that should
38         # never happen.
39         #
40         while ($engine->{'readbuf'} !~ /\n/) {
41                 my $tmp;
42                 my $ret = sysread $engine->{'read'}, $tmp, 4096;
43
44                 if (!defined($ret)) {
45                         next if ($!{EINTR});
46                         die "error in reading from the UCI engine: $!";
47                 } elsif ($ret == 0) {
48                         die "EOF from UCI engine";
49                 }
50
51                 $engine->{'readbuf'} .= $tmp;
52         }
53
54         # Blah.
55         my @lines = ();
56         while ($engine->{'readbuf'} =~ s/^([^\n]*)\n//) {
57                 my $line = $1;
58                 $line =~ tr/\r\n//d;
59                 push @lines, $line;
60         }
61         return @lines;
62 }
63
64
65
66 1;