1 
  
   2 
  
   3 
  
   4 
  
   5 
  
   6 using System;
  
   7 using System.Collections;
  
   8 
  
   9 namespace System.Xml.Serialization
  
  10 {
  
  11     delegate XmlSerializable* FactoryFunction();
  
  12 
  
  13     public class XmlClassRegistry
  
  14     {
  
  15         static XmlClassRegistry() : instance(new XmlClassRegistry())
  
  16         {
  
  17         }
  
  18         public static XmlClassRegistry& Instance()
  
  19         {
  
  20             return *instance;
  
  21         }
  
  22         private XmlClassRegistry()
  
  23         {
  
  24         }
  
  25         public Result<bool> Register(int classId, const string& className, FactoryFunction factoryFunction)
  
  26         {
  
  27             auto it = factoryMap.Find(classId);
  
  28             if (it != factoryMap.End())
  
  29             {
  
  30                 int errorId = AllocateError("class id " + ToString(classId) + " of class \'" + 
  
  31                     className + "\' conflicts with previously registered class \'" + classIdNameMap[classId] + 
  
  32                     "\', please change the name of one or the other to have different hash codes");
  
  33                 return Result<bool>(ErrorId(errorId));
  
  34             }
  
  35             classIdNameMap[classId] = className;
  
  36             factoryMap[classId] = factoryFunction;
  
  37             return Result<bool>(true);
  
  38         }
  
  39         public Result<XmlSerializable*> Create(int classId)
  
  40         {
  
  41             auto it = factoryMap.Find(classId);
  
  42             if (it != factoryMap.End())
  
  43             {
  
  44                 FactoryFunction factoryFunction = it->second;
  
  45                 return Result<XmlSerializable*>(factoryFunction());
  
  46             }
  
  47             else
  
  48             {
  
  49                 int errorId = AllocateError("class having id " + ToString(classId) + " not registered");
  
  50                 return Result<XmlSerializable*>(ErrorId(errorId));
  
  51             }
  
  52         }
  
  53         private static UniquePtr<XmlClassRegistry> instance;
  
  54         private Map<int, string> classIdNameMap;
  
  55         private Map<int, FactoryFunction> factoryMap;
  
  56     }
  
  57 
  
  58     [nodiscard]
  
  59     public Result<bool> XmlRegister<T>(int classId)
  
  60     {
  
  61         return XmlClassRegistry.Instance().Register(classId, T.StaticClassName(), T.Create);
  
  62     }
  
  63 }