Permalink
Browse files

Initial commit

  • Loading branch information...
0 parents commit 05d7412c49f43c5d094b77447b3e04083f7a3889 @tadzik committed Oct 22, 2011
Showing with 127 additions and 0 deletions.
  1. +2 −0 README
  2. +74 −0 lib/MuEvent.pm
  3. +51 −0 test.pl
2 README
@@ -0,0 +1,2 @@
+Stupid event loop, interface modeled after Perl 5's AnyEvent.
+More docs and tests coming soon.
74 lib/MuEvent.pm
@@ -0,0 +1,74 @@
+module MuEvent;
+
+my @timers;
+my @sockets;
+my @idlers;
+my $since;
+
+sub clock {
+ nqp::p6box_n(pir::time__n())
+}
+
+our sub timer(:&cb!, :$after!, :$interval) {
+ @timers.push: { :$after, :$interval, :&cb, keep => 1, lastrun => 0 };
+}
+
+our sub socket(:&cb!, :$socket!, :$poll where 'r'|'w') {
+ my $p = $poll eq 'r' ?? 1 !! 2;
+ @sockets.push: { :$socket, :poll($p), :&cb, keep => 1 };
+}
+
+sub run-timers {
+ my $seen-action = False;
+ for @timers -> $e is rw {
+ if clock() > $since + $e<after> {
+ if defined $e<interval> {
+ if clock() > $e<lastrun> + $e<interval> {
+ $e<cb>.();
+ $seen-action = True;
+ $e<lastrun> = clock();
+ }
+ } else {
+ $e<cb>.();
+ $seen-action = True;
+ $e<keep> = 0;
+ }
+ }
+ }
+ my @tmp = @timers.grep: { $_<keep> == 1 };
+ @timers = @tmp;
+ return $seen-action;
+}
+
+sub run-sockets {
+ my $seen-action = False;
+ for @sockets -> $e is rw {
+ if $e<socket>.poll($e<poll>, 0.01) {
+ $e<cb>.() or $e<keep> = 0;
+ $seen-action = True;
+ }
+ }
+ my @tmp = @sockets.grep: { $_<keep> == 1 };
+ @sockets = @tmp;
+ return $seen-action;
+}
+
+our sub idle(:&cb!) {
+ @idlers.push(&cb);
+}
+
+our sub run {
+ $since = clock();
+ loop {
+ run-once()
+ }
+}
+
+sub run-once {
+ my $seen-action = False;
+ $seen-action = run-timers();
+ $seen-action = run-sockets();
+ if not $seen-action {
+ for @idlers { $_.() }
+ }
+}
51 test.pl
@@ -0,0 +1,51 @@
+use MuEvent;
+
+MuEvent::timer(
+ after => 2,
+ cb => sub { say "2 seconds have passed" },
+);
+
+MuEvent::timer(
+ after => 0,
+ interval => 5,
+ cb => sub { say "I run every 5 seconds" },
+);
+
+MuEvent::idle(
+ cb => sub { say "Nothing better to do"; sleep 1 },
+);
+
+my $l = IO::Socket::INET.new(
+ :localhost('localhost'),
+ :localport(6666),
+ :listen
+);
+
+MuEvent::socket(
+ socket => $l,
+ poll => 'r',
+ cb => &socket-cb,
+);
+
+sub socket-cb {
+ say "Oh gosh a client!";
+ my $s = $l.accept;
+ MuEvent::socket(
+ socket => $s,
+ poll => 'r',
+ cb => sub {
+ my $a = $s.recv;
+ if $a {
+ print "Incoming transmission: $a";
+ return True;
+ } else {
+ say "Client disconnected";
+ $s.close;
+ return False;
+ }
+ }
+ );
+ return True;
+}
+
+MuEvent::run;

0 comments on commit 05d7412

Please sign in to comment.