Created
March 5, 2016 11:21
-
-
Save ncannasse/8674575efe456cdca5ed to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package haxe; | |
class MainEvent { | |
var f : Void -> Void; | |
var prev : MainEvent; | |
var next : MainEvent; | |
public var priority(default,null) : Int; | |
public function new(f,p) { | |
this.f = f; | |
this.priority = p; | |
} | |
public inline function call() { | |
f(); | |
} | |
public inline function remove() { | |
f = null; | |
if( prev == null ) | |
@:privateAccess MainLoop.pending = next; | |
else | |
prev.next = next; | |
if( next != null ) | |
next.prev = prev; | |
} | |
} | |
class MainLoop { | |
static var pending : MainEvent = null; | |
public static function add( f : Void -> Void, priority = 0 ) : MainEvent @:privateAccess { | |
var e = new MainEvent(f,priority); | |
var head = pending; | |
if( head == null ) { | |
pending = e; | |
return e; | |
} | |
var prev = null; | |
while( head != null && head.priority > priority ) { | |
prev = head; | |
head = head.next; | |
} | |
if( prev == null ) { | |
e.next = head; | |
head.prev = e; | |
pending = e; | |
} else { | |
var n = prev.next; | |
if( n != null ) n.prev = e; | |
e.next = n; | |
prev.next = e; | |
e.prev = prev; | |
} | |
return e; | |
} | |
public static function run() @:privateAccess { | |
while( true ) { | |
var e = pending; | |
if( e == null ) break; | |
while( e != null ) { | |
var n = e.next; | |
if( e.f != null ) e.call(); | |
e = n; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment