1 /** 2 * Copyright: © 2012-2014 Anton Gushcha 3 * License: Subject to the terms of the MIT license, as written in the included LICENSE file. 4 * Authors: NCrashed <ncrashed@gmail.com>, 5 * LeMarwin <lemarwin42@gmail.com>, 6 * Nazgull09 <nazgull90@gmail.com> 7 */ 8 module devol.operatormng; 9 10 import std.stdio; 11 import std.random; 12 import std.array; 13 import std.conv; 14 15 import devol.singleton; 16 17 public 18 { 19 import devol.operator; 20 import devol.type; 21 } 22 23 class OperatorMng : Singleton!OperatorMng 24 { 25 static this() 26 { 27 new OperatorMng(); 28 } 29 30 void registerOperator(T)() 31 if ( __traits(compiles, "Operator t = new T()" ) ) 32 { 33 Operator t = new T(); 34 35 if ( t.name in operators ) 36 throw new Exception(text("Operator ", t.name, " is already registered!")); 37 38 operators[t.name] = t; 39 } 40 41 Operator getOperator(string name) 42 { 43 if ( name !in operators ) 44 throw new Exception(text("Operator ", name," isn't registered!")); 45 46 return operators[name]; 47 } 48 49 Operator getRndOperator() 50 { 51 if (operators.keys.empty) return null; 52 53 return operators.values[uniform(0,operators.length)]; 54 } 55 56 Operator getRndOperator(Type retType) 57 { 58 if (operators.keys.empty || retType is null) return null; 59 60 auto buff = new Operator[0]; 61 62 foreach(op; operators) 63 { 64 if ( retType.isConvertable(op.rtype) ) 65 buff ~= op; 66 } 67 if (buff.empty) return null; 68 69 return buff[uniform(0,buff.length)]; 70 } 71 72 @property string[] strings() 73 { 74 auto ret = new string[0]; 75 foreach(s; operators.keys) 76 { 77 ret ~= s; 78 } 79 return ret; 80 } 81 82 int opApply(int delegate(ref Operator) dg) 83 { 84 int result = 0; 85 86 foreach(operator; operators) 87 { 88 result = dg(operator); 89 if (result) break; 90 } 91 return result; 92 } 93 94 protected Operator[string] operators; 95 }