BastliBridge

git clone git://xatko.vsos.ethz.ch/BastliBridge.git
Log | Files | Refs | Submodules | README

util.d (995B)


      1 module bastlibridge.util;
      2 import std.exception;
      3 import std.socket;
      4 import std.traits;
      5 import std.typecons;
      6 import std.range;
      7 
      8 void tryNTimes(alias func, alias errhandle)(uint N){
      9 	Exception last_e;
     10 	foreach(n;iota(0,N)){
     11 		try{
     12 			func();
     13 		}
     14 		catch(Exception e){
     15 			errhandle(e);
     16 			last_e=e;
     17 			continue;
     18 		}
     19 		return;
     20 	}
     21 	throw last_e;
     22 }
     23 unittest{
     24 	uint i=0;
     25 	auto func=(){
     26 		i++;
     27 		throw new Exception("derp");
     28 	};
     29 	import std.exception:assertThrown;
     30 	assertThrown(tryNTimes!(func, (e)=>assert(e.msg=="derp"))(5));
     31 	assert(i==5);
     32 }
     33 
     34 void wait(Socket sock) @trusted{
     35 	version(Windows){
     36 		static assert(false);
     37 	}
     38 	import core.sys.posix.sys.socket;
     39 	ubyte[4] buf;
     40 	recv(sock.handle, buf.ptr, buf.length, MSG_PEEK);
     41 }
     42 
     43 struct DeferredExecution(alias func, alias pred){
     44 	alias Args=Parameters!func;
     45 	Tuple!Args[] queue;
     46 	void exec(Args a){
     47 		if(!pred()){
     48 			queue~=tuple(a);
     49 		}
     50 		else{
     51 			func(a);
     52 		}
     53 	}
     54 	void dequeue(){
     55 		foreach(arg; queue){
     56 			func(arg.expand);
     57 		}
     58 		queue.length=0;
     59 	}
     60 }