Advertisement
Guest User

Untitled

a guest
Apr 7th, 2014
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.43 KB | None | 0 0
  1. module resourcemanager;
  2.  
  3. import std.file;
  4.  
  5. class ResourceManager{
  6.     /**
  7.         Add a resource to the manager
  8.     */
  9.     void AddRes(T)(in string sName, ref T res){
  10.         TypeInfo ti = typeid(T);
  11.         if(!(ti in m_loadedRes && sName in m_loadedRes[ti]))
  12.             m_loadedRes[typeid(T)][sName] = res;
  13.     }
  14.  
  15.     /**
  16.         Gets the resource with its name
  17.     */
  18.     ref T Get(T)(string sName){
  19.         TypeInfo ti = typeid(T);
  20.         if(ti in m_loadedRes && sName in m_loadedRes[ti]){
  21.             return *(cast(T*)&(m_loadedRes[ti][sName]));
  22.         }
  23.         throw new Exception("Resource '"~sName~"' not found");
  24.     }
  25.  
  26.     /**
  27.         Loads the resources contained in directory matching filePatern
  28.         The first argument of the resource constructor must be a DirEntry, followed by any arguments provided with ctorArgs
  29.     */
  30.     void LoadFromFiles(T, VT...)(in string directory, in string filePatern, in bool recursive, VT ctorArgs){
  31.         foreach(ref file ; dirEntries(directory, filePatern, recursive?SpanMode.depth:SpanMode.shallow)){
  32.             if(file.isFile){
  33.                 AddRes!T(file.name, new T(file, ctorArgs));
  34.             }
  35.         }
  36.     }
  37.  
  38. private:
  39.     Object[string][TypeInfo] m_loadedRes;
  40. }
  41.  
  42. version( unittest )
  43. class Foo{
  44.     this(){}
  45.     this(DirEntry file, int i){s = file.name;}
  46.     string s = "goto bar";
  47. }  
  48.  
  49. unittest {
  50.  
  51.     auto rm = new ResourceManager;
  52.  
  53.     auto foo = new Foo;
  54.     rm.AddRes!Foo("yolo", foo);
  55.  
  56.     assert(rm.Get!Foo("yolo") == foo);
  57.     assert(rm.Get!Foo("yolo") is foo);
  58.  
  59.     rm.LoadFromFiles!Foo(".", "dub.json", true, 5);
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement