Procházet zdrojové kódy

还剩protobuf-net的问题了

tanghai před 4 roky
rodič
revize
a7441b5f0f
100 změnil soubory, kde provedl 53 přidání a 19746 odebrání
  1. 0 15
      Client-Server.sln
  2. 0 4
      Config/AIConfigCategory.bytes
  3. 0 2
      Config/StartMachineConfigCategory.bytes
  4. 0 3
      Config/StartProcessConfigCategory.bytes
  5. binární
      Config/StartSceneConfigCategory.bytes
  6. 0 3
      Config/StartZoneConfigCategory.bytes
  7. 0 2
      Config/UnitConfigCategory.bytes
  8. 0 1
      Robot/Model/Robot.Model.csproj
  9. 3 9
      Server/App/Template.txt
  10. 1 1
      Server/Model/ExcelExporter/ExcelExporter.cs
  11. 8 14
      Server/Model/Generate/Config/AIConfig.cs
  12. 7 13
      Server/Model/Generate/Config/StartMachineConfig.cs
  13. 7 13
      Server/Model/Generate/Config/StartProcessConfig.cs
  14. 9 15
      Server/Model/Generate/Config/StartSceneConfig.cs
  15. 6 12
      Server/Model/Generate/Config/StartZoneConfig.cs
  16. 9 15
      Server/Model/Generate/Config/UnitConfig.cs
  17. 1 1
      Server/Model/Generate/ConfigPartial/StartProcessConfig.cs
  18. 1 1
      Server/Model/Generate/ConfigPartial/StartSceneConfig.cs
  19. 0 1
      Server/Model/Server.Model.csproj
  20. 1 0
      ThirdParty/ShareLib/ShareLib.csproj
  21. 0 712
      ThirdParty/protobuf-net/BclHelpers.cs
  22. 0 78
      ThirdParty/protobuf-net/BufferExtension.cs
  23. 0 149
      ThirdParty/protobuf-net/BufferPool.cs
  24. 0 33
      ThirdParty/protobuf-net/CallbackAttributes.cs
  25. 0 1435
      ThirdParty/protobuf-net/Compiler/CompilerContext.cs
  26. 0 7
      ThirdParty/protobuf-net/Compiler/CompilerDelegates.cs
  27. 0 58
      ThirdParty/protobuf-net/Compiler/Local.cs
  28. 0 49
      ThirdParty/protobuf-net/DataFormat.cs
  29. 0 176
      ThirdParty/protobuf-net/DiscriminatedUnion.Serializable.cs
  30. 0 416
      ThirdParty/protobuf-net/DiscriminatedUnion.cs
  31. 0 284
      ThirdParty/protobuf-net/Extensible.cs
  32. 0 118
      ThirdParty/protobuf-net/ExtensibleUtil.cs
  33. binární
      ThirdParty/protobuf-net/GlobalSuppressions.cs
  34. 0 638
      ThirdParty/protobuf-net/Helpers.cs
  35. 0 23
      ThirdParty/protobuf-net/IExtensible.cs
  36. 0 58
      ThirdParty/protobuf-net/IExtension.cs
  37. 0 13
      ThirdParty/protobuf-net/IProtoInputT.cs
  38. 0 55
      ThirdParty/protobuf-net/IProtoOutputT.cs
  39. 0 29
      ThirdParty/protobuf-net/ImplicitFields.cs
  40. 0 44
      ThirdParty/protobuf-net/KeyValuePairProxy.cs
  41. 0 108
      ThirdParty/protobuf-net/Meta/AttributeMap.cs
  42. 0 267
      ThirdParty/protobuf-net/Meta/BasicList.cs
  43. 0 110
      ThirdParty/protobuf-net/Meta/CallbackSet.cs
  44. 0 2160
      ThirdParty/protobuf-net/Meta/MetaType.cs
  45. 0 17
      ThirdParty/protobuf-net/Meta/ProtoSyntax.cs
  46. 0 2006
      ThirdParty/protobuf-net/Meta/RuntimeTypeModel.cs
  47. 0 97
      ThirdParty/protobuf-net/Meta/SubType.cs
  48. 0 64
      ThirdParty/protobuf-net/Meta/TypeFormatEventArgs.cs
  49. 0 45
      ThirdParty/protobuf-net/Meta/TypeModel.InputOutput.cs
  50. 0 1696
      ThirdParty/protobuf-net/Meta/TypeModel.cs
  51. 0 855
      ThirdParty/protobuf-net/Meta/ValueMember.cs
  52. 0 190
      ThirdParty/protobuf-net/NetObjectCache.cs
  53. 0 26
      ThirdParty/protobuf-net/PrefixStyle.cs
  54. 0 175
      ThirdParty/protobuf-net/ProtoContractAttribute.cs
  55. 0 13
      ThirdParty/protobuf-net/ProtoConverterAttribute.cs
  56. 0 36
      ThirdParty/protobuf-net/ProtoEnumAttribute.cs
  57. 0 30
      ThirdParty/protobuf-net/ProtoException.cs
  58. 0 40
      ThirdParty/protobuf-net/ProtoIgnoreAttribute.cs
  59. 0 60
      ThirdParty/protobuf-net/ProtoIncludeAttribute.cs
  60. 0 29
      ThirdParty/protobuf-net/ProtoMapAttribute.cs
  61. 0 228
      ThirdParty/protobuf-net/ProtoMemberAttribute.cs
  62. 0 1436
      ThirdParty/protobuf-net/ProtoReader.cs
  63. 0 1003
      ThirdParty/protobuf-net/ProtoWriter.cs
  64. 0 76
      ThirdParty/protobuf-net/SerializationContext.cs
  65. 0 514
      ThirdParty/protobuf-net/Serializer.cs
  66. 0 310
      ThirdParty/protobuf-net/Serializers/ArrayDecorator.cs
  67. 0 59
      ThirdParty/protobuf-net/Serializers/BlobSerializer.cs
  68. 0 41
      ThirdParty/protobuf-net/Serializers/BooleanSerializer.cs
  69. 0 42
      ThirdParty/protobuf-net/Serializers/ByteSerializer.cs
  70. 0 32
      ThirdParty/protobuf-net/Serializers/CharSerializer.cs
  71. 0 88
      ThirdParty/protobuf-net/Serializers/CompiledSerializer.cs
  72. 0 65
      ThirdParty/protobuf-net/Serializers/DateTimeSerializer.cs
  73. 0 42
      ThirdParty/protobuf-net/Serializers/DecimalSerializer.cs
  74. 0 259
      ThirdParty/protobuf-net/Serializers/DefaultValueDecorator.cs
  75. 0 42
      ThirdParty/protobuf-net/Serializers/DoubleSerializer.cs
  76. 0 267
      ThirdParty/protobuf-net/Serializers/EnumSerializer.cs
  77. 0 104
      ThirdParty/protobuf-net/Serializers/FieldDecorator.cs
  78. 0 43
      ThirdParty/protobuf-net/Serializers/GuidSerializer.cs
  79. 0 64
      ThirdParty/protobuf-net/Serializers/IProtoSerializer.cs
  80. 0 20
      ThirdParty/protobuf-net/Serializers/IProtoTypeSerializer.cs
  81. 0 10
      ThirdParty/protobuf-net/Serializers/ISerializerProxy.cs
  82. 0 304
      ThirdParty/protobuf-net/Serializers/ImmutableCollectionDecorator.cs
  83. 0 42
      ThirdParty/protobuf-net/Serializers/Int16Serializer.cs
  84. 0 42
      ThirdParty/protobuf-net/Serializers/Int32Serializer.cs
  85. 0 41
      ThirdParty/protobuf-net/Serializers/Int64Serializer.cs
  86. 0 579
      ThirdParty/protobuf-net/Serializers/ListDecorator.cs
  87. 0 298
      ThirdParty/protobuf-net/Serializers/MapDecorator.cs
  88. 0 76
      ThirdParty/protobuf-net/Serializers/MemberSpecifiedDecorator.cs
  89. 0 64
      ThirdParty/protobuf-net/Serializers/NetObjectSerializer.cs
  90. 0 167
      ThirdParty/protobuf-net/Serializers/NullDecorator.cs
  91. 0 111
      ThirdParty/protobuf-net/Serializers/ParseableSerializer.cs
  92. 0 167
      ThirdParty/protobuf-net/Serializers/PropertyDecorator.cs
  93. 0 24
      ThirdParty/protobuf-net/Serializers/ProtoDecoratorBase.cs
  94. 0 90
      ThirdParty/protobuf-net/Serializers/ReflectedUriDecorator.cs
  95. 0 45
      ThirdParty/protobuf-net/Serializers/SByteSerializer.cs
  96. 0 45
      ThirdParty/protobuf-net/Serializers/SingleSerializer.cs
  97. 0 41
      ThirdParty/protobuf-net/Serializers/StringSerializer.cs
  98. 0 138
      ThirdParty/protobuf-net/Serializers/SubItemSerializer.cs
  99. 0 157
      ThirdParty/protobuf-net/Serializers/SurrogateSerializer.cs
  100. 0 46
      ThirdParty/protobuf-net/Serializers/SystemTypeSerializer.cs

+ 0 - 15
Client-Server.sln

@@ -33,8 +33,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Robot.Hotfix", "Robot\Hotfi
 EndProject
 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ThirdParty", "ThirdParty", "{D885C55E-8E9B-4837-938D-15A919188607}"
 EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "protobuf-net", "ThirdParty\protobuf-net\protobuf-net.csproj", "{919D81EA-AE2A-4B5E-B965-300582C7B546}"
-EndProject
 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnityEngine", "ThirdParty\UnityEngine\UnityEngine.csproj", "{9F66DBC1-55AB-40D4-B4C4-B707CB39E624}"
 EndProject
 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShareLib", "ThirdParty\ShareLib\ShareLib.csproj", "{EC8FBBC4-59C8-438C-AE16-1762C269B928}"
@@ -183,18 +181,6 @@ Global
 		{57098A03-52D4-455F-9B88-3A0951D651DF}.Release|x64.Build.0 = Release|Any CPU
 		{57098A03-52D4-455F-9B88-3A0951D651DF}.Release|x86.ActiveCfg = Release|Any CPU
 		{57098A03-52D4-455F-9B88-3A0951D651DF}.Release|x86.Build.0 = Release|Any CPU
-		{919D81EA-AE2A-4B5E-B965-300582C7B546}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
-		{919D81EA-AE2A-4B5E-B965-300582C7B546}.Debug|Any CPU.Build.0 = Debug|Any CPU
-		{919D81EA-AE2A-4B5E-B965-300582C7B546}.Debug|x64.ActiveCfg = Debug|Any CPU
-		{919D81EA-AE2A-4B5E-B965-300582C7B546}.Debug|x64.Build.0 = Debug|Any CPU
-		{919D81EA-AE2A-4B5E-B965-300582C7B546}.Debug|x86.ActiveCfg = Debug|Any CPU
-		{919D81EA-AE2A-4B5E-B965-300582C7B546}.Debug|x86.Build.0 = Debug|Any CPU
-		{919D81EA-AE2A-4B5E-B965-300582C7B546}.Release|Any CPU.ActiveCfg = Release|Any CPU
-		{919D81EA-AE2A-4B5E-B965-300582C7B546}.Release|Any CPU.Build.0 = Release|Any CPU
-		{919D81EA-AE2A-4B5E-B965-300582C7B546}.Release|x64.ActiveCfg = Release|Any CPU
-		{919D81EA-AE2A-4B5E-B965-300582C7B546}.Release|x64.Build.0 = Release|Any CPU
-		{919D81EA-AE2A-4B5E-B965-300582C7B546}.Release|x86.ActiveCfg = Release|Any CPU
-		{919D81EA-AE2A-4B5E-B965-300582C7B546}.Release|x86.Build.0 = Release|Any CPU
 		{9F66DBC1-55AB-40D4-B4C4-B707CB39E624}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
 		{9F66DBC1-55AB-40D4-B4C4-B707CB39E624}.Debug|Any CPU.Build.0 = Debug|Any CPU
 		{9F66DBC1-55AB-40D4-B4C4-B707CB39E624}.Debug|x64.ActiveCfg = Debug|Any CPU
@@ -247,7 +233,6 @@ Global
 		{3743C043-A5B7-4D63-8009-19E8C2FB89D4} = {0CFA1E78-9E36-48A3-A134-6EC704815CC8}
 		{405D6513-704F-4715-ACC9-F1C0C07EE39F} = {0CFA1E78-9E36-48A3-A134-6EC704815CC8}
 		{57098A03-52D4-455F-9B88-3A0951D651DF} = {0CFA1E78-9E36-48A3-A134-6EC704815CC8}
-		{919D81EA-AE2A-4B5E-B965-300582C7B546} = {D885C55E-8E9B-4837-938D-15A919188607}
 		{9F66DBC1-55AB-40D4-B4C4-B707CB39E624} = {D885C55E-8E9B-4837-938D-15A919188607}
 		{EC8FBBC4-59C8-438C-AE16-1762C269B928} = {D885C55E-8E9B-4837-938D-15A919188607}
 		{5910FA29-5797-199C-985B-FC9FC473328E} = {914C77C9-212A-4DD0-8D9A-074620E77FAA}

+ 0 - 4
Config/AIConfigCategory.bytes

@@ -1,4 +0,0 @@
-
-e"	AI_Attack
-f"	AI_XunLuo
-É"	AI_XunLuo

+ 0 - 2
Config/StartMachineConfigCategory.bytes

@@ -1,2 +0,0 @@
-
-	127.0.0.1	127.0.0.1"10000

+ 0 - 3
Config/StartProcessConfigCategory.bytes

@@ -1,3 +0,0 @@
-
-¡œ"Server
-¢œ"Robot

binární
Config/StartSceneConfigCategory.bytes


+ 0 - 3
Config/StartZoneConfigCategory.bytes

@@ -1,3 +0,0 @@
-
-mongdb://127.0.0.1ET1
-mongdb://127.0.0.1ET2

+ 0 - 2
Config/UnitConfigCategory.bytes

@@ -1,2 +0,0 @@
-
-/é	米克尔带有强力攻击技能 (²0D

+ 0 - 1
Robot/Model/Robot.Model.csproj

@@ -112,7 +112,6 @@
         </Compile>
     </ItemGroup>
     <ItemGroup>
-      <ProjectReference Include="..\..\ThirdParty\protobuf-net\protobuf-net.csproj" />
       <ProjectReference Include="..\..\ThirdParty\ShareLib\ShareLib.csproj" />
       <ProjectReference Include="..\..\ThirdParty\UnityEngine\UnityEngine.csproj" />
     </ItemGroup>

+ 3 - 9
Server/App/Template.txt

@@ -24,15 +24,15 @@ namespace ET
             Instance = this;
         }
 		
-		[ProtoAfterDeserialization]
-        public void AfterDeserialization()
+        public override void EndInit()
         {
             foreach ((ConfigName) config in list)
             {
                 this.dict.Add(config.Id, config);
             }
             list.Clear();
-            this.EndInit();
+            
+            this.AfterEndInit();
         }
 		
         public (ConfigName) Get(int id)
@@ -71,11 +71,5 @@ namespace ET
 	public partial class (ConfigName): ProtoObject, IConfig
 	{
 (Fields)
-
-		[ProtoAfterDeserialization]
-        public void AfterDeserialization()
-        {
-            this.EndInit();
-        }
 	}
 }

+ 1 - 1
Server/Model/ExcelExporter/ExcelExporter.cs

@@ -157,7 +157,7 @@ namespace ET
                 {
                     continue;
                 }
-                sb.Append($"\t\t[ProtoMember({i + 1}, IsRequired  = true)]\n");
+                sb.Append($"\t\t[ProtoMember({i + 1})]\n");
                 sb.Append($"\t\tpublic {headInfo.FieldType} {headInfo.FieldName} {{ get; set; }}\n");
             }
             string content = template.Replace("(ConfigName)", protoName).Replace(("(Fields)"), sb.ToString());

+ 8 - 14
Server/Model/Generate/Config/AIConfig.cs

@@ -24,15 +24,15 @@ namespace ET
             Instance = this;
         }
 		
-		[ProtoAfterDeserialization]
-        public void AfterDeserialization()
+        public override void EndInit()
         {
             foreach (AIConfig config in list)
             {
                 this.dict.Add(config.Id, config);
             }
             list.Clear();
-            this.EndInit();
+            
+            this.AfterEndInit();
         }
 		
         public AIConfig Get(int id)
@@ -70,22 +70,16 @@ namespace ET
     [ProtoContract]
 	public partial class AIConfig: ProtoObject, IConfig
 	{
-		[ProtoMember(1, IsRequired  = true)]
+		[ProtoMember(1)]
 		public int Id { get; set; }
-		[ProtoMember(2, IsRequired  = true)]
+		[ProtoMember(2)]
 		public int AIConfigId { get; set; }
-		[ProtoMember(3, IsRequired  = true)]
+		[ProtoMember(3)]
 		public int Order { get; set; }
-		[ProtoMember(4, IsRequired  = true)]
+		[ProtoMember(4)]
 		public string Name { get; set; }
-		[ProtoMember(5, IsRequired  = true)]
+		[ProtoMember(5)]
 		public int[] NodeParams { get; set; }
 
-
-		[ProtoAfterDeserialization]
-        public void AfterDeserialization()
-        {
-            this.EndInit();
-        }
 	}
 }

+ 7 - 13
Server/Model/Generate/Config/StartMachineConfig.cs

@@ -24,15 +24,15 @@ namespace ET
             Instance = this;
         }
 		
-		[ProtoAfterDeserialization]
-        public void AfterDeserialization()
+        public override void EndInit()
         {
             foreach (StartMachineConfig config in list)
             {
                 this.dict.Add(config.Id, config);
             }
             list.Clear();
-            this.EndInit();
+            
+            this.AfterEndInit();
         }
 		
         public StartMachineConfig Get(int id)
@@ -70,20 +70,14 @@ namespace ET
     [ProtoContract]
 	public partial class StartMachineConfig: ProtoObject, IConfig
 	{
-		[ProtoMember(1, IsRequired  = true)]
+		[ProtoMember(1)]
 		public int Id { get; set; }
-		[ProtoMember(2, IsRequired  = true)]
+		[ProtoMember(2)]
 		public string InnerIP { get; set; }
-		[ProtoMember(3, IsRequired  = true)]
+		[ProtoMember(3)]
 		public string OuterIP { get; set; }
-		[ProtoMember(4, IsRequired  = true)]
+		[ProtoMember(4)]
 		public string WatcherPort { get; set; }
 
-
-		[ProtoAfterDeserialization]
-        public void AfterDeserialization()
-        {
-            this.EndInit();
-        }
 	}
 }

+ 7 - 13
Server/Model/Generate/Config/StartProcessConfig.cs

@@ -24,15 +24,15 @@ namespace ET
             Instance = this;
         }
 		
-		[ProtoAfterDeserialization]
-        public void AfterDeserialization()
+        public override void EndInit()
         {
             foreach (StartProcessConfig config in list)
             {
                 this.dict.Add(config.Id, config);
             }
             list.Clear();
-            this.EndInit();
+            
+            this.AfterEndInit();
         }
 		
         public StartProcessConfig Get(int id)
@@ -70,20 +70,14 @@ namespace ET
     [ProtoContract]
 	public partial class StartProcessConfig: ProtoObject, IConfig
 	{
-		[ProtoMember(1, IsRequired  = true)]
+		[ProtoMember(1)]
 		public int Id { get; set; }
-		[ProtoMember(2, IsRequired  = true)]
+		[ProtoMember(2)]
 		public int MachineId { get; set; }
-		[ProtoMember(3, IsRequired  = true)]
+		[ProtoMember(3)]
 		public int InnerPort { get; set; }
-		[ProtoMember(4, IsRequired  = true)]
+		[ProtoMember(4)]
 		public string AppName { get; set; }
 
-
-		[ProtoAfterDeserialization]
-        public void AfterDeserialization()
-        {
-            this.EndInit();
-        }
 	}
 }

+ 9 - 15
Server/Model/Generate/Config/StartSceneConfig.cs

@@ -24,15 +24,15 @@ namespace ET
             Instance = this;
         }
 		
-		[ProtoAfterDeserialization]
-        public void AfterDeserialization()
+        public override void EndInit()
         {
             foreach (StartSceneConfig config in list)
             {
                 this.dict.Add(config.Id, config);
             }
             list.Clear();
-            this.EndInit();
+            
+            this.AfterEndInit();
         }
 		
         public StartSceneConfig Get(int id)
@@ -70,24 +70,18 @@ namespace ET
     [ProtoContract]
 	public partial class StartSceneConfig: ProtoObject, IConfig
 	{
-		[ProtoMember(1, IsRequired  = true)]
+		[ProtoMember(1)]
 		public int Id { get; set; }
-		[ProtoMember(2, IsRequired  = true)]
+		[ProtoMember(2)]
 		public int Process { get; set; }
-		[ProtoMember(3, IsRequired  = true)]
+		[ProtoMember(3)]
 		public int Zone { get; set; }
-		[ProtoMember(4, IsRequired  = true)]
+		[ProtoMember(4)]
 		public string SceneType { get; set; }
-		[ProtoMember(5, IsRequired  = true)]
+		[ProtoMember(5)]
 		public string Name { get; set; }
-		[ProtoMember(6, IsRequired  = true)]
+		[ProtoMember(6)]
 		public int OuterPort { get; set; }
 
-
-		[ProtoAfterDeserialization]
-        public void AfterDeserialization()
-        {
-            this.EndInit();
-        }
 	}
 }

+ 6 - 12
Server/Model/Generate/Config/StartZoneConfig.cs

@@ -24,15 +24,15 @@ namespace ET
             Instance = this;
         }
 		
-		[ProtoAfterDeserialization]
-        public void AfterDeserialization()
+        public override void EndInit()
         {
             foreach (StartZoneConfig config in list)
             {
                 this.dict.Add(config.Id, config);
             }
             list.Clear();
-            this.EndInit();
+            
+            this.AfterEndInit();
         }
 		
         public StartZoneConfig Get(int id)
@@ -70,18 +70,12 @@ namespace ET
     [ProtoContract]
 	public partial class StartZoneConfig: ProtoObject, IConfig
 	{
-		[ProtoMember(1, IsRequired  = true)]
+		[ProtoMember(1)]
 		public int Id { get; set; }
-		[ProtoMember(2, IsRequired  = true)]
+		[ProtoMember(2)]
 		public string DBConnection { get; set; }
-		[ProtoMember(3, IsRequired  = true)]
+		[ProtoMember(3)]
 		public string DBName { get; set; }
 
-
-		[ProtoAfterDeserialization]
-        public void AfterDeserialization()
-        {
-            this.EndInit();
-        }
 	}
 }

+ 9 - 15
Server/Model/Generate/Config/UnitConfig.cs

@@ -24,15 +24,15 @@ namespace ET
             Instance = this;
         }
 		
-		[ProtoAfterDeserialization]
-        public void AfterDeserialization()
+        public override void EndInit()
         {
             foreach (UnitConfig config in list)
             {
                 this.dict.Add(config.Id, config);
             }
             list.Clear();
-            this.EndInit();
+            
+            this.AfterEndInit();
         }
 		
         public UnitConfig Get(int id)
@@ -70,24 +70,18 @@ namespace ET
     [ProtoContract]
 	public partial class UnitConfig: ProtoObject, IConfig
 	{
-		[ProtoMember(1, IsRequired  = true)]
+		[ProtoMember(1)]
 		public int Id { get; set; }
-		[ProtoMember(2, IsRequired  = true)]
+		[ProtoMember(2)]
 		public string Name { get; set; }
-		[ProtoMember(3, IsRequired  = true)]
+		[ProtoMember(3)]
 		public string Desc { get; set; }
-		[ProtoMember(4, IsRequired  = true)]
+		[ProtoMember(4)]
 		public int Position { get; set; }
-		[ProtoMember(5, IsRequired  = true)]
+		[ProtoMember(5)]
 		public int Height { get; set; }
-		[ProtoMember(6, IsRequired  = true)]
+		[ProtoMember(6)]
 		public int Weight { get; set; }
 
-
-		[ProtoAfterDeserialization]
-        public void AfterDeserialization()
-        {
-            this.EndInit();
-        }
 	}
 }

+ 1 - 1
Server/Model/Generate/ConfigPartial/StartProcessConfig.cs

@@ -27,7 +27,7 @@ namespace ET
 
         public StartMachineConfig StartMachineConfig => StartMachineConfigCategory.Instance.Get(this.MachineId);
 
-        public override void EndInit()
+        public override void AfterEndInit()
         {
             InstanceIdStruct instanceIdStruct = new InstanceIdStruct((int)this.Id, 0);
             this.SceneId = instanceIdStruct.ToLong();

+ 1 - 1
Server/Model/Generate/ConfigPartial/StartSceneConfig.cs

@@ -26,7 +26,7 @@ namespace ET
             return this.ZoneScenesByName[zone][name];
         }
         
-        public override void EndInit()
+        public override void AfterEndInit()
         {
             foreach (StartSceneConfig startSceneConfig in this.GetAll().Values)
             {

+ 0 - 1
Server/Model/Server.Model.csproj

@@ -111,7 +111,6 @@
     <PackageReference Include="MongoDB.Driver" Version="2.13.0" />
   </ItemGroup>
   <ItemGroup>
-    <ProjectReference Include="..\..\ThirdParty\protobuf-net\protobuf-net.csproj" />
     <ProjectReference Include="..\..\ThirdParty\ShareLib\ShareLib.csproj" />
     <ProjectReference Include="..\..\ThirdParty\UnityEngine\UnityEngine.csproj" />
   </ItemGroup>

+ 1 - 0
ThirdParty/ShareLib/ShareLib.csproj

@@ -53,6 +53,7 @@
       <PackageReference Include="mongocsharpdriver" Version="2.13.0" />
       <PackageReference Include="MongoDB.Bson" Version="2.13.0" />
       <PackageReference Include="NLog" Version="4.7.10" />
+      <PackageReference Include="protobuf-net" Version="2.4.0" />
       <PackageReference Include="SharpZipLib" Version="1.3.2" />
     </ItemGroup>
 

+ 0 - 712
ThirdParty/protobuf-net/BclHelpers.cs

@@ -1,712 +0,0 @@
-using System;
-using System.Reflection;
-namespace ProtoBuf
-{
-    internal enum TimeSpanScale
-    {
-        Days = 0,
-        Hours = 1,
-        Minutes = 2,
-        Seconds = 3,
-        Milliseconds = 4,
-        Ticks = 5,
-
-        MinMax = 15
-    }
-
-    /// <summary>
-    /// Provides support for common .NET types that do not have a direct representation
-    /// in protobuf, using the definitions from bcl.proto
-    /// </summary>
-    public static class BclHelpers
-    {
-        /// <summary>
-        /// Creates a new instance of the specified type, bypassing the constructor.
-        /// </summary>
-        /// <param name="type">The type to create</param>
-        /// <returns>The new instance</returns>
-        /// <exception cref="NotSupportedException">If the platform does not support constructor-skipping</exception>
-        public static object GetUninitializedObject(Type type)
-        {
-#if COREFX
-            object obj = TryGetUninitializedObjectWithFormatterServices(type);
-            if (obj != null) return obj;
-#endif
-#if PLAT_BINARYFORMATTER && !(COREFX || PROFILE259)
-            return System.Runtime.Serialization.FormatterServices.GetUninitializedObject(type);
-#else
-            throw new NotSupportedException("Constructor-skipping is not supported on this platform");
-#endif
-        }
-
-#if COREFX // this is inspired by DCS: https://github.com/dotnet/corefx/blob/c02d33b18398199f6acc17d375dab154e9a1df66/src/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatReaderGenerator.cs#L854-L894
-        static Func<Type, object> getUninitializedObject;
-        static internal object TryGetUninitializedObjectWithFormatterServices(Type type)
-        {
-            if (getUninitializedObject == null)
-            {
-                try {
-                    var formatterServiceType = typeof(string).GetTypeInfo().Assembly.GetType("System.Runtime.Serialization.FormatterServices");
-                    if (formatterServiceType == null)
-                    {
-                        // fallback for .Net Core 3.0
-                        var formatterAssembly = Assembly.Load(new AssemblyName("System.Runtime.Serialization.Formatters"));
-                        formatterServiceType = formatterAssembly.GetType("System.Runtime.Serialization.FormatterServices");
-                    }
-                    MethodInfo method = formatterServiceType?.GetMethod("GetUninitializedObject", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
-                    if (method != null)
-                    {
-                        getUninitializedObject = (Func<Type, object>)method.CreateDelegate(typeof(Func<Type, object>));
-                    }
-                }
-                catch  { /* best efforts only */ }
-                if(getUninitializedObject == null) getUninitializedObject = x => null;
-            }
-            return getUninitializedObject(type);
-        }
-#endif
-
-        const int FieldTimeSpanValue = 0x01, FieldTimeSpanScale = 0x02, FieldTimeSpanKind = 0x03;
-
-        internal static readonly DateTime[] EpochOrigin = {
-            new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified),
-            new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc),
-            new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Local)
-        };
-
-        /// <summary>
-        /// The default value for dates that are following google.protobuf.Timestamp semantics
-        /// </summary>
-        private static readonly DateTime TimestampEpoch = EpochOrigin[(int)DateTimeKind.Utc];
-
-        /// <summary>
-        /// Writes a TimeSpan to a protobuf stream using protobuf-net's own representation, bcl.TimeSpan
-        /// </summary>
-        public static void WriteTimeSpan(TimeSpan timeSpan, ProtoWriter dest)
-        {
-            WriteTimeSpanImpl(timeSpan, dest, DateTimeKind.Unspecified);
-        }
-
-        private static void WriteTimeSpanImpl(TimeSpan timeSpan, ProtoWriter dest, DateTimeKind kind)
-        {
-            if (dest == null) throw new ArgumentNullException(nameof(dest));
-            long value;
-            switch (dest.WireType)
-            {
-                case WireType.String:
-                case WireType.StartGroup:
-                    TimeSpanScale scale;
-                    value = timeSpan.Ticks;
-                    if (timeSpan == TimeSpan.MaxValue)
-                    {
-                        value = 1;
-                        scale = TimeSpanScale.MinMax;
-                    }
-                    else if (timeSpan == TimeSpan.MinValue)
-                    {
-                        value = -1;
-                        scale = TimeSpanScale.MinMax;
-                    }
-                    else if (value % TimeSpan.TicksPerDay == 0)
-                    {
-                        scale = TimeSpanScale.Days;
-                        value /= TimeSpan.TicksPerDay;
-                    }
-                    else if (value % TimeSpan.TicksPerHour == 0)
-                    {
-                        scale = TimeSpanScale.Hours;
-                        value /= TimeSpan.TicksPerHour;
-                    }
-                    else if (value % TimeSpan.TicksPerMinute == 0)
-                    {
-                        scale = TimeSpanScale.Minutes;
-                        value /= TimeSpan.TicksPerMinute;
-                    }
-                    else if (value % TimeSpan.TicksPerSecond == 0)
-                    {
-                        scale = TimeSpanScale.Seconds;
-                        value /= TimeSpan.TicksPerSecond;
-                    }
-                    else if (value % TimeSpan.TicksPerMillisecond == 0)
-                    {
-                        scale = TimeSpanScale.Milliseconds;
-                        value /= TimeSpan.TicksPerMillisecond;
-                    }
-                    else
-                    {
-                        scale = TimeSpanScale.Ticks;
-                    }
-
-                    SubItemToken token = ProtoWriter.StartSubItem(null, dest);
-
-                    if (value != 0)
-                    {
-                        ProtoWriter.WriteFieldHeader(FieldTimeSpanValue, WireType.SignedVariant, dest);
-                        ProtoWriter.WriteInt64(value, dest);
-                    }
-                    if (scale != TimeSpanScale.Days)
-                    {
-                        ProtoWriter.WriteFieldHeader(FieldTimeSpanScale, WireType.Variant, dest);
-                        ProtoWriter.WriteInt32((int)scale, dest);
-                    }
-                    if (kind != DateTimeKind.Unspecified)
-                    {
-                        ProtoWriter.WriteFieldHeader(FieldTimeSpanKind, WireType.Variant, dest);
-                        ProtoWriter.WriteInt32((int)kind, dest);
-                    }
-                    ProtoWriter.EndSubItem(token, dest);
-                    break;
-                case WireType.Fixed64:
-                    ProtoWriter.WriteInt64(timeSpan.Ticks, dest);
-                    break;
-                default:
-                    throw new ProtoException("Unexpected wire-type: " + dest.WireType.ToString());
-            }
-        }
-
-        /// <summary>
-        /// Parses a TimeSpan from a protobuf stream using protobuf-net's own representation, bcl.TimeSpan
-        /// </summary>        
-        public static TimeSpan ReadTimeSpan(ProtoReader source)
-        {
-            long ticks = ReadTimeSpanTicks(source, out DateTimeKind kind);
-            if (ticks == long.MinValue) return TimeSpan.MinValue;
-            if (ticks == long.MaxValue) return TimeSpan.MaxValue;
-            return TimeSpan.FromTicks(ticks);
-        }
-
-        /// <summary>
-        /// Parses a TimeSpan from a protobuf stream using the standardized format, google.protobuf.Duration
-        /// </summary>
-        public static TimeSpan ReadDuration(ProtoReader source)
-        {
-            long seconds = 0;
-            int nanos = 0;
-            SubItemToken token = ProtoReader.StartSubItem(source);
-            int fieldNumber;
-            while ((fieldNumber = source.ReadFieldHeader()) > 0)
-            {
-                switch (fieldNumber)
-                {
-                    case 1:
-                        seconds = source.ReadInt64();
-                        break;
-                    case 2:
-                        nanos = source.ReadInt32();
-                        break;
-                    default:
-                        source.SkipField();
-                        break;
-                }
-            }
-            ProtoReader.EndSubItem(token, source);
-            return FromDurationSeconds(seconds, nanos);
-        }
-
-        /// <summary>
-        /// Writes a TimeSpan to a protobuf stream using the standardized format, google.protobuf.Duration
-        /// </summary>
-        public static void WriteDuration(TimeSpan value, ProtoWriter dest)
-        {
-            var seconds = ToDurationSeconds(value, out int nanos);
-            WriteSecondsNanos(seconds, nanos, dest);
-        }
-
-        private static void WriteSecondsNanos(long seconds, int nanos, ProtoWriter dest)
-        {
-            SubItemToken token = ProtoWriter.StartSubItem(null, dest);
-            if (seconds != 0)
-            {
-                ProtoWriter.WriteFieldHeader(1, WireType.Variant, dest);
-                ProtoWriter.WriteInt64(seconds, dest);
-            }
-            if (nanos != 0)
-            {
-                ProtoWriter.WriteFieldHeader(2, WireType.Variant, dest);
-                ProtoWriter.WriteInt32(nanos, dest);
-            }
-            ProtoWriter.EndSubItem(token, dest);
-        }
-
-        /// <summary>
-        /// Parses a DateTime from a protobuf stream using the standardized format, google.protobuf.Timestamp
-        /// </summary>
-        public static DateTime ReadTimestamp(ProtoReader source)
-        {
-            // note: DateTime is only defined for just over 0000 to just below 10000;
-            // TimeSpan has a range of +/- 10,675,199 days === 29k years;
-            // so we can just use epoch time delta
-            return TimestampEpoch + ReadDuration(source);
-        }
-
-        /// <summary>
-        /// Writes a DateTime to a protobuf stream using the standardized format, google.protobuf.Timestamp
-        /// </summary>
-        public static void WriteTimestamp(DateTime value, ProtoWriter dest)
-        {
-            var seconds = ToDurationSeconds(value - TimestampEpoch, out int nanos);
-
-            if (nanos < 0)
-            {   // from Timestamp.proto:
-                // "Negative second values with fractions must still have
-                // non -negative nanos values that count forward in time."
-                seconds--;
-                nanos += 1000000000;
-            }
-            WriteSecondsNanos(seconds, nanos, dest);
-        }
-
-        static TimeSpan FromDurationSeconds(long seconds, int nanos)
-        {
-
-            long ticks = checked((seconds * TimeSpan.TicksPerSecond)
-                + (nanos * TimeSpan.TicksPerMillisecond) / 1000000);
-            return TimeSpan.FromTicks(ticks);
-        }
-
-        static long ToDurationSeconds(TimeSpan value, out int nanos)
-        {
-            nanos = (int)(((value.Ticks % TimeSpan.TicksPerSecond) * 1000000)
-                / TimeSpan.TicksPerMillisecond);
-            return value.Ticks / TimeSpan.TicksPerSecond;
-        }
-
-        /// <summary>
-        /// Parses a DateTime from a protobuf stream
-        /// </summary>
-        public static DateTime ReadDateTime(ProtoReader source)
-        {
-            long ticks = ReadTimeSpanTicks(source, out DateTimeKind kind);
-            if (ticks == long.MinValue) return DateTime.MinValue;
-            if (ticks == long.MaxValue) return DateTime.MaxValue;
-            return EpochOrigin[(int)kind].AddTicks(ticks);
-        }
-
-        /// <summary>
-        /// Writes a DateTime to a protobuf stream, excluding the <c>Kind</c>
-        /// </summary>
-        public static void WriteDateTime(DateTime value, ProtoWriter dest)
-        {
-            WriteDateTimeImpl(value, dest, false);
-        }
-
-        /// <summary>
-        /// Writes a DateTime to a protobuf stream, including the <c>Kind</c>
-        /// </summary>
-        public static void WriteDateTimeWithKind(DateTime value, ProtoWriter dest)
-        {
-            WriteDateTimeImpl(value, dest, true);
-        }
-
-        private static void WriteDateTimeImpl(DateTime value, ProtoWriter dest, bool includeKind)
-        {
-            if (dest == null) throw new ArgumentNullException(nameof(dest));
-            TimeSpan delta;
-            switch (dest.WireType)
-            {
-                case WireType.StartGroup:
-                case WireType.String:
-                    if (value == DateTime.MaxValue)
-                    {
-                        delta = TimeSpan.MaxValue;
-                        includeKind = false;
-                    }
-                    else if (value == DateTime.MinValue)
-                    {
-                        delta = TimeSpan.MinValue;
-                        includeKind = false;
-                    }
-                    else
-                    {
-                        delta = value - EpochOrigin[0];
-                    }
-                    break;
-                default:
-                    delta = value - EpochOrigin[0];
-                    break;
-            }
-            WriteTimeSpanImpl(delta, dest, includeKind ? value.Kind : DateTimeKind.Unspecified);
-        }
-
-        private static long ReadTimeSpanTicks(ProtoReader source, out DateTimeKind kind)
-        {
-            kind = DateTimeKind.Unspecified;
-            switch (source.WireType)
-            {
-                case WireType.String:
-                case WireType.StartGroup:
-                    SubItemToken token = ProtoReader.StartSubItem(source);
-                    int fieldNumber;
-                    TimeSpanScale scale = TimeSpanScale.Days;
-                    long value = 0;
-                    while ((fieldNumber = source.ReadFieldHeader()) > 0)
-                    {
-                        switch (fieldNumber)
-                        {
-                            case FieldTimeSpanScale:
-                                scale = (TimeSpanScale)source.ReadInt32();
-                                break;
-                            case FieldTimeSpanValue:
-                                source.Assert(WireType.SignedVariant);
-                                value = source.ReadInt64();
-                                break;
-                            case FieldTimeSpanKind:
-                                kind = (DateTimeKind)source.ReadInt32();
-                                switch (kind)
-                                {
-                                    case DateTimeKind.Unspecified:
-                                    case DateTimeKind.Utc:
-                                    case DateTimeKind.Local:
-                                        break; // fine
-                                    default:
-                                        throw new ProtoException("Invalid date/time kind: " + kind.ToString());
-                                }
-                                break;
-                            default:
-                                source.SkipField();
-                                break;
-                        }
-                    }
-                    ProtoReader.EndSubItem(token, source);
-                    switch (scale)
-                    {
-                        case TimeSpanScale.Days:
-                            return value * TimeSpan.TicksPerDay;
-                        case TimeSpanScale.Hours:
-                            return value * TimeSpan.TicksPerHour;
-                        case TimeSpanScale.Minutes:
-                            return value * TimeSpan.TicksPerMinute;
-                        case TimeSpanScale.Seconds:
-                            return value * TimeSpan.TicksPerSecond;
-                        case TimeSpanScale.Milliseconds:
-                            return value * TimeSpan.TicksPerMillisecond;
-                        case TimeSpanScale.Ticks:
-                            return value;
-                        case TimeSpanScale.MinMax:
-                            switch (value)
-                            {
-                                case 1: return long.MaxValue;
-                                case -1: return long.MinValue;
-                                default: throw new ProtoException("Unknown min/max value: " + value.ToString());
-                            }
-                        default:
-                            throw new ProtoException("Unknown timescale: " + scale.ToString());
-                    }
-                case WireType.Fixed64:
-                    return source.ReadInt64();
-                default:
-                    throw new ProtoException("Unexpected wire-type: " + source.WireType.ToString());
-            }
-        }
-
-        const int FieldDecimalLow = 0x01, FieldDecimalHigh = 0x02, FieldDecimalSignScale = 0x03;
-
-        /// <summary>
-        /// Parses a decimal from a protobuf stream
-        /// </summary>
-        public static decimal ReadDecimal(ProtoReader reader)
-        {
-            ulong low = 0;
-            uint high = 0;
-            uint signScale = 0;
-
-            int fieldNumber;
-            SubItemToken token = ProtoReader.StartSubItem(reader);
-            while ((fieldNumber = reader.ReadFieldHeader()) > 0)
-            {
-                switch (fieldNumber)
-                {
-                    case FieldDecimalLow: low = reader.ReadUInt64(); break;
-                    case FieldDecimalHigh: high = reader.ReadUInt32(); break;
-                    case FieldDecimalSignScale: signScale = reader.ReadUInt32(); break;
-                    default: reader.SkipField(); break;
-                }
-
-            }
-            ProtoReader.EndSubItem(token, reader);
-
-            int lo = (int)(low & 0xFFFFFFFFL),
-                mid = (int)((low >> 32) & 0xFFFFFFFFL),
-                hi = (int)high;
-            bool isNeg = (signScale & 0x0001) == 0x0001;
-            byte scale = (byte)((signScale & 0x01FE) >> 1);
-            return new decimal(lo, mid, hi, isNeg, scale);
-        }
-
-        /// <summary>
-        /// Writes a decimal to a protobuf stream
-        /// </summary>
-        public static void WriteDecimal(decimal value, ProtoWriter writer)
-        {
-            int[] bits = decimal.GetBits(value);
-            ulong a = ((ulong)bits[1]) << 32, b = ((ulong)bits[0]) & 0xFFFFFFFFL;
-            ulong low = a | b;
-            uint high = (uint)bits[2];
-            uint signScale = (uint)(((bits[3] >> 15) & 0x01FE) | ((bits[3] >> 31) & 0x0001));
-
-            SubItemToken token = ProtoWriter.StartSubItem(null, writer);
-            if (low != 0)
-            {
-                ProtoWriter.WriteFieldHeader(FieldDecimalLow, WireType.Variant, writer);
-                ProtoWriter.WriteUInt64(low, writer);
-            }
-            if (high != 0)
-            {
-                ProtoWriter.WriteFieldHeader(FieldDecimalHigh, WireType.Variant, writer);
-                ProtoWriter.WriteUInt32(high, writer);
-            }
-            if (signScale != 0)
-            {
-                ProtoWriter.WriteFieldHeader(FieldDecimalSignScale, WireType.Variant, writer);
-                ProtoWriter.WriteUInt32(signScale, writer);
-            }
-            ProtoWriter.EndSubItem(token, writer);
-        }
-
-        const int FieldGuidLow = 1, FieldGuidHigh = 2;
-        /// <summary>
-        /// Writes a Guid to a protobuf stream
-        /// </summary>        
-        public static void WriteGuid(Guid value, ProtoWriter dest)
-        {
-            byte[] blob = value.ToByteArray();
-
-            SubItemToken token = ProtoWriter.StartSubItem(null, dest);
-            if (value != Guid.Empty)
-            {
-                ProtoWriter.WriteFieldHeader(FieldGuidLow, WireType.Fixed64, dest);
-                ProtoWriter.WriteBytes(blob, 0, 8, dest);
-                ProtoWriter.WriteFieldHeader(FieldGuidHigh, WireType.Fixed64, dest);
-                ProtoWriter.WriteBytes(blob, 8, 8, dest);
-            }
-            ProtoWriter.EndSubItem(token, dest);
-        }
-        /// <summary>
-        /// Parses a Guid from a protobuf stream
-        /// </summary>
-        public static Guid ReadGuid(ProtoReader source)
-        {
-            ulong low = 0, high = 0;
-            int fieldNumber;
-            SubItemToken token = ProtoReader.StartSubItem(source);
-            while ((fieldNumber = source.ReadFieldHeader()) > 0)
-            {
-                switch (fieldNumber)
-                {
-                    case FieldGuidLow: low = source.ReadUInt64(); break;
-                    case FieldGuidHigh: high = source.ReadUInt64(); break;
-                    default: source.SkipField(); break;
-                }
-            }
-            ProtoReader.EndSubItem(token, source);
-            if (low == 0 && high == 0) return Guid.Empty;
-            uint a = (uint)(low >> 32), b = (uint)low, c = (uint)(high >> 32), d = (uint)high;
-            return new Guid((int)b, (short)a, (short)(a >> 16),
-                (byte)d, (byte)(d >> 8), (byte)(d >> 16), (byte)(d >> 24),
-                (byte)c, (byte)(c >> 8), (byte)(c >> 16), (byte)(c >> 24));
-
-        }
-
-
-        private const int
-            FieldExistingObjectKey = 1,
-            FieldNewObjectKey = 2,
-            FieldExistingTypeKey = 3,
-            FieldNewTypeKey = 4,
-            FieldTypeName = 8,
-            FieldObject = 10;
-
-        /// <summary>
-        /// Optional behaviours that introduce .NET-specific functionality
-        /// </summary>
-        [Flags]
-        public enum NetObjectOptions : byte
-        {
-            /// <summary>
-            /// No special behaviour
-            /// </summary>
-            None = 0,
-            /// <summary>
-            /// Enables full object-tracking/full-graph support.
-            /// </summary>
-            AsReference = 1,
-            /// <summary>
-            /// Embeds the type information into the stream, allowing usage with types not known in advance.
-            /// </summary>
-            DynamicType = 2,
-            /// <summary>
-            /// If false, the constructor for the type is bypassed during deserialization, meaning any field initializers
-            /// or other initialization code is skipped.
-            /// </summary>
-            UseConstructor = 4,
-            /// <summary>
-            /// Should the object index be reserved, rather than creating an object promptly
-            /// </summary>
-            LateSet = 8
-        }
-
-        /// <summary>
-        /// Reads an *implementation specific* bundled .NET object, including (as options) type-metadata, identity/re-use, etc.
-        /// </summary>
-        public static object ReadNetObject(object value, ProtoReader source, int key, Type type, NetObjectOptions options)
-        {
-            SubItemToken token = ProtoReader.StartSubItem(source);
-            int fieldNumber;
-            int newObjectKey = -1, newTypeKey = -1, tmp;
-            while ((fieldNumber = source.ReadFieldHeader()) > 0)
-            {
-                switch (fieldNumber)
-                {
-                    case FieldExistingObjectKey:
-                        tmp = source.ReadInt32();
-                        value = source.NetCache.GetKeyedObject(tmp);
-                        break;
-                    case FieldNewObjectKey:
-                        newObjectKey = source.ReadInt32();
-                        break;
-                    case FieldExistingTypeKey:
-                        tmp = source.ReadInt32();
-                        type = (Type)source.NetCache.GetKeyedObject(tmp);
-                        key = source.GetTypeKey(ref type);
-                        break;
-                    case FieldNewTypeKey:
-                        newTypeKey = source.ReadInt32();
-                        break;
-                    case FieldTypeName:
-                        string typeName = source.ReadString();
-                        type = source.DeserializeType(typeName);
-                        if (type == null)
-                        {
-                            throw new ProtoException("Unable to resolve type: " + typeName + " (you can use the TypeModel.DynamicTypeFormatting event to provide a custom mapping)");
-                        }
-                        if (type == typeof(string))
-                        {
-                            key = -1;
-                        }
-                        else
-                        {
-                            key = source.GetTypeKey(ref type);
-                            if (key < 0)
-                                throw new InvalidOperationException("Dynamic type is not a contract-type: " + type.Name);
-                        }
-                        break;
-                    case FieldObject:
-                        bool isString = type == typeof(string);
-                        bool wasNull = value == null;
-                        bool lateSet = wasNull && (isString || ((options & NetObjectOptions.LateSet) != 0));
-
-                        if (newObjectKey >= 0 && !lateSet)
-                        {
-                            if (value == null)
-                            {
-                                source.TrapNextObject(newObjectKey);
-                            }
-                            else
-                            {
-                                source.NetCache.SetKeyedObject(newObjectKey, value);
-                            }
-                            if (newTypeKey >= 0) source.NetCache.SetKeyedObject(newTypeKey, type);
-                        }
-                        object oldValue = value;
-                        if (isString)
-                        {
-                            value = source.ReadString();
-                        }
-                        else
-                        {
-                            value = ProtoReader.ReadTypedObject(oldValue, key, source, type);
-                        }
-
-                        if (newObjectKey >= 0)
-                        {
-                            if (wasNull && !lateSet)
-                            { // this both ensures (via exception) that it *was* set, and makes sure we don't shout
-                                // about changed references
-                                oldValue = source.NetCache.GetKeyedObject(newObjectKey);
-                            }
-                            if (lateSet)
-                            {
-                                source.NetCache.SetKeyedObject(newObjectKey, value);
-                                if (newTypeKey >= 0) source.NetCache.SetKeyedObject(newTypeKey, type);
-                            }
-                        }
-                        if (newObjectKey >= 0 && !lateSet && !ReferenceEquals(oldValue, value))
-                        {
-                            throw new ProtoException("A reference-tracked object changed reference during deserialization");
-                        }
-                        if (newObjectKey < 0 && newTypeKey >= 0)
-                        {  // have a new type, but not a new object
-                            source.NetCache.SetKeyedObject(newTypeKey, type);
-                        }
-                        break;
-                    default:
-                        source.SkipField();
-                        break;
-                }
-            }
-            if (newObjectKey >= 0 && (options & NetObjectOptions.AsReference) == 0)
-            {
-                throw new ProtoException("Object key in input stream, but reference-tracking was not expected");
-            }
-            ProtoReader.EndSubItem(token, source);
-
-            return value;
-        }
-
-        /// <summary>
-        /// Writes an *implementation specific* bundled .NET object, including (as options) type-metadata, identity/re-use, etc.
-        /// </summary>
-        public static void WriteNetObject(object value, ProtoWriter dest, int key, NetObjectOptions options)
-        {
-            if (dest == null) throw new ArgumentNullException("dest");
-            bool dynamicType = (options & NetObjectOptions.DynamicType) != 0,
-                 asReference = (options & NetObjectOptions.AsReference) != 0;
-            WireType wireType = dest.WireType;
-            SubItemToken token = ProtoWriter.StartSubItem(null, dest);
-            bool writeObject = true;
-            if (asReference)
-            {
-                int objectKey = dest.NetCache.AddObjectKey(value, out bool existing);
-                ProtoWriter.WriteFieldHeader(existing ? FieldExistingObjectKey : FieldNewObjectKey, WireType.Variant, dest);
-                ProtoWriter.WriteInt32(objectKey, dest);
-                if (existing)
-                {
-                    writeObject = false;
-                }
-            }
-
-            if (writeObject)
-            {
-                if (dynamicType)
-                {
-                    Type type = value.GetType();
-
-                    if (!(value is string))
-                    {
-                        key = dest.GetTypeKey(ref type);
-                        if (key < 0) throw new InvalidOperationException("Dynamic type is not a contract-type: " + type.Name);
-                    }
-                    int typeKey = dest.NetCache.AddObjectKey(type, out bool existing);
-                    ProtoWriter.WriteFieldHeader(existing ? FieldExistingTypeKey : FieldNewTypeKey, WireType.Variant, dest);
-                    ProtoWriter.WriteInt32(typeKey, dest);
-                    if (!existing)
-                    {
-                        ProtoWriter.WriteFieldHeader(FieldTypeName, WireType.String, dest);
-                        ProtoWriter.WriteString(dest.SerializeType(type), dest);
-                    }
-
-                }
-                ProtoWriter.WriteFieldHeader(FieldObject, wireType, dest);
-                if (value is string)
-                {
-                    ProtoWriter.WriteString((string)value, dest);
-                }
-                else
-                {
-                    ProtoWriter.WriteObject(value, key, dest);
-                }
-            }
-            ProtoWriter.EndSubItem(token, dest);
-        }
-    }
-}

+ 0 - 78
ThirdParty/protobuf-net/BufferExtension.cs

@@ -1,78 +0,0 @@
-using System;
-using System.IO;
-
-namespace ProtoBuf
-{
-    /// <summary>
-    /// Provides a simple buffer-based implementation of an <see cref="IExtension">extension</see> object.
-    /// </summary>
-    public sealed class BufferExtension : IExtension, IExtensionResettable
-    {
-        private byte[] buffer;
-
-        void IExtensionResettable.Reset()
-        {
-            buffer = null;
-        }
-
-        int IExtension.GetLength()
-        {
-            return buffer == null ? 0 : buffer.Length;
-        }
-
-        Stream IExtension.BeginAppend()
-        {
-            return new MemoryStream();
-        }
-
-        void IExtension.EndAppend(Stream stream, bool commit)
-        {
-            using (stream)
-            {
-                int len;
-                if (commit && (len = (int)stream.Length) > 0)
-                {
-                    MemoryStream ms = (MemoryStream)stream;
-
-                    if (buffer == null)
-                    {   // allocate new buffer
-                        buffer = ms.ToArray();
-                    }
-                    else
-                    {   // resize and copy the data
-                        // note: Array.Resize not available on CF
-                        int offset = buffer.Length;
-                        byte[] tmp = new byte[offset + len];
-                        Buffer.BlockCopy(buffer, 0, tmp, 0, offset);
-
-#if PORTABLE // no GetBuffer() - fine, we'll use Read instead
-                        int bytesRead;
-                        long oldPos = ms.Position;
-                        ms.Position = 0;
-                        while (len > 0 && (bytesRead = ms.Read(tmp, offset, len)) > 0)
-                        {
-                            len -= bytesRead;
-                            offset += bytesRead;
-                        }
-                        if(len != 0) throw new EndOfStreamException();
-                        ms.Position = oldPos;
-#else
-                        Buffer.BlockCopy(Helpers.GetBuffer(ms), 0, tmp, offset, len);
-#endif
-                        buffer = tmp;
-                    }
-                }
-            }
-        }
-
-        Stream IExtension.BeginQuery()
-        {
-            return buffer == null ? Stream.Null : new MemoryStream(buffer);
-        }
-
-        void IExtension.EndQuery(Stream stream)
-        {
-            using (stream) { } // just clean up
-        }
-    }
-}

+ 0 - 149
ThirdParty/protobuf-net/BufferPool.cs

@@ -1,149 +0,0 @@
-using System;
-
-namespace ProtoBuf
-{
-    internal sealed class BufferPool
-    {
-        internal static void Flush()
-        {
-            lock (Pool)
-            {
-                for (var i = 0; i < Pool.Length; i++)
-                    Pool[i] = null;
-            }
-        }
-
-        private BufferPool() { }
-        private const int POOL_SIZE = 20;
-        internal const int BUFFER_LENGTH = 1024;
-        private static readonly CachedBuffer[] Pool = new CachedBuffer[POOL_SIZE];
-
-        internal static byte[] GetBuffer() => GetBuffer(BUFFER_LENGTH);
-
-        internal static byte[] GetBuffer(int minSize)
-        {
-            byte[] cachedBuff = GetCachedBuffer(minSize);
-            return cachedBuff ?? new byte[minSize];
-        }
-
-        internal static byte[] GetCachedBuffer(int minSize)
-        {
-            lock (Pool)
-            {
-                var bestIndex = -1;
-                byte[] bestMatch = null;
-                for (var i = 0; i < Pool.Length; i++)
-                {
-                    var buffer = Pool[i];
-                    if (buffer == null || buffer.Size < minSize)
-                    {
-                        continue;
-                    }
-                    if (bestMatch != null && bestMatch.Length < buffer.Size)
-                    {
-                        continue;
-                    }
-
-                    var tmp = buffer.Buffer;
-                    if (tmp == null)
-                    {
-                        Pool[i] = null;
-                    }
-                    else
-                    {
-                        bestMatch = tmp;
-                        bestIndex = i;
-                    }
-                }
-
-                if (bestIndex >= 0)
-                {
-                    Pool[bestIndex] = null;
-                }
-
-                return bestMatch;
-            }
-        }
-
-        /// <remarks>
-        /// https://docs.microsoft.com/en-us/dotnet/framework/configure-apps/file-schema/runtime/gcallowverylargeobjects-element
-        /// </remarks>
-        private const int MaxByteArraySize = int.MaxValue - 56;
-
-        internal static void ResizeAndFlushLeft(ref byte[] buffer, int toFitAtLeastBytes, int copyFromIndex, int copyBytes)
-        {
-            Helpers.DebugAssert(buffer != null);
-            Helpers.DebugAssert(toFitAtLeastBytes > buffer.Length);
-            Helpers.DebugAssert(copyFromIndex >= 0);
-            Helpers.DebugAssert(copyBytes >= 0);
-
-            int newLength = buffer.Length * 2;
-            if (newLength < 0)
-            {
-                newLength = MaxByteArraySize;
-            }
-
-            if (newLength < toFitAtLeastBytes) newLength = toFitAtLeastBytes;
-
-            if (copyBytes == 0)
-            {
-                ReleaseBufferToPool(ref buffer);
-            }
-
-            var newBuffer = GetCachedBuffer(toFitAtLeastBytes) ?? new byte[newLength];
-
-            if (copyBytes > 0)
-            {
-                Buffer.BlockCopy(buffer, copyFromIndex, newBuffer, 0, copyBytes);
-                ReleaseBufferToPool(ref buffer);
-            }
-
-            buffer = newBuffer;
-        }
-
-        internal static void ReleaseBufferToPool(ref byte[] buffer)
-        {
-            if (buffer == null) return;
-
-            lock (Pool)
-            {
-                var minIndex = 0;
-                var minSize = int.MaxValue;
-                for (var i = 0; i < Pool.Length; i++)
-                {
-                    var tmp = Pool[i];
-                    if (tmp == null || !tmp.IsAlive)
-                    {
-                        minIndex = 0;
-                        break;
-                    }
-                    if (tmp.Size < minSize)
-                    {
-                        minIndex = i;
-                        minSize = tmp.Size;
-                    }
-                }
-
-                Pool[minIndex] = new CachedBuffer(buffer);
-            }
-
-            buffer = null;
-        }
-
-        private class CachedBuffer
-        {
-            private readonly WeakReference _reference;
-
-            public int Size { get; }
-
-            public bool IsAlive => _reference.IsAlive;
-            public byte[] Buffer => (byte[])_reference.Target;
-
-            public CachedBuffer(byte[] buffer)
-            {
-                Size = buffer.Length;
-                _reference = new WeakReference(buffer);
-            }
-        }
-    }
-}

+ 0 - 33
ThirdParty/protobuf-net/CallbackAttributes.cs

@@ -1,33 +0,0 @@
-using System;
-using System.ComponentModel;
-
-namespace ProtoBuf
-{
-    /// <summary>Specifies a method on the root-contract in an hierarchy to be invoked before serialization.</summary>
-    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
-#if !CF && !PORTABLE && !COREFX && !PROFILE259
-    [ImmutableObject(true)]
-#endif
-    public sealed class ProtoBeforeSerializationAttribute : Attribute { }
-
-    /// <summary>Specifies a method on the root-contract in an hierarchy to be invoked after serialization.</summary>
-    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
-#if !CF && !PORTABLE && !COREFX && !PROFILE259
-    [ImmutableObject(true)]
-#endif
-    public sealed class ProtoAfterSerializationAttribute : Attribute { }
-
-    /// <summary>Specifies a method on the root-contract in an hierarchy to be invoked before deserialization.</summary>
-    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
-#if !CF && !PORTABLE && !COREFX && !PROFILE259
-    [ImmutableObject(true)]
-#endif
-    public sealed class ProtoBeforeDeserializationAttribute : Attribute { }
-
-    /// <summary>Specifies a method on the root-contract in an hierarchy to be invoked after deserialization.</summary>
-    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
-#if !CF && !PORTABLE && !COREFX && !PROFILE259
-    [ImmutableObject(true)]
-#endif
-    public sealed class ProtoAfterDeserializationAttribute : Attribute { }
-}

+ 0 - 1435
ThirdParty/protobuf-net/Compiler/CompilerContext.cs

@@ -1,1435 +0,0 @@
-#if FEAT_COMPILER
-//#define DEBUG_COMPILE
-using System;
-using System.Threading;
-using ProtoBuf.Meta;
-using ProtoBuf.Serializers;
-using System.Reflection;
-using System.Reflection.Emit;
-
-namespace ProtoBuf.Compiler
-{
-    internal readonly struct CodeLabel
-    {
-        public readonly Label Value;
-        public readonly int Index;
-        public CodeLabel(Label value, int index)
-        {
-            this.Value = value;
-            this.Index = index;
-        }
-    }
-    internal sealed class CompilerContext
-    {
-        public TypeModel Model => model;
-
-        readonly DynamicMethod method;
-        static int next;
-
-        internal CodeLabel DefineLabel()
-        {
-            CodeLabel result = new CodeLabel(il.DefineLabel(), nextLabel++);
-            return result;
-        }
-#if DEBUG_COMPILE
-        static readonly string traceCompilePath;
-        static CompilerContext()
-        {
-            traceCompilePath = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(),
-                "TraceCompile.txt");
-            Console.WriteLine("DEBUG_COMPILE enabled; writing to " + traceCompilePath);
-        }
-#endif
-        [System.Diagnostics.Conditional("DEBUG_COMPILE")]
-        private void TraceCompile(string value)
-        {
-#if DEBUG_COMPILE
-            if (!string.IsNullOrWhiteSpace(value))
-            {
-                using (System.IO.StreamWriter sw = System.IO.File.AppendText(traceCompilePath))
-                {
-                    sw.WriteLine(value);
-                }
-            }
-#endif
-        }
-        internal void MarkLabel(CodeLabel label)
-        {
-            il.MarkLabel(label.Value);
-            TraceCompile("#: " + label.Index);
-        }
-
-        public static ProtoSerializer BuildSerializer(IProtoSerializer head, TypeModel model)
-        {
-            Type type = head.ExpectedType;
-            try
-            {
-                CompilerContext ctx = new CompilerContext(type, true, true, model, typeof(object));
-                ctx.LoadValue(ctx.InputValue);
-                ctx.CastFromObject(type);
-                ctx.WriteNullCheckedTail(type, head, null);
-                ctx.Emit(OpCodes.Ret);
-                return (ProtoSerializer)ctx.method.CreateDelegate(
-                    typeof(ProtoSerializer));
-            }
-            catch (Exception ex)
-            {
-                string name = type.FullName;
-                if (string.IsNullOrEmpty(name)) name = type.Name;
-                throw new InvalidOperationException("It was not possible to prepare a serializer for: " + name, ex);
-            }
-        }
-        /*public static ProtoCallback BuildCallback(IProtoTypeSerializer head)
-        {
-            Type type = head.ExpectedType;
-            CompilerContext ctx = new CompilerContext(type, true, true);
-            using (Local typedVal = new Local(ctx, type))
-            {
-                ctx.LoadValue(Local.InputValue);
-                ctx.CastFromObject(type);
-                ctx.StoreValue(typedVal);
-                CodeLabel[] jumpTable = new CodeLabel[4];
-                for(int i = 0 ; i < jumpTable.Length ; i++) {
-                    jumpTable[i] = ctx.DefineLabel();
-                }
-                ctx.LoadReaderWriter();
-                ctx.Switch(jumpTable);
-                ctx.Return();
-                for(int i = 0 ; i < jumpTable.Length ; i++) {
-                    ctx.MarkLabel(jumpTable[i]);
-                    if (head.HasCallbacks((TypeModel.CallbackType)i))
-                    {
-                        head.EmitCallback(ctx, typedVal, (TypeModel.CallbackType)i);
-                    }
-                    ctx.Return();
-                }                
-            }
-            
-            ctx.Emit(OpCodes.Ret);
-            return (ProtoCallback)ctx.method.CreateDelegate(
-                typeof(ProtoCallback));
-        }*/
-        public static ProtoDeserializer BuildDeserializer(IProtoSerializer head, TypeModel model)
-        {
-            Type type = head.ExpectedType;
-            CompilerContext ctx = new CompilerContext(type, false, true, model, typeof(object));
-
-            using (Local typedVal = new Local(ctx, type))
-            {
-                if (!Helpers.IsValueType(type))
-                {
-                    ctx.LoadValue(ctx.InputValue);
-                    ctx.CastFromObject(type);
-                    ctx.StoreValue(typedVal);
-                }
-                else
-                {
-                    ctx.LoadValue(ctx.InputValue);
-                    CodeLabel notNull = ctx.DefineLabel(), endNull = ctx.DefineLabel();
-                    ctx.BranchIfTrue(notNull, true);
-
-                    ctx.LoadAddress(typedVal, type);
-                    ctx.EmitCtor(type);
-                    ctx.Branch(endNull, true);
-
-                    ctx.MarkLabel(notNull);
-                    ctx.LoadValue(ctx.InputValue);
-                    ctx.CastFromObject(type);
-                    ctx.StoreValue(typedVal);
-
-                    ctx.MarkLabel(endNull);
-                }
-                head.EmitRead(ctx, typedVal);
-
-                if (head.ReturnsValue)
-                {
-                    ctx.StoreValue(typedVal);
-                }
-
-                ctx.LoadValue(typedVal);
-                ctx.CastToObject(type);
-            }
-            ctx.Emit(OpCodes.Ret);
-            return (ProtoDeserializer)ctx.method.CreateDelegate(
-                typeof(ProtoDeserializer));
-        }
-
-        internal void Return()
-        {
-            Emit(OpCodes.Ret);
-        }
-
-        static bool IsObject(Type type)
-        {
-            return type == typeof(object);
-        }
-
-        internal void CastToObject(Type type)
-        {
-            if (IsObject(type))
-            { }
-            else if (Helpers.IsValueType(type))
-            {
-                il.Emit(OpCodes.Box, type);
-                TraceCompile(OpCodes.Box + ": " + type);
-            }
-            else
-            {
-                il.Emit(OpCodes.Castclass, MapType(typeof(object)));
-                TraceCompile(OpCodes.Castclass + ": " + type);
-            }
-        }
-
-        internal void CastFromObject(Type type)
-        {
-            if (IsObject(type))
-            { }
-            else if (Helpers.IsValueType(type))
-            {
-                switch (MetadataVersion)
-                {
-                    case ILVersion.Net1:
-                        il.Emit(OpCodes.Unbox, type);
-                        il.Emit(OpCodes.Ldobj, type);
-                        TraceCompile(OpCodes.Unbox + ": " + type);
-                        TraceCompile(OpCodes.Ldobj + ": " + type);
-                        break;
-                    default:
-
-                        il.Emit(OpCodes.Unbox_Any, type);
-                        TraceCompile(OpCodes.Unbox_Any + ": " + type);
-                        break;
-                }
-            }
-            else
-            {
-                il.Emit(OpCodes.Castclass, type);
-                TraceCompile(OpCodes.Castclass + ": " + type);
-            }
-        }
-        private readonly bool isStatic;
-        private readonly RuntimeTypeModel.SerializerPair[] methodPairs;
-
-        internal MethodBuilder GetDedicatedMethod(int metaKey, bool read)
-        {
-            if (methodPairs == null) return null;
-            // but if we *do* have pairs, we demand that we find a match...
-            for (int i = 0; i < methodPairs.Length; i++)
-            {
-                if (methodPairs[i].MetaKey == metaKey) { return read ? methodPairs[i].Deserialize : methodPairs[i].Serialize; }
-            }
-            throw new ArgumentException("Meta-key not found", "metaKey");
-        }
-
-        internal int MapMetaKeyToCompiledKey(int metaKey)
-        {
-            if (metaKey < 0 || methodPairs == null) return metaKey; // all meta, or a dummy/wildcard key
-
-            for (int i = 0; i < methodPairs.Length; i++)
-            {
-                if (methodPairs[i].MetaKey == metaKey) return i;
-            }
-            throw new ArgumentException("Key could not be mapped: " + metaKey.ToString(), "metaKey");
-        }
-
-
-        private readonly bool isWriter;
-
-        private readonly bool nonPublic;
-        internal bool NonPublic { get { return nonPublic; } }
-
-        private readonly Local inputValue;
-        public Local InputValue { get { return inputValue; } }
-
-        private readonly string assemblyName;
-        internal CompilerContext(ILGenerator il, bool isStatic, bool isWriter, RuntimeTypeModel.SerializerPair[] methodPairs, TypeModel model, ILVersion metadataVersion, string assemblyName, Type inputType, string traceName)
-        {
-            if (string.IsNullOrEmpty(assemblyName)) throw new ArgumentNullException(nameof(assemblyName));
-            this.assemblyName = assemblyName;
-            this.isStatic = isStatic;
-            this.methodPairs = methodPairs ?? throw new ArgumentNullException(nameof(methodPairs));
-            this.il = il ?? throw new ArgumentNullException(nameof(il));
-            // nonPublic = false; <== implicit
-            this.isWriter = isWriter;
-            this.model = model ?? throw new ArgumentNullException(nameof(model));
-            this.metadataVersion = metadataVersion;
-            if (inputType != null) this.inputValue = new Local(null, inputType);
-            TraceCompile(">> " + traceName);
-        }
-
-        private CompilerContext(Type associatedType, bool isWriter, bool isStatic, TypeModel model, Type inputType)
-        {
-            metadataVersion = ILVersion.Net2;
-            this.isStatic = isStatic;
-            this.isWriter = isWriter;
-            this.model = model ?? throw new ArgumentNullException(nameof(model));
-            nonPublic = true;
-            Type[] paramTypes;
-            Type returnType;
-            if (isWriter)
-            {
-                returnType = typeof(void);
-                paramTypes = new Type[] { typeof(object), typeof(ProtoWriter) };
-            }
-            else
-            {
-                returnType = typeof(object);
-                paramTypes = new Type[] { typeof(object), typeof(ProtoReader) };
-            }
-            int uniqueIdentifier;
-#if PLAT_NO_INTERLOCKED
-            uniqueIdentifier = ++next;
-#else
-            uniqueIdentifier = Interlocked.Increment(ref next);
-#endif
-            method = new DynamicMethod("proto_" + uniqueIdentifier.ToString(), returnType, paramTypes, associatedType
-#if COREFX
-                .GetTypeInfo()
-#endif
-                .IsInterface ? typeof(object) : associatedType, true);
-            this.il = method.GetILGenerator();
-            if (inputType != null) this.inputValue = new Local(null, inputType);
-            TraceCompile(">> " + method.Name);
-        }
-
-        private readonly ILGenerator il;
-
-        private void Emit(OpCode opcode)
-        {
-            il.Emit(opcode);
-            TraceCompile(opcode.ToString());
-        }
-
-        public void LoadValue(string value)
-        {
-            if (value == null)
-            {
-                LoadNullRef();
-            }
-            else
-            {
-                il.Emit(OpCodes.Ldstr, value);
-                TraceCompile(OpCodes.Ldstr + ": " + value);
-            }
-        }
-
-        public void LoadValue(float value)
-        {
-            il.Emit(OpCodes.Ldc_R4, value);
-            TraceCompile(OpCodes.Ldc_R4 + ": " + value);
-        }
-
-        public void LoadValue(double value)
-        {
-            il.Emit(OpCodes.Ldc_R8, value);
-            TraceCompile(OpCodes.Ldc_R8 + ": " + value);
-        }
-
-        public void LoadValue(long value)
-        {
-            il.Emit(OpCodes.Ldc_I8, value);
-            TraceCompile(OpCodes.Ldc_I8 + ": " + value);
-        }
-
-        public void LoadValue(int value)
-        {
-            switch (value)
-            {
-                case 0: Emit(OpCodes.Ldc_I4_0); break;
-                case 1: Emit(OpCodes.Ldc_I4_1); break;
-                case 2: Emit(OpCodes.Ldc_I4_2); break;
-                case 3: Emit(OpCodes.Ldc_I4_3); break;
-                case 4: Emit(OpCodes.Ldc_I4_4); break;
-                case 5: Emit(OpCodes.Ldc_I4_5); break;
-                case 6: Emit(OpCodes.Ldc_I4_6); break;
-                case 7: Emit(OpCodes.Ldc_I4_7); break;
-                case 8: Emit(OpCodes.Ldc_I4_8); break;
-                case -1: Emit(OpCodes.Ldc_I4_M1); break;
-                default:
-                    if (value >= -128 && value <= 127)
-                    {
-                        il.Emit(OpCodes.Ldc_I4_S, (sbyte)value);
-                        TraceCompile(OpCodes.Ldc_I4_S + ": " + value);
-                    }
-                    else
-                    {
-                        il.Emit(OpCodes.Ldc_I4, value);
-                        TraceCompile(OpCodes.Ldc_I4 + ": " + value);
-                    }
-                    break;
-
-            }
-        }
-
-        MutableList locals = new MutableList();
-        internal LocalBuilder GetFromPool(Type type)
-        {
-            int count = locals.Count;
-            for (int i = 0; i < count; i++)
-            {
-                LocalBuilder item = (LocalBuilder)locals[i];
-                if (item != null && item.LocalType == type)
-                {
-                    locals[i] = null; // remove from pool
-                    return item;
-                }
-            }
-            LocalBuilder result = il.DeclareLocal(type);
-            TraceCompile("$ " + result + ": " + type);
-            return result;
-        }
-
-        //
-        internal void ReleaseToPool(LocalBuilder value)
-        {
-            int count = locals.Count;
-            for (int i = 0; i < count; i++)
-            {
-                if (locals[i] == null)
-                {
-                    locals[i] = value; // released into existing slot
-                    return;
-                }
-            }
-            locals.Add(value); // create a new slot
-        }
-
-        public void LoadReaderWriter()
-        {
-            Emit(isStatic ? OpCodes.Ldarg_1 : OpCodes.Ldarg_2);
-        }
-
-        public void StoreValue(Local local)
-        {
-            if (local == this.InputValue)
-            {
-                byte b = isStatic ? (byte)0 : (byte)1;
-                il.Emit(OpCodes.Starg_S, b);
-                TraceCompile(OpCodes.Starg_S + ": $" + b);
-            }
-            else
-            {
-
-                switch (local.Value.LocalIndex)
-                {
-                    case 0: Emit(OpCodes.Stloc_0); break;
-                    case 1: Emit(OpCodes.Stloc_1); break;
-                    case 2: Emit(OpCodes.Stloc_2); break;
-                    case 3: Emit(OpCodes.Stloc_3); break;
-                    default:
-
-                        OpCode code = UseShortForm(local) ? OpCodes.Stloc_S : OpCodes.Stloc;
-                        il.Emit(code, local.Value);
-                        TraceCompile(code + ": $" + local.Value);
-
-                        break;
-                }
-            }
-        }
-
-        public void LoadValue(Local local)
-        {
-            if (local == null) { /* nothing to do; top of stack */}
-            else if (local == this.InputValue)
-            {
-                Emit(isStatic ? OpCodes.Ldarg_0 : OpCodes.Ldarg_1);
-            }
-            else
-            {
-
-                switch (local.Value.LocalIndex)
-                {
-                    case 0: Emit(OpCodes.Ldloc_0); break;
-                    case 1: Emit(OpCodes.Ldloc_1); break;
-                    case 2: Emit(OpCodes.Ldloc_2); break;
-                    case 3: Emit(OpCodes.Ldloc_3); break;
-                    default:
-
-                        OpCode code = UseShortForm(local) ? OpCodes.Ldloc_S : OpCodes.Ldloc;
-                        il.Emit(code, local.Value);
-                        TraceCompile(code + ": $" + local.Value);
-
-                        break;
-                }
-            }
-        }
-
-        public Local GetLocalWithValue(Type type, Compiler.Local fromValue)
-        {
-            if (fromValue != null)
-            {
-                if (fromValue.Type == type) return fromValue.AsCopy();
-                // otherwise, load onto the stack and let the default handling (below) deal with it
-                LoadValue(fromValue);
-                if (!Helpers.IsValueType(type) && (fromValue.Type == null || !type.IsAssignableFrom(fromValue.Type)))
-                { // need to cast
-                    Cast(type);
-                }
-            }
-            // need to store the value from the stack
-            Local result = new Local(this, type);
-            StoreValue(result);
-            return result;
-        }
-
-        internal void EmitBasicRead(string methodName, Type expectedType)
-        {
-            MethodInfo method = MapType(typeof(ProtoReader)).GetMethod(
-                methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
-            if (method == null || method.ReturnType != expectedType
-                || method.GetParameters().Length != 0) throw new ArgumentException("methodName");
-            LoadReaderWriter();
-            EmitCall(method);
-        }
-
-        internal void EmitBasicRead(Type helperType, string methodName, Type expectedType)
-        {
-            MethodInfo method = helperType.GetMethod(
-                methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
-            if (method == null || method.ReturnType != expectedType
-                || method.GetParameters().Length != 1) throw new ArgumentException("methodName");
-            LoadReaderWriter();
-            EmitCall(method);
-        }
-
-        internal void EmitBasicWrite(string methodName, Compiler.Local fromValue)
-        {
-            if (string.IsNullOrEmpty(methodName)) throw new ArgumentNullException("methodName");
-            LoadValue(fromValue);
-            LoadReaderWriter();
-            EmitCall(GetWriterMethod(methodName));
-        }
-
-        private MethodInfo GetWriterMethod(string methodName)
-        {
-            Type writerType = MapType(typeof(ProtoWriter));
-            MethodInfo[] methods = writerType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
-            foreach (MethodInfo method in methods)
-            {
-                if (method.Name != methodName) continue;
-                ParameterInfo[] pis = method.GetParameters();
-                if (pis.Length == 2 && pis[1].ParameterType == writerType) return method;
-            }
-            throw new ArgumentException("No suitable method found for: " + methodName, "methodName");
-        }
-
-        internal void EmitWrite(Type helperType, string methodName, Compiler.Local valueFrom)
-        {
-            if (string.IsNullOrEmpty(methodName)) throw new ArgumentNullException("methodName");
-            MethodInfo method = helperType.GetMethod(
-                methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
-            if (method == null || method.ReturnType != MapType(typeof(void))) throw new ArgumentException("methodName");
-            LoadValue(valueFrom);
-            LoadReaderWriter();
-            EmitCall(method);
-        }
-
-        public void EmitCall(MethodInfo method) { EmitCall(method, null); }
-
-        public void EmitCall(MethodInfo method, Type targetType)
-        {
-            Helpers.DebugAssert(method != null);
-            MemberInfo member = method;
-            CheckAccessibility(ref member);
-            OpCode opcode;
-            if (method.IsStatic || Helpers.IsValueType(method.DeclaringType))
-            {
-                opcode = OpCodes.Call;
-            }
-            else
-            {
-                opcode = OpCodes.Callvirt;
-                if (targetType != null && Helpers.IsValueType(targetType) && !Helpers.IsValueType(method.DeclaringType))
-                {
-                    Constrain(targetType);
-                }
-            }
-            il.EmitCall(opcode, method, null);
-            TraceCompile(opcode + ": " + method + " on " + method.DeclaringType + (targetType == null ? "" : (" via " + targetType)));
-        }
-
-        /// <summary>
-        /// Pushes a null reference onto the stack. Note that this should only
-        /// be used to return a null (or set a variable to null); for null-tests
-        /// use BranchIfTrue / BranchIfFalse.
-        /// </summary>
-        public void LoadNullRef()
-        {
-            Emit(OpCodes.Ldnull);
-        }
-
-        private int nextLabel;
-
-        internal void WriteNullCheckedTail(Type type, IProtoSerializer tail, Compiler.Local valueFrom)
-        {
-            if (Helpers.IsValueType(type))
-            {
-                Type underlyingType = Helpers.GetUnderlyingType(type);
-
-                if (underlyingType == null)
-                { // not a nullable T; can invoke directly
-                    tail.EmitWrite(this, valueFrom);
-                }
-                else
-                { // nullable T; check HasValue
-                    using (Compiler.Local valOrNull = GetLocalWithValue(type, valueFrom))
-                    {
-                        LoadAddress(valOrNull, type);
-                        LoadValue(type.GetProperty("HasValue"));
-                        CodeLabel @end = DefineLabel();
-                        BranchIfFalse(@end, false);
-                        LoadAddress(valOrNull, type);
-                        EmitCall(type.GetMethod("GetValueOrDefault", Helpers.EmptyTypes));
-                        tail.EmitWrite(this, null);
-                        MarkLabel(@end);
-                    }
-                }
-            }
-            else
-            { // ref-type; do a null-check
-                LoadValue(valueFrom);
-                CopyValue();
-                CodeLabel hasVal = DefineLabel(), @end = DefineLabel();
-                BranchIfTrue(hasVal, true);
-                DiscardValue();
-                Branch(@end, false);
-                MarkLabel(hasVal);
-                tail.EmitWrite(this, null);
-                MarkLabel(@end);
-            }
-        }
-
-        internal void ReadNullCheckedTail(Type type, IProtoSerializer tail, Compiler.Local valueFrom)
-        {
-
-            Type underlyingType;
-
-            if (Helpers.IsValueType(type) && (underlyingType = Helpers.GetUnderlyingType(type)) != null)
-            {
-                if (tail.RequiresOldValue)
-                {
-                    // we expect the input value to be in valueFrom; need to unpack it from T?
-                    using (Local loc = GetLocalWithValue(type, valueFrom))
-                    {
-                        LoadAddress(loc, type);
-                        EmitCall(type.GetMethod("GetValueOrDefault", Helpers.EmptyTypes));
-                    }
-                }
-                else
-                {
-                    Helpers.DebugAssert(valueFrom == null); // not expecting a valueFrom in this case
-                }
-                tail.EmitRead(this, null); // either unwrapped on the stack or not provided
-                if (tail.ReturnsValue)
-                {
-                    // now re-wrap the value
-                    EmitCtor(type, underlyingType);
-                }
-                return;
-            }
-
-            // either a ref-type of a non-nullable struct; treat "as is", even if null
-            // (the type-serializer will handle the null case; it needs to allow null
-            // inputs to perform the correct type of subclass creation)
-            tail.EmitRead(this, valueFrom);
-        }
-
-        public void EmitCtor(Type type)
-        {
-            EmitCtor(type, Helpers.EmptyTypes);
-        }
-
-        public void EmitCtor(ConstructorInfo ctor)
-        {
-            if (ctor == null) throw new ArgumentNullException("ctor");
-            MemberInfo ctorMember = ctor;
-            CheckAccessibility(ref ctorMember);
-            il.Emit(OpCodes.Newobj, ctor);
-            TraceCompile(OpCodes.Newobj + ": " + ctor.DeclaringType);
-        }
-
-        public void InitLocal(Type type, Compiler.Local target)
-        {
-            LoadAddress(target, type, evenIfClass: true); // for class, initobj is a load-null, store-indirect
-            il.Emit(OpCodes.Initobj, type);
-            TraceCompile(OpCodes.Initobj + ": " + type);
-        }
-
-        public void EmitCtor(Type type, params Type[] parameterTypes)
-        {
-            Helpers.DebugAssert(type != null);
-            Helpers.DebugAssert(parameterTypes != null);
-            if (Helpers.IsValueType(type) && parameterTypes.Length == 0)
-            {
-                il.Emit(OpCodes.Initobj, type);
-                TraceCompile(OpCodes.Initobj + ": " + type);
-            }
-            else
-            {
-                ConstructorInfo ctor = Helpers.GetConstructor(type
-#if COREFX
-                .GetTypeInfo()
-#endif
-                    , parameterTypes, true);
-                if (ctor == null) throw new InvalidOperationException("No suitable constructor found for " + type.FullName);
-                EmitCtor(ctor);
-            }
-        }
-
-        BasicList knownTrustedAssemblies, knownUntrustedAssemblies;
-
-        bool InternalsVisible(Assembly assembly)
-        {
-            if (string.IsNullOrEmpty(assemblyName)) return false;
-            if (knownTrustedAssemblies != null)
-            {
-                if (knownTrustedAssemblies.IndexOfReference(assembly) >= 0)
-                {
-                    return true;
-                }
-            }
-            if (knownUntrustedAssemblies != null)
-            {
-                if (knownUntrustedAssemblies.IndexOfReference(assembly) >= 0)
-                {
-                    return false;
-                }
-            }
-            bool isTrusted = false;
-            Type attributeType = MapType(typeof(System.Runtime.CompilerServices.InternalsVisibleToAttribute));
-            if (attributeType == null) return false;
-
-#if COREFX
-            foreach (System.Runtime.CompilerServices.InternalsVisibleToAttribute attrib in assembly.GetCustomAttributes(attributeType))
-#else
-            foreach (System.Runtime.CompilerServices.InternalsVisibleToAttribute attrib in assembly.GetCustomAttributes(attributeType, false))
-#endif
-            {
-                if (attrib.AssemblyName == assemblyName || attrib.AssemblyName.StartsWith(assemblyName + ","))
-                {
-                    isTrusted = true;
-                    break;
-                }
-            }
-
-            if (isTrusted)
-            {
-                if (knownTrustedAssemblies == null) knownTrustedAssemblies = new BasicList();
-                knownTrustedAssemblies.Add(assembly);
-            }
-            else
-            {
-                if (knownUntrustedAssemblies == null) knownUntrustedAssemblies = new BasicList();
-                knownUntrustedAssemblies.Add(assembly);
-            }
-            return isTrusted;
-        }
-
-        internal void CheckAccessibility(ref MemberInfo member)
-        {
-            if (member == null)
-            {
-                throw new ArgumentNullException(nameof(member));
-            }
-#if !COREFX
-            Type type;
-#endif
-            if (!NonPublic)
-            {
-                if (member is FieldInfo && member.Name.StartsWith("<") & member.Name.EndsWith(">k__BackingField"))
-                {
-                    var propName = member.Name.Substring(1, member.Name.Length - 17);
-                    var prop = member.DeclaringType.GetProperty(propName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
-                    if (prop != null) member = prop;
-                }
-                bool isPublic;
-#if COREFX
-                if (member is TypeInfo)
-                {
-                    TypeInfo ti = (TypeInfo)member;
-                    do
-                    {
-                        isPublic = ti.IsNestedPublic || ti.IsPublic || ((ti.IsNested || ti.IsNestedAssembly || ti.IsNestedFamORAssem) && InternalsVisible(ti.Assembly));
-                    } while (isPublic && ti.IsNested && (ti = ti.DeclaringType.GetTypeInfo()) != null);
-                }
-                else if (member is FieldInfo)
-                {
-                    FieldInfo field = ((FieldInfo)member);
-                    isPublic = field.IsPublic || ((field.IsAssembly || field.IsFamilyOrAssembly) && InternalsVisible(Helpers.GetAssembly(field.DeclaringType)));
-                }
-                else if (member is PropertyInfo)
-                {
-                    isPublic = true; // defer to get/set
-                }
-                else if (member is ConstructorInfo)
-                {
-                    ConstructorInfo ctor = ((ConstructorInfo)member);
-                    isPublic = ctor.IsPublic || ((ctor.IsAssembly || ctor.IsFamilyOrAssembly) && InternalsVisible(Helpers.GetAssembly(ctor.DeclaringType)));
-                }
-                else if (member is MethodInfo)
-                {
-                    MethodInfo method = ((MethodInfo)member);
-                    isPublic = method.IsPublic || ((method.IsAssembly || method.IsFamilyOrAssembly) && InternalsVisible(Helpers.GetAssembly(method.DeclaringType)));
-                    if (!isPublic)
-                    {
-                        // allow calls to TypeModel protected methods, and methods we are in the process of creating
-                        if (
-                                member is MethodBuilder ||
-                                member.DeclaringType == MapType(typeof(TypeModel)))
-                            isPublic = true;
-                    }
-                }
-                else
-                {
-                    throw new NotSupportedException(member.GetType().Name);
-                }
-#else
-                MemberTypes memberType = member.MemberType;
-                switch (memberType)
-                {
-                    case MemberTypes.TypeInfo:
-                        // top-level type
-                        type = (Type)member;
-                        isPublic = type.IsPublic || InternalsVisible(type.Assembly);
-                        break;
-                    case MemberTypes.NestedType:
-                        type = (Type)member;
-                        do
-                        {
-                            isPublic = type.IsNestedPublic || type.IsPublic || ((type.DeclaringType == null || type.IsNestedAssembly || type.IsNestedFamORAssem) && InternalsVisible(type.Assembly));
-                        } while (isPublic && (type = type.DeclaringType) != null); // ^^^ !type.IsNested, but not all runtimes have that
-                        break;
-                    case MemberTypes.Field:
-                        FieldInfo field = ((FieldInfo)member);
-                        isPublic = field.IsPublic || ((field.IsAssembly || field.IsFamilyOrAssembly) && InternalsVisible(field.DeclaringType.Assembly));
-                        break;
-                    case MemberTypes.Constructor:
-                        ConstructorInfo ctor = ((ConstructorInfo)member);
-                        isPublic = ctor.IsPublic || ((ctor.IsAssembly || ctor.IsFamilyOrAssembly) && InternalsVisible(ctor.DeclaringType.Assembly));
-                        break;
-                    case MemberTypes.Method:
-                        MethodInfo method = ((MethodInfo)member);
-                        isPublic = method.IsPublic || ((method.IsAssembly || method.IsFamilyOrAssembly) && InternalsVisible(method.DeclaringType.Assembly));
-                        if (!isPublic)
-                        {
-                            // allow calls to TypeModel protected methods, and methods we are in the process of creating
-                            if (
-                                member is MethodBuilder ||
-                                member.DeclaringType == MapType(typeof(TypeModel))) isPublic = true;
-                        }
-                        break;
-                    case MemberTypes.Property:
-                        isPublic = true; // defer to get/set
-                        break;
-                    default:
-                        throw new NotSupportedException(memberType.ToString());
-                }
-#endif
-                if (!isPublic)
-                {
-#if COREFX
-                    if (member is TypeInfo)
-                    {
-                        throw new InvalidOperationException("Non-public type cannot be used with full dll compilation: " +
-                                ((TypeInfo)member).FullName);
-                    }
-                    else
-                    {
-                        throw new InvalidOperationException("Non-public member cannot be used with full dll compilation: " +
-                                member.DeclaringType.FullName + "." + member.Name);
-                    }
-
-#else
-                    switch (memberType)
-                    {
-                        case MemberTypes.TypeInfo:
-                        case MemberTypes.NestedType:
-                            throw new InvalidOperationException("Non-public type cannot be used with full dll compilation: " +
-                                ((Type)member).FullName);
-                        default:
-                            throw new InvalidOperationException("Non-public member cannot be used with full dll compilation: " +
-                                member.DeclaringType.FullName + "." + member.Name);
-                    }
-#endif
-
-                }
-            }
-        }
-
-        public void LoadValue(FieldInfo field)
-        {
-            MemberInfo member = field;
-            CheckAccessibility(ref member);
-            if (member is PropertyInfo)
-            {
-                LoadValue((PropertyInfo)member);
-            }
-            else
-            {
-                OpCode code = field.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld;
-                il.Emit(code, field);
-                TraceCompile(code + ": " + field + " on " + field.DeclaringType);
-            }
-        }
-
-        public void StoreValue(FieldInfo field)
-        {
-            MemberInfo member = field;
-            CheckAccessibility(ref member);
-            if (member is PropertyInfo)
-            {
-                StoreValue((PropertyInfo)member);
-            }
-            else
-            {
-                OpCode code = field.IsStatic ? OpCodes.Stsfld : OpCodes.Stfld;
-                il.Emit(code, field);
-                TraceCompile(code + ": " + field + " on " + field.DeclaringType);
-            }
-        }
-
-        public void LoadValue(PropertyInfo property)
-        {
-            MemberInfo member = property;
-            CheckAccessibility(ref member);
-            EmitCall(Helpers.GetGetMethod(property, true, true));
-        }
-
-        public void StoreValue(PropertyInfo property)
-        {
-            MemberInfo member = property;
-            CheckAccessibility(ref member);
-            EmitCall(Helpers.GetSetMethod(property, true, true));
-        }
-
-        //internal void EmitInstance()
-        //{
-        //    if (isStatic) throw new InvalidOperationException();
-        //    Emit(OpCodes.Ldarg_0);
-        //}
-
-        internal static void LoadValue(ILGenerator il, int value)
-        {
-            switch (value)
-            {
-                case 0: il.Emit(OpCodes.Ldc_I4_0); break;
-                case 1: il.Emit(OpCodes.Ldc_I4_1); break;
-                case 2: il.Emit(OpCodes.Ldc_I4_2); break;
-                case 3: il.Emit(OpCodes.Ldc_I4_3); break;
-                case 4: il.Emit(OpCodes.Ldc_I4_4); break;
-                case 5: il.Emit(OpCodes.Ldc_I4_5); break;
-                case 6: il.Emit(OpCodes.Ldc_I4_6); break;
-                case 7: il.Emit(OpCodes.Ldc_I4_7); break;
-                case 8: il.Emit(OpCodes.Ldc_I4_8); break;
-                case -1: il.Emit(OpCodes.Ldc_I4_M1); break;
-                default: il.Emit(OpCodes.Ldc_I4, value); break;
-            }
-        }
-
-        private bool UseShortForm(Local local)
-        {
-            return local.Value.LocalIndex < 256;
-        }
-
-        internal void LoadAddress(Local local, Type type, bool evenIfClass = false)
-        {
-            if (evenIfClass || Helpers.IsValueType(type))
-            {
-                if (local == null)
-                {
-                    throw new InvalidOperationException("Cannot load the address of the head of the stack");
-                }
-
-                if (local == this.InputValue)
-                {
-                    il.Emit(OpCodes.Ldarga_S, (isStatic ? (byte)0 : (byte)1));
-                    TraceCompile(OpCodes.Ldarga_S + ": $" + (isStatic ? 0 : 1));
-                }
-                else
-                {
-                    OpCode code = UseShortForm(local) ? OpCodes.Ldloca_S : OpCodes.Ldloca;
-                    il.Emit(code, local.Value);
-                    TraceCompile(code + ": $" + local.Value);
-                }
-
-            }
-            else
-            {   // reference-type; already *is* the address; just load it
-                LoadValue(local);
-            }
-        }
-
-        internal void Branch(CodeLabel label, bool @short)
-        {
-            OpCode code = @short ? OpCodes.Br_S : OpCodes.Br;
-            il.Emit(code, label.Value);
-            TraceCompile(code + ": " + label.Index);
-        }
-
-        internal void BranchIfFalse(CodeLabel label, bool @short)
-        {
-            OpCode code = @short ? OpCodes.Brfalse_S : OpCodes.Brfalse;
-            il.Emit(code, label.Value);
-            TraceCompile(code + ": " + label.Index);
-        }
-
-        internal void BranchIfTrue(CodeLabel label, bool @short)
-        {
-            OpCode code = @short ? OpCodes.Brtrue_S : OpCodes.Brtrue;
-            il.Emit(code, label.Value);
-            TraceCompile(code + ": " + label.Index);
-        }
-
-        internal void BranchIfEqual(CodeLabel label, bool @short)
-        {
-            OpCode code = @short ? OpCodes.Beq_S : OpCodes.Beq;
-            il.Emit(code, label.Value);
-            TraceCompile(code + ": " + label.Index);
-        }
-
-        //internal void TestEqual()
-        //{
-        //    Emit(OpCodes.Ceq);
-        //}
-
-        internal void CopyValue()
-        {
-            Emit(OpCodes.Dup);
-        }
-
-        internal void BranchIfGreater(CodeLabel label, bool @short)
-        {
-            OpCode code = @short ? OpCodes.Bgt_S : OpCodes.Bgt;
-            il.Emit(code, label.Value);
-            TraceCompile(code + ": " + label.Index);
-        }
-
-        internal void BranchIfLess(CodeLabel label, bool @short)
-        {
-            OpCode code = @short ? OpCodes.Blt_S : OpCodes.Blt;
-            il.Emit(code, label.Value);
-            TraceCompile(code + ": " + label.Index);
-        }
-
-        internal void DiscardValue()
-        {
-            Emit(OpCodes.Pop);
-        }
-
-        public void Subtract()
-        {
-            Emit(OpCodes.Sub);
-        }
-
-        public void Switch(CodeLabel[] jumpTable)
-        {
-            const int MAX_JUMPS = 128;
-
-            if (jumpTable.Length <= MAX_JUMPS)
-            {
-                // simple case
-                Label[] labels = new Label[jumpTable.Length];
-                for (int i = 0; i < labels.Length; i++)
-                {
-                    labels[i] = jumpTable[i].Value;
-                }
-                TraceCompile(OpCodes.Switch.ToString());
-                il.Emit(OpCodes.Switch, labels);
-            }
-            else
-            {
-                // too many to jump easily (especially on Android) - need to split up (note: uses a local pulled from the stack)
-                using (Local val = GetLocalWithValue(MapType(typeof(int)), null))
-                {
-                    int count = jumpTable.Length, offset = 0;
-                    int blockCount = count / MAX_JUMPS;
-                    if ((count % MAX_JUMPS) != 0) blockCount++;
-
-                    Label[] blockLabels = new Label[blockCount];
-                    for (int i = 0; i < blockCount; i++)
-                    {
-                        blockLabels[i] = il.DefineLabel();
-                    }
-                    CodeLabel endOfSwitch = DefineLabel();
-
-                    LoadValue(val);
-                    LoadValue(MAX_JUMPS);
-                    Emit(OpCodes.Div);
-                    TraceCompile(OpCodes.Switch.ToString());
-                    il.Emit(OpCodes.Switch, blockLabels);
-                    Branch(endOfSwitch, false);
-
-                    Label[] innerLabels = new Label[MAX_JUMPS];
-                    for (int blockIndex = 0; blockIndex < blockCount; blockIndex++)
-                    {
-                        il.MarkLabel(blockLabels[blockIndex]);
-
-                        int itemsThisBlock = Math.Min(MAX_JUMPS, count);
-                        count -= itemsThisBlock;
-                        if (innerLabels.Length != itemsThisBlock) innerLabels = new Label[itemsThisBlock];
-
-                        int subtract = offset;
-                        for (int j = 0; j < itemsThisBlock; j++)
-                        {
-                            innerLabels[j] = jumpTable[offset++].Value;
-                        }
-                        LoadValue(val);
-                        if (subtract != 0) // switches are always zero-based
-                        {
-                            LoadValue(subtract);
-                            Emit(OpCodes.Sub);
-                        }
-                        TraceCompile(OpCodes.Switch.ToString());
-                        il.Emit(OpCodes.Switch, innerLabels);
-                        if (count != 0)
-                        { // force default to the very bottom
-                            Branch(endOfSwitch, false);
-                        }
-                    }
-                    Helpers.DebugAssert(count == 0, "Should use exactly all switch items");
-                    MarkLabel(endOfSwitch);
-                }
-            }
-        }
-
-        internal void EndFinally()
-        {
-            il.EndExceptionBlock();
-            TraceCompile("EndExceptionBlock");
-        }
-
-        internal void BeginFinally()
-        {
-            il.BeginFinallyBlock();
-            TraceCompile("BeginFinallyBlock");
-        }
-
-        internal void EndTry(CodeLabel label, bool @short)
-        {
-            OpCode code = @short ? OpCodes.Leave_S : OpCodes.Leave;
-            il.Emit(code, label.Value);
-            TraceCompile(code + ": " + label.Index);
-        }
-
-        internal CodeLabel BeginTry()
-        {
-            CodeLabel label = new CodeLabel(il.BeginExceptionBlock(), nextLabel++);
-            TraceCompile("BeginExceptionBlock: " + label.Index);
-            return label;
-        }
-
-        internal void Constrain(Type type)
-        {
-            il.Emit(OpCodes.Constrained, type);
-            TraceCompile(OpCodes.Constrained + ": " + type);
-        }
-
-        internal void TryCast(Type type)
-        {
-            il.Emit(OpCodes.Isinst, type);
-            TraceCompile(OpCodes.Isinst + ": " + type);
-        }
-
-        internal void Cast(Type type)
-        {
-            il.Emit(OpCodes.Castclass, type);
-            TraceCompile(OpCodes.Castclass + ": " + type);
-        }
-
-        public IDisposable Using(Local local)
-        {
-            return new UsingBlock(this, local);
-        }
-
-        private sealed class UsingBlock : IDisposable
-        {
-            private Local local;
-            CompilerContext ctx;
-            CodeLabel label;
-            /// <summary>
-            /// Creates a new "using" block (equivalent) around a variable;
-            /// the variable must exist, and note that (unlike in C#) it is
-            /// the variables *final* value that gets disposed. If you need
-            /// *original* disposal, copy your variable first.
-            /// 
-            /// It is the callers responsibility to ensure that the variable's
-            /// scope fully-encapsulates the "using"; if not, the variable
-            /// may be re-used (and thus re-assigned) unexpectedly.
-            /// </summary>
-            public UsingBlock(CompilerContext ctx, Local local)
-            {
-                if (ctx == null) throw new ArgumentNullException("ctx");
-                if (local == null) throw new ArgumentNullException("local");
-
-                Type type = local.Type;
-                // check if **never** disposable
-                if ((Helpers.IsValueType(type) || Helpers.IsSealed(type)) &&
-                    !ctx.MapType(typeof(IDisposable)).IsAssignableFrom(type))
-                {
-                    return; // nothing to do! easiest "using" block ever
-                    // (note that C# wouldn't allow this as a "using" block,
-                    // but we'll be generous and simply not do anything)
-                }
-                this.local = local;
-                this.ctx = ctx;
-                label = ctx.BeginTry();
-
-            }
-            public void Dispose()
-            {
-                if (local == null || ctx == null) return;
-
-                ctx.EndTry(label, false);
-                ctx.BeginFinally();
-                Type disposableType = ctx.MapType(typeof(IDisposable));
-                MethodInfo dispose = disposableType.GetMethod("Dispose");
-                Type type = local.Type;
-                // remember that we've already (in the .ctor) excluded the case
-                // where it *cannot* be disposable
-                if (Helpers.IsValueType(type))
-                {
-                    ctx.LoadAddress(local, type);
-                    switch (ctx.MetadataVersion)
-                    {
-                        case ILVersion.Net1:
-                            ctx.LoadValue(local);
-                            ctx.CastToObject(type);
-                            break;
-                        default:
-                            ctx.Constrain(type);
-                            break;
-                    }
-                    ctx.EmitCall(dispose);
-                }
-                else
-                {
-                    Compiler.CodeLabel @null = ctx.DefineLabel();
-                    if (disposableType.IsAssignableFrom(type))
-                    {   // *known* to be IDisposable; just needs a null-check                            
-                        ctx.LoadValue(local);
-                        ctx.BranchIfFalse(@null, true);
-                        ctx.LoadAddress(local, type);
-                    }
-                    else
-                    {   // *could* be IDisposable; test via "as"
-                        using (Compiler.Local disp = new Compiler.Local(ctx, disposableType))
-                        {
-                            ctx.LoadValue(local);
-                            ctx.TryCast(disposableType);
-                            ctx.CopyValue();
-                            ctx.StoreValue(disp);
-                            ctx.BranchIfFalse(@null, true);
-                            ctx.LoadAddress(disp, disposableType);
-                        }
-                    }
-                    ctx.EmitCall(dispose);
-                    ctx.MarkLabel(@null);
-                }
-                ctx.EndFinally();
-                this.local = null;
-                this.ctx = null;
-                label = new CodeLabel(); // default
-            }
-        }
-
-        internal void Add()
-        {
-            Emit(OpCodes.Add);
-        }
-
-        internal void LoadLength(Local arr, bool zeroIfNull)
-        {
-            Helpers.DebugAssert(arr.Type.IsArray && arr.Type.GetArrayRank() == 1);
-
-            if (zeroIfNull)
-            {
-                Compiler.CodeLabel notNull = DefineLabel(), done = DefineLabel();
-                LoadValue(arr);
-                CopyValue(); // optimised for non-null case
-                BranchIfTrue(notNull, true);
-                DiscardValue();
-                LoadValue(0);
-                Branch(done, true);
-                MarkLabel(notNull);
-                Emit(OpCodes.Ldlen);
-                Emit(OpCodes.Conv_I4);
-                MarkLabel(done);
-            }
-            else
-            {
-                LoadValue(arr);
-                Emit(OpCodes.Ldlen);
-                Emit(OpCodes.Conv_I4);
-            }
-        }
-
-        internal void CreateArray(Type elementType, Local length)
-        {
-            LoadValue(length);
-            il.Emit(OpCodes.Newarr, elementType);
-            TraceCompile(OpCodes.Newarr + ": " + elementType);
-        }
-
-        internal void LoadArrayValue(Local arr, Local i)
-        {
-            Type type = arr.Type;
-            Helpers.DebugAssert(type.IsArray && arr.Type.GetArrayRank() == 1);
-            type = type.GetElementType();
-            Helpers.DebugAssert(type != null, "Not an array: " + arr.Type.FullName);
-            LoadValue(arr);
-            LoadValue(i);
-            switch (Helpers.GetTypeCode(type))
-            {
-                case ProtoTypeCode.SByte: Emit(OpCodes.Ldelem_I1); break;
-                case ProtoTypeCode.Int16: Emit(OpCodes.Ldelem_I2); break;
-                case ProtoTypeCode.Int32: Emit(OpCodes.Ldelem_I4); break;
-                case ProtoTypeCode.Int64: Emit(OpCodes.Ldelem_I8); break;
-
-                case ProtoTypeCode.Byte: Emit(OpCodes.Ldelem_U1); break;
-                case ProtoTypeCode.UInt16: Emit(OpCodes.Ldelem_U2); break;
-                case ProtoTypeCode.UInt32: Emit(OpCodes.Ldelem_U4); break;
-                case ProtoTypeCode.UInt64: Emit(OpCodes.Ldelem_I8); break; // odd, but this is what C# does...
-
-                case ProtoTypeCode.Single: Emit(OpCodes.Ldelem_R4); break;
-                case ProtoTypeCode.Double: Emit(OpCodes.Ldelem_R8); break;
-                default:
-                    if (Helpers.IsValueType(type))
-                    {
-                        il.Emit(OpCodes.Ldelema, type);
-                        il.Emit(OpCodes.Ldobj, type);
-                        TraceCompile(OpCodes.Ldelema + ": " + type);
-                        TraceCompile(OpCodes.Ldobj + ": " + type);
-                    }
-                    else
-                    {
-                        Emit(OpCodes.Ldelem_Ref);
-                    }
-
-                    break;
-            }
-        }
-
-        internal void LoadValue(Type type)
-        {
-            il.Emit(OpCodes.Ldtoken, type);
-            TraceCompile(OpCodes.Ldtoken + ": " + type);
-            EmitCall(MapType(typeof(System.Type)).GetMethod("GetTypeFromHandle"));
-        }
-
-        internal void ConvertToInt32(ProtoTypeCode typeCode, bool uint32Overflow)
-        {
-            switch (typeCode)
-            {
-                case ProtoTypeCode.Byte:
-                case ProtoTypeCode.SByte:
-                case ProtoTypeCode.Int16:
-                case ProtoTypeCode.UInt16:
-                    Emit(OpCodes.Conv_I4);
-                    break;
-                case ProtoTypeCode.Int32:
-                    break;
-                case ProtoTypeCode.Int64:
-                    Emit(OpCodes.Conv_Ovf_I4);
-                    break;
-                case ProtoTypeCode.UInt32:
-                    Emit(uint32Overflow ? OpCodes.Conv_Ovf_I4_Un : OpCodes.Conv_Ovf_I4);
-                    break;
-                case ProtoTypeCode.UInt64:
-                    Emit(OpCodes.Conv_Ovf_I4_Un);
-                    break;
-                default:
-                    throw new InvalidOperationException("ConvertToInt32 not implemented for: " + typeCode.ToString());
-            }
-        }
-
-        internal void ConvertFromInt32(ProtoTypeCode typeCode, bool uint32Overflow)
-        {
-            switch (typeCode)
-            {
-                case ProtoTypeCode.SByte: Emit(OpCodes.Conv_Ovf_I1); break;
-                case ProtoTypeCode.Byte: Emit(OpCodes.Conv_Ovf_U1); break;
-                case ProtoTypeCode.Int16: Emit(OpCodes.Conv_Ovf_I2); break;
-                case ProtoTypeCode.UInt16: Emit(OpCodes.Conv_Ovf_U2); break;
-                case ProtoTypeCode.Int32: break;
-                case ProtoTypeCode.UInt32: Emit(uint32Overflow ? OpCodes.Conv_Ovf_U4 : OpCodes.Conv_U4); break;
-                case ProtoTypeCode.Int64: Emit(OpCodes.Conv_I8); break;
-                case ProtoTypeCode.UInt64: Emit(OpCodes.Conv_U8); break;
-                default: throw new InvalidOperationException();
-            }
-        }
-
-        internal void LoadValue(decimal value)
-        {
-            if (value == 0M)
-            {
-                LoadValue(typeof(decimal).GetField("Zero"));
-            }
-            else
-            {
-                int[] bits = decimal.GetBits(value);
-                LoadValue(bits[0]); // lo
-                LoadValue(bits[1]); // mid
-                LoadValue(bits[2]); // hi
-                LoadValue((int)(((uint)bits[3]) >> 31)); // isNegative (bool, but int for CLI purposes)
-                LoadValue((bits[3] >> 16) & 0xFF); // scale (byte, but int for CLI purposes)
-
-                EmitCtor(MapType(typeof(decimal)), new Type[] { MapType(typeof(int)), MapType(typeof(int)), MapType(typeof(int)), MapType(typeof(bool)), MapType(typeof(byte)) });
-            }
-        }
-
-        internal void LoadValue(Guid value)
-        {
-            if (value == Guid.Empty)
-            {
-                LoadValue(typeof(Guid).GetField("Empty"));
-            }
-            else
-            { // note we're adding lots of shorts/bytes here - but at the IL level they are I4, not I1/I2 (which barely exist)
-                byte[] bytes = value.ToByteArray();
-                int i = (bytes[0]) | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24);
-                LoadValue(i);
-                short s = (short)((bytes[4]) | (bytes[5] << 8));
-                LoadValue(s);
-                s = (short)((bytes[6]) | (bytes[7] << 8));
-                LoadValue(s);
-                for (i = 8; i <= 15; i++)
-                {
-                    LoadValue(bytes[i]);
-                }
-                EmitCtor(MapType(typeof(Guid)), new Type[] { MapType(typeof(int)), MapType(typeof(short)), MapType(typeof(short)),
-                            MapType(typeof(byte)), MapType(typeof(byte)), MapType(typeof(byte)), MapType(typeof(byte)), MapType(typeof(byte)), MapType(typeof(byte)), MapType(typeof(byte)), MapType(typeof(byte)) });
-            }
-        }
-
-        //internal void LoadValue(bool value)
-        //{
-        //    Emit(value ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
-        //}
-
-        internal void LoadSerializationContext()
-        {
-            LoadReaderWriter();
-            LoadValue((isWriter ? typeof(ProtoWriter) : typeof(ProtoReader)).GetProperty("Context"));
-        }
-
-        private readonly TypeModel model;
-
-        internal Type MapType(Type type)
-        {
-            return model.MapType(type);
-        }
-
-        private readonly ILVersion metadataVersion;
-        public ILVersion MetadataVersion { get { return metadataVersion; } }
-        public enum ILVersion
-        {
-            Net1, Net2
-        }
-
-        internal bool AllowInternal(PropertyInfo property)
-        {
-            return NonPublic ? true : InternalsVisible(Helpers.GetAssembly(property.DeclaringType));
-        }
-    }
-}
-#endif

+ 0 - 7
ThirdParty/protobuf-net/Compiler/CompilerDelegates.cs

@@ -1,7 +0,0 @@
-#if FEAT_COMPILER
-namespace ProtoBuf.Compiler
-{
-    internal delegate void ProtoSerializer(object value, ProtoWriter dest);
-    internal delegate object ProtoDeserializer(object value, ProtoReader source);
-}
-#endif

+ 0 - 58
ThirdParty/protobuf-net/Compiler/Local.cs

@@ -1,58 +0,0 @@
-#if FEAT_COMPILER
-using System;
-using System.Reflection.Emit;
-
-namespace ProtoBuf.Compiler
-{
-    internal sealed class Local : IDisposable
-    {
-        // public static readonly Local InputValue = new Local(null, null);
-        private LocalBuilder value;
-        private readonly Type type;
-        private CompilerContext ctx;
-
-        private Local(LocalBuilder value, Type type)
-        {
-            this.value = value;
-            this.type = type;
-        }
-
-        internal Local(CompilerContext ctx, Type type)
-        {
-            this.ctx = ctx;
-            if (ctx != null) { value = ctx.GetFromPool(type); }
-            this.type = type;
-        }
-
-        internal LocalBuilder Value => value ?? throw new ObjectDisposedException(GetType().Name);
-
-        public Type Type => type;
-
-        public Local AsCopy()
-        {
-            if (ctx == null) return this; // can re-use if context-free
-            return new Local(value, this.type);
-        }
-        
-        public void Dispose()
-        {
-            if (ctx != null)
-            {
-                // only *actually* dispose if this is context-bound; note that non-bound
-                // objects are cheekily re-used, and *must* be left intact agter a "using" etc
-                ctx.ReleaseToPool(value);
-                value = null; 
-                ctx = null;
-            }            
-        }
-
-        internal bool IsSame(Local other)
-        {
-            if((object)this == (object)other) return true;
-
-            object ourVal = value; // use prop to ensure obj-disposed etc
-            return other != null && ourVal == (object)(other.value); 
-        }
-    }
-}
-#endif

+ 0 - 49
ThirdParty/protobuf-net/DataFormat.cs

@@ -1,49 +0,0 @@
-
-namespace ProtoBuf
-{
-    /// <summary>
-    /// Sub-format to use when serializing/deserializing data
-    /// </summary>
-    public enum DataFormat
-    {
-        /// <summary>
-        /// Uses the default encoding for the data-type.
-        /// </summary>
-        Default,
-
-        /// <summary>
-        /// When applied to signed integer-based data (including Decimal), this
-        /// indicates that zigzag variant encoding will be used. This means that values
-        /// with small magnitude (regardless of sign) take a small amount
-        /// of space to encode.
-        /// </summary>
-        ZigZag,
-
-        /// <summary>
-        /// When applied to signed integer-based data (including Decimal), this
-        /// indicates that two's-complement variant encoding will be used.
-        /// This means that any -ve number will take 10 bytes (even for 32-bit),
-        /// so should only be used for compatibility.
-        /// </summary>
-        TwosComplement,
-
-        /// <summary>
-        /// When applied to signed integer-based data (including Decimal), this
-        /// indicates that a fixed amount of space will be used.
-        /// </summary>
-        FixedSize,
-
-        /// <summary>
-        /// When applied to a sub-message, indicates that the value should be treated
-        /// as group-delimited.
-        /// </summary>
-        Group,
-
-        /// <summary>
-        /// When applied to members of types such as DateTime or TimeSpan, specifies
-        /// that the "well known" standardized representation should be use; DateTime uses Timestamp,
-        /// 
-        /// </summary>
-        WellKnown
-    }
-}

+ 0 - 176
ThirdParty/protobuf-net/DiscriminatedUnion.Serializable.cs

@@ -1,176 +0,0 @@
-#if PLAT_BINARYFORMATTER
-using System;
-using System.Runtime.InteropServices;
-using System.Runtime.Serialization;
-
-namespace ProtoBuf
-{
-    [Serializable]
-    public readonly partial struct DiscriminatedUnionObject : ISerializable
-    {
-        void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
-        {
-            if (Discriminator != default) info.AddValue("d", Discriminator);
-            if (Object is object) info.AddValue("o", Object);
-        }
-        private DiscriminatedUnionObject(SerializationInfo info, StreamingContext context)
-        {
-            this = default;
-            foreach (var field in info)
-            {
-                switch (field.Name)
-                {
-                    case "d": Discriminator = (int)field.Value; break;
-                    case "o": Object = field.Value; break;
-                }
-            }
-        }
-    }
-
-    [Serializable]
-    public readonly partial struct DiscriminatedUnion128Object : ISerializable
-    {
-        [FieldOffset(8)] private readonly long _lo;
-        [FieldOffset(16)] private readonly long _hi;
-        void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
-        {
-            if (_discriminator != default) info.AddValue("d", _discriminator);
-            if (_lo != default) info.AddValue("l", _lo);
-            if (_hi != default) info.AddValue("h", _hi);
-            if (Object != null) info.AddValue("o", Object);
-        }
-        private DiscriminatedUnion128Object(SerializationInfo info, StreamingContext context)
-        {
-            this = default;
-            foreach (var field in info)
-            {
-                switch (field.Name)
-                {
-                    case "d": _discriminator = (int)field.Value; break;
-                    case "l": _lo = (long)field.Value; break;
-                    case "h": _hi = (long)field.Value; break;
-                    case "o": Object = field.Value; break;
-                }
-            }
-        }
-    }
-
-    [Serializable]
-    public readonly partial struct DiscriminatedUnion128 : ISerializable
-    {
-        [FieldOffset(8)] private readonly long _lo;
-        [FieldOffset(16)] private readonly long _hi;
-        void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
-        {
-            if (_discriminator != default) info.AddValue("d", _discriminator);
-            if (_lo != default) info.AddValue("l", _lo);
-            if (_hi != default) info.AddValue("h", _hi);
-        }
-        private DiscriminatedUnion128(SerializationInfo info, StreamingContext context)
-        {
-            this = default;
-            foreach (var field in info)
-            {
-                switch (field.Name)
-                {
-                    case "d": _discriminator = (int)field.Value; break;
-                    case "l": _lo = (long)field.Value; break;
-                    case "h": _hi = (long)field.Value; break;
-                }
-            }
-        }
-    }
-
-    [Serializable]
-    public readonly partial struct DiscriminatedUnion64 : ISerializable
-    {
-        void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
-        {
-            if (_discriminator != default) info.AddValue("d", _discriminator);
-            if (Int64 != default) info.AddValue("i", Int64);
-        }
-        private DiscriminatedUnion64(SerializationInfo info, StreamingContext context)
-        {
-            this = default;
-            foreach (var field in info)
-            {
-                switch (field.Name)
-                {
-                    case "d": _discriminator = (int)field.Value; break;
-                    case "i": Int64 = (long)field.Value; break;
-                }
-            }
-        }
-    }
-
-    [Serializable]
-    public readonly partial struct DiscriminatedUnion64Object : ISerializable
-    {
-        void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
-        {
-            if (_discriminator != default) info.AddValue("d", _discriminator);
-            if (Int64 != default) info.AddValue("i", Int64);
-            if (Object is object) info.AddValue("o", Object);
-        }
-        private DiscriminatedUnion64Object(SerializationInfo info, StreamingContext context)
-        {
-            this = default;
-            foreach (var field in info)
-            {
-                switch (field.Name)
-                {
-                    case "d": _discriminator = (int)field.Value; break;
-                    case "i": Int64 = (long)field.Value; break;
-                    case "o": Object = field.Value; break;
-                }
-            }
-        }
-    }
-
-    [Serializable]
-    public readonly partial struct DiscriminatedUnion32 : ISerializable
-    {
-        void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
-        {
-            if (_discriminator != default) info.AddValue("d", _discriminator);
-            if (Int32 != default) info.AddValue("i", Int32);
-        }
-        private DiscriminatedUnion32(SerializationInfo info, StreamingContext context)
-        {
-            this = default;
-            foreach (var field in info)
-            {
-                switch (field.Name)
-                {
-                    case "d": _discriminator = (int)field.Value; break;
-                    case "i": Int32 = (int)field.Value; break;
-                }
-            }
-        }
-    }
-
-    [Serializable]
-    public readonly partial struct DiscriminatedUnion32Object : ISerializable
-    {
-        void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
-        {
-            if (_discriminator != default) info.AddValue("d", _discriminator);
-            if (Int32 != default) info.AddValue("i", Int32);
-            if (Object is object) info.AddValue("o", Object);
-        }
-        private DiscriminatedUnion32Object(SerializationInfo info, StreamingContext context)
-        {
-            this = default;
-            foreach (var field in info)
-            {
-                switch (field.Name)
-                {
-                    case "d": _discriminator = (int)field.Value; break;
-                    case "i": Int32 = (int)field.Value; break;
-                    case "o": Object = field.Value; break;
-                }
-            }
-        }
-    }
-}
-#endif

+ 0 - 416
ThirdParty/protobuf-net/DiscriminatedUnion.cs

@@ -1,416 +0,0 @@
-using System;
-using System.Runtime.InteropServices;
-
-namespace ProtoBuf
-{
-    /// <summary>Represent multiple types as a union; this is used as part of OneOf -
-    /// note that it is the caller's responsbility to only read/write the value as the same type</summary>
-    public readonly partial struct DiscriminatedUnionObject
-    {
-
-        /// <summary>The value typed as Object</summary>
-        public readonly object Object;
-
-        /// <summary>Indicates whether the specified discriminator is assigned</summary>
-        public bool Is(int discriminator) => Discriminator == discriminator;
-
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnionObject(int discriminator, object value)
-        {
-            Discriminator = discriminator;
-            Object = value;
-        }
-
-        /// <summary>Reset a value if the specified discriminator is assigned</summary>
-        public static void Reset(ref DiscriminatedUnionObject value, int discriminator)
-        {
-            if (value.Discriminator == discriminator) value = default;
-        }
-
-        /// <summary>The discriminator value</summary>
-        public int Discriminator { get; }
-    }
-
-    /// <summary>Represent multiple types as a union; this is used as part of OneOf -
-    /// note that it is the caller's responsbility to only read/write the value as the same type</summary>
-    [StructLayout(LayoutKind.Explicit)]
-    public readonly partial struct DiscriminatedUnion64
-    {
-#if !FEAT_SAFE
-		unsafe static DiscriminatedUnion64()
-        {
-            if (sizeof(DateTime) > 8) throw new InvalidOperationException(nameof(DateTime) + " was unexpectedly too big for " + nameof(DiscriminatedUnion64));
-            if (sizeof(TimeSpan) > 8) throw new InvalidOperationException(nameof(TimeSpan) + " was unexpectedly too big for " + nameof(DiscriminatedUnion64));
-        }
-#endif
-		[FieldOffset(0)] private readonly int _discriminator;  // note that we can't pack further because Object needs x8 alignment/padding on x64
-
-        /// <summary>The value typed as Int64</summary>
-        [FieldOffset(8)] public readonly long Int64;
-        /// <summary>The value typed as UInt64</summary>
-        [FieldOffset(8)] public readonly ulong UInt64;
-        /// <summary>The value typed as Int32</summary>
-        [FieldOffset(8)] public readonly int Int32;
-        /// <summary>The value typed as UInt32</summary>
-        [FieldOffset(8)] public readonly uint UInt32;
-        /// <summary>The value typed as Boolean</summary>
-        [FieldOffset(8)] public readonly bool Boolean;
-        /// <summary>The value typed as Single</summary>
-        [FieldOffset(8)] public readonly float Single;
-        /// <summary>The value typed as Double</summary>
-        [FieldOffset(8)] public readonly double Double;
-        /// <summary>The value typed as DateTime</summary>
-        [FieldOffset(8)] public readonly DateTime DateTime;
-        /// <summary>The value typed as TimeSpan</summary>
-        [FieldOffset(8)] public readonly TimeSpan TimeSpan;
-
-        private DiscriminatedUnion64(int discriminator) : this()
-        {
-            _discriminator = discriminator;
-        }
-
-        /// <summary>Indicates whether the specified discriminator is assigned</summary>
-        public bool Is(int discriminator) => _discriminator == discriminator;
-
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion64(int discriminator, long value) : this(discriminator) { Int64 = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion64(int discriminator, int value) : this(discriminator) { Int32 = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion64(int discriminator, ulong value) : this(discriminator) { UInt64 = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion64(int discriminator, uint value) : this(discriminator) { UInt32 = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion64(int discriminator, float value) : this(discriminator) { Single = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion64(int discriminator, double value) : this(discriminator) { Double = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion64(int discriminator, bool value) : this(discriminator) { Boolean = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion64(int discriminator, DateTime? value) : this(value.HasValue ? discriminator: 0) { DateTime = value.GetValueOrDefault(); }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion64(int discriminator, TimeSpan? value) : this(value.HasValue ? discriminator : 0) { TimeSpan = value.GetValueOrDefault(); }
-
-        /// <summary>Reset a value if the specified discriminator is assigned</summary>
-        public static void Reset(ref DiscriminatedUnion64 value, int discriminator)
-        {
-            if (value.Discriminator == discriminator) value = default;
-        }
-        /// <summary>The discriminator value</summary>
-        public int Discriminator => _discriminator;
-    }
-
-    /// <summary>Represent multiple types as a union; this is used as part of OneOf -
-    /// note that it is the caller's responsbility to only read/write the value as the same type</summary>
-    [StructLayout(LayoutKind.Explicit)]
-    public readonly partial struct DiscriminatedUnion128Object
-    {
-#if !FEAT_SAFE
-		unsafe static DiscriminatedUnion128Object()
-        {
-            if (sizeof(DateTime) > 16) throw new InvalidOperationException(nameof(DateTime) + " was unexpectedly too big for " + nameof(DiscriminatedUnion128Object));
-            if (sizeof(TimeSpan) > 16) throw new InvalidOperationException(nameof(TimeSpan) + " was unexpectedly too big for " + nameof(DiscriminatedUnion128Object));
-            if (sizeof(Guid) > 16) throw new InvalidOperationException(nameof(Guid) + " was unexpectedly too big for " + nameof(DiscriminatedUnion128Object));
-        }
-#endif
-
-		[FieldOffset(0)] private readonly int _discriminator;  // note that we can't pack further because Object needs x8 alignment/padding on x64
-
-        /// <summary>The value typed as Int64</summary>
-        [FieldOffset(8)] public readonly long Int64;
-        /// <summary>The value typed as UInt64</summary>
-        [FieldOffset(8)] public readonly ulong UInt64;
-        /// <summary>The value typed as Int32</summary>
-        [FieldOffset(8)] public readonly int Int32;
-        /// <summary>The value typed as UInt32</summary>
-        [FieldOffset(8)] public readonly uint UInt32;
-        /// <summary>The value typed as Boolean</summary>
-        [FieldOffset(8)] public readonly bool Boolean;
-        /// <summary>The value typed as Single</summary>
-        [FieldOffset(8)] public readonly float Single;
-        /// <summary>The value typed as Double</summary>
-        [FieldOffset(8)] public readonly double Double;
-        /// <summary>The value typed as DateTime</summary>
-        [FieldOffset(8)] public readonly DateTime DateTime;
-        /// <summary>The value typed as TimeSpan</summary>
-        [FieldOffset(8)] public readonly TimeSpan TimeSpan;
-        /// <summary>The value typed as Guid</summary>
-        [FieldOffset(8)] public readonly Guid Guid;
-        /// <summary>The value typed as Object</summary>
-        [FieldOffset(24)] public readonly object Object;
-
-        private DiscriminatedUnion128Object(int discriminator) : this()
-        {
-            _discriminator = discriminator;
-        }
-
-        /// <summary>Indicates whether the specified discriminator is assigned</summary>
-        public bool Is(int discriminator) => _discriminator == discriminator;
-
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion128Object(int discriminator, long value) : this(discriminator) { Int64 = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion128Object(int discriminator, int value) : this(discriminator) { Int32 = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion128Object(int discriminator, ulong value) : this(discriminator) { UInt64 = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion128Object(int discriminator, uint value) : this(discriminator) { UInt32 = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion128Object(int discriminator, float value) : this(discriminator) { Single = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion128Object(int discriminator, double value) : this(discriminator) { Double = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion128Object(int discriminator, bool value) : this(discriminator) { Boolean = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion128Object(int discriminator, object value) : this(value != null ? discriminator : 0) { Object = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion128Object(int discriminator, DateTime? value) : this(value.HasValue ? discriminator: 0) { DateTime = value.GetValueOrDefault(); }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion128Object(int discriminator, TimeSpan? value) : this(value.HasValue ? discriminator : 0) { TimeSpan = value.GetValueOrDefault(); }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion128Object(int discriminator, Guid? value) : this(value.HasValue ? discriminator : 0) { Guid = value.GetValueOrDefault(); }
-
-        /// <summary>Reset a value if the specified discriminator is assigned</summary>
-        public static void Reset(ref DiscriminatedUnion128Object value, int discriminator)
-        {
-            if (value.Discriminator == discriminator) value = default;
-        }
-        /// <summary>The discriminator value</summary>
-        public int Discriminator => _discriminator;
-    }
-
-    /// <summary>Represent multiple types as a union; this is used as part of OneOf -
-    /// note that it is the caller's responsbility to only read/write the value as the same type</summary>
-    [StructLayout(LayoutKind.Explicit)]
-    public readonly partial struct DiscriminatedUnion128
-    {
-#if !FEAT_SAFE
-        unsafe static DiscriminatedUnion128()
-        {
-            if (sizeof(DateTime) > 16) throw new InvalidOperationException(nameof(DateTime) + " was unexpectedly too big for " + nameof(DiscriminatedUnion128));
-            if (sizeof(TimeSpan) > 16) throw new InvalidOperationException(nameof(TimeSpan) + " was unexpectedly too big for " + nameof(DiscriminatedUnion128));
-            if (sizeof(Guid) > 16) throw new InvalidOperationException(nameof(Guid) + " was unexpectedly too big for " + nameof(DiscriminatedUnion128));
-        }
-#endif
-        [FieldOffset(0)] private readonly int _discriminator;  // note that we can't pack further because Object needs x8 alignment/padding on x64
-
-        /// <summary>The value typed as Int64</summary>
-        [FieldOffset(8)] public readonly long Int64;
-        /// <summary>The value typed as UInt64</summary>
-        [FieldOffset(8)] public readonly ulong UInt64;
-        /// <summary>The value typed as Int32</summary>
-        [FieldOffset(8)] public readonly int Int32;
-        /// <summary>The value typed as UInt32</summary>
-        [FieldOffset(8)] public readonly uint UInt32;
-        /// <summary>The value typed as Boolean</summary>
-        [FieldOffset(8)] public readonly bool Boolean;
-        /// <summary>The value typed as Single</summary>
-        [FieldOffset(8)] public readonly float Single;
-        /// <summary>The value typed as Double</summary>
-        [FieldOffset(8)] public readonly double Double;
-        /// <summary>The value typed as DateTime</summary>
-        [FieldOffset(8)] public readonly DateTime DateTime;
-        /// <summary>The value typed as TimeSpan</summary>
-        [FieldOffset(8)] public readonly TimeSpan TimeSpan;
-        /// <summary>The value typed as Guid</summary>
-        [FieldOffset(8)] public readonly Guid Guid;
-
-        private DiscriminatedUnion128(int discriminator) : this()
-        {
-            _discriminator = discriminator;
-        }
-
-        /// <summary>Indicates whether the specified discriminator is assigned</summary>
-        public bool Is(int discriminator) => _discriminator == discriminator;
-
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion128(int discriminator, long value) : this(discriminator) { Int64 = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion128(int discriminator, int value) : this(discriminator) { Int32 = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion128(int discriminator, ulong value) : this(discriminator) { UInt64 = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion128(int discriminator, uint value) : this(discriminator) { UInt32 = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion128(int discriminator, float value) : this(discriminator) { Single = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion128(int discriminator, double value) : this(discriminator) { Double = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion128(int discriminator, bool value) : this(discriminator) { Boolean = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion128(int discriminator, DateTime? value) : this(value.HasValue ? discriminator: 0) { DateTime = value.GetValueOrDefault(); }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion128(int discriminator, TimeSpan? value) : this(value.HasValue ? discriminator : 0) { TimeSpan = value.GetValueOrDefault(); }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion128(int discriminator, Guid? value) : this(value.HasValue ? discriminator : 0) { Guid = value.GetValueOrDefault(); }
-
-        /// <summary>Reset a value if the specified discriminator is assigned</summary>
-        public static void Reset(ref DiscriminatedUnion128 value, int discriminator)
-        {
-            if (value.Discriminator == discriminator) value = default;
-        }
-        /// <summary>The discriminator value</summary>
-        public int Discriminator => _discriminator;
-    }
-
-    /// <summary>Represent multiple types as a union; this is used as part of OneOf -
-    /// note that it is the caller's responsbility to only read/write the value as the same type</summary>
-    [StructLayout(LayoutKind.Explicit)]
-    public readonly partial struct DiscriminatedUnion64Object
-    {
-#if !FEAT_SAFE
-        unsafe static DiscriminatedUnion64Object()
-        {
-            if (sizeof(DateTime) > 8) throw new InvalidOperationException(nameof(DateTime) + " was unexpectedly too big for " + nameof(DiscriminatedUnion64Object));
-            if (sizeof(TimeSpan) > 8) throw new InvalidOperationException(nameof(TimeSpan) + " was unexpectedly too big for " + nameof(DiscriminatedUnion64Object));
-        }
-#endif
-        [FieldOffset(0)] private readonly int _discriminator;  // note that we can't pack further because Object needs x8 alignment/padding on x64
-
-        /// <summary>The value typed as Int64</summary>
-        [FieldOffset(8)] public readonly long Int64;
-        /// <summary>The value typed as UInt64</summary>
-        [FieldOffset(8)] public readonly ulong UInt64;
-        /// <summary>The value typed as Int32</summary>
-        [FieldOffset(8)] public readonly int Int32;
-        /// <summary>The value typed as UInt32</summary>
-        [FieldOffset(8)] public readonly uint UInt32;
-        /// <summary>The value typed as Boolean</summary>
-        [FieldOffset(8)] public readonly bool Boolean;
-        /// <summary>The value typed as Single</summary>
-        [FieldOffset(8)] public readonly float Single;
-        /// <summary>The value typed as Double</summary>
-        [FieldOffset(8)] public readonly double Double;
-        /// <summary>The value typed as DateTime</summary>
-        [FieldOffset(8)] public readonly DateTime DateTime;
-        /// <summary>The value typed as TimeSpan</summary>
-        [FieldOffset(8)] public readonly TimeSpan TimeSpan;
-        /// <summary>The value typed as Object</summary>
-        [FieldOffset(16)] public readonly object Object;
-
-        private DiscriminatedUnion64Object(int discriminator) : this()
-        {
-            _discriminator = discriminator;
-        }
-
-        /// <summary>Indicates whether the specified discriminator is assigned</summary>
-        public bool Is(int discriminator) => _discriminator == discriminator;
-
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion64Object(int discriminator, long value) : this(discriminator) { Int64 = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion64Object(int discriminator, int value) : this(discriminator) { Int32 = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion64Object(int discriminator, ulong value) : this(discriminator) { UInt64 = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion64Object(int discriminator, uint value) : this(discriminator) { UInt32 = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion64Object(int discriminator, float value) : this(discriminator) { Single = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion64Object(int discriminator, double value) : this(discriminator) { Double = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion64Object(int discriminator, bool value) : this(discriminator) { Boolean = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion64Object(int discriminator, object value) : this(value != null ? discriminator : 0) { Object = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion64Object(int discriminator, DateTime? value) : this(value.HasValue ? discriminator: 0) { DateTime = value.GetValueOrDefault(); }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion64Object(int discriminator, TimeSpan? value) : this(value.HasValue ? discriminator : 0) { TimeSpan = value.GetValueOrDefault(); }
-
-        /// <summary>Reset a value if the specified discriminator is assigned</summary>
-        public static void Reset(ref DiscriminatedUnion64Object value, int discriminator)
-        {
-            if (value.Discriminator == discriminator) value = default;
-        }
-        /// <summary>The discriminator value</summary>
-        public int Discriminator => _discriminator;
-    }
-
-    /// <summary>Represent multiple types as a union; this is used as part of OneOf -
-    /// note that it is the caller's responsbility to only read/write the value as the same type</summary>
-    [StructLayout(LayoutKind.Explicit)]
-    public readonly partial struct DiscriminatedUnion32
-    {
-        [FieldOffset(0)] private readonly int _discriminator;
-
-        /// <summary>The value typed as Int32</summary>
-        [FieldOffset(4)] public readonly int Int32;
-        /// <summary>The value typed as UInt32</summary>
-        [FieldOffset(4)] public readonly uint UInt32;
-        /// <summary>The value typed as Boolean</summary>
-        [FieldOffset(4)] public readonly bool Boolean;
-        /// <summary>The value typed as Single</summary>
-        [FieldOffset(4)] public readonly float Single;
-
-        private DiscriminatedUnion32(int discriminator) : this()
-        {
-            _discriminator = discriminator;
-        }
-
-        /// <summary>Indicates whether the specified discriminator is assigned</summary>
-        public bool Is(int discriminator) => _discriminator == discriminator;
-
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion32(int discriminator, int value) : this(discriminator) { Int32 = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion32(int discriminator, uint value) : this(discriminator) { UInt32 = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion32(int discriminator, float value) : this(discriminator) { Single = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion32(int discriminator, bool value) : this(discriminator) { Boolean = value; }
-
-        /// <summary>Reset a value if the specified discriminator is assigned</summary>
-        public static void Reset(ref DiscriminatedUnion32 value, int discriminator)
-        {
-            if (value.Discriminator == discriminator) value = default;
-        }
-        /// <summary>The discriminator value</summary>
-        public int Discriminator => _discriminator;
-    }
-
-    /// <summary>Represent multiple types as a union; this is used as part of OneOf -
-    /// note that it is the caller's responsbility to only read/write the value as the same type</summary>
-    [StructLayout(LayoutKind.Explicit)]
-    public readonly partial struct DiscriminatedUnion32Object
-    {
-        [FieldOffset(0)] private readonly int _discriminator;
-
-        /// <summary>The value typed as Int32</summary>
-        [FieldOffset(4)] public readonly int Int32;
-        /// <summary>The value typed as UInt32</summary>
-        [FieldOffset(4)] public readonly uint UInt32;
-        /// <summary>The value typed as Boolean</summary>
-        [FieldOffset(4)] public readonly bool Boolean;
-        /// <summary>The value typed as Single</summary>
-        [FieldOffset(4)] public readonly float Single;
-        /// <summary>The value typed as Object</summary>
-        [FieldOffset(8)] public readonly object Object;
-
-        private DiscriminatedUnion32Object(int discriminator) : this()
-        {
-            _discriminator = discriminator;
-        }
-
-        /// <summary>Indicates whether the specified discriminator is assigned</summary>
-        public bool Is(int discriminator) => _discriminator == discriminator;
-
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion32Object(int discriminator, int value) : this(discriminator) { Int32 = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion32Object(int discriminator, uint value) : this(discriminator) { UInt32 = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion32Object(int discriminator, float value) : this(discriminator) { Single = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion32Object(int discriminator, bool value) : this(discriminator) { Boolean = value; }
-        /// <summary>Create a new discriminated union value</summary>
-        public DiscriminatedUnion32Object(int discriminator, object value) : this(value != null ? discriminator : 0) { Object = value; }
-
-        /// <summary>Reset a value if the specified discriminator is assigned</summary>
-        public static void Reset(ref DiscriminatedUnion32Object value, int discriminator)
-        {
-            if (value.Discriminator == discriminator) value = default;
-        }
-        /// <summary>The discriminator value</summary>
-        public int Discriminator => _discriminator;
-    }
-}

+ 0 - 284
ThirdParty/protobuf-net/Extensible.cs

@@ -1,284 +0,0 @@
-using System;
-using System.Collections.Generic;
-using ProtoBuf.Meta;
-using System.Collections;
-
-namespace ProtoBuf
-{
-    /// <summary>
-    /// Simple base class for supporting unexpected fields allowing
-    /// for loss-less round-tips/merge, even if the data is not understod.
-    /// The additional fields are (by default) stored in-memory in a buffer.
-    /// </summary>
-    /// <remarks>As an example of an alternative implementation, you might
-    /// choose to use the file system (temporary files) as the back-end, tracking
-    /// only the paths [such an object would ideally be IDisposable and use
-    /// a finalizer to ensure that the files are removed].</remarks>
-    /// <seealso cref="IExtensible"/>
-    public abstract class Extensible : IExtensible
-    {
-        // note: not marked ProtoContract - no local state, and can't 
-        // predict sub-classes
-
-        private IExtension extensionObject;
-
-        IExtension IExtensible.GetExtensionObject(bool createIfMissing)
-        {
-            return GetExtensionObject(createIfMissing);
-        }
-
-        /// <summary>
-        /// Retrieves the <see cref="IExtension">extension</see> object for the current
-        /// instance, optionally creating it if it does not already exist.
-        /// </summary>
-        /// <param name="createIfMissing">Should a new extension object be
-        /// created if it does not already exist?</param>
-        /// <returns>The extension object if it exists (or was created), or null
-        /// if the extension object does not exist or is not available.</returns>
-        /// <remarks>The <c>createIfMissing</c> argument is false during serialization,
-        /// and true during deserialization upon encountering unexpected fields.</remarks>
-        protected virtual IExtension GetExtensionObject(bool createIfMissing)
-        {
-            return GetExtensionObject(ref extensionObject, createIfMissing);
-        }
-
-        /// <summary>
-        /// Provides a simple, default implementation for <see cref="IExtension">extension</see> support,
-        /// optionally creating it if it does not already exist. Designed to be called by
-        /// classes implementing <see cref="IExtensible"/>.
-        /// </summary>
-        /// <param name="createIfMissing">Should a new extension object be
-        /// created if it does not already exist?</param>
-        /// <param name="extensionObject">The extension field to check (and possibly update).</param>
-        /// <returns>The extension object if it exists (or was created), or null
-        /// if the extension object does not exist or is not available.</returns>
-        /// <remarks>The <c>createIfMissing</c> argument is false during serialization,
-        /// and true during deserialization upon encountering unexpected fields.</remarks>
-        public static IExtension GetExtensionObject(ref IExtension extensionObject, bool createIfMissing)
-        {
-            if (createIfMissing && extensionObject == null)
-            {
-                extensionObject = new BufferExtension();
-            }
-            return extensionObject;
-        }
-
-#if !NO_RUNTIME
-        /// <summary>
-        /// Appends the value as an additional (unexpected) data-field for the instance.
-        /// Note that for non-repeated sub-objects, this equates to a merge operation;
-        /// for repeated sub-objects this adds a new instance to the set; for simple
-        /// values the new value supercedes the old value.
-        /// </summary>
-        /// <remarks>Note that appending a value does not remove the old value from
-        /// the stream; avoid repeatedly appending values for the same field.</remarks>
-        /// <typeparam name="TValue">The type of the value to append.</typeparam>
-        /// <param name="instance">The extensible object to append the value to.</param>
-        /// <param name="tag">The field identifier; the tag should not be defined as a known data-field for the instance.</param>
-        /// <param name="value">The value to append.</param>
-        public static void AppendValue<TValue>(IExtensible instance, int tag, TValue value)
-        {
-            AppendValue<TValue>(instance, tag, DataFormat.Default, value);
-        }
-
-        /// <summary>
-        /// Appends the value as an additional (unexpected) data-field for the instance.
-        /// Note that for non-repeated sub-objects, this equates to a merge operation;
-        /// for repeated sub-objects this adds a new instance to the set; for simple
-        /// values the new value supercedes the old value.
-        /// </summary>
-        /// <remarks>Note that appending a value does not remove the old value from
-        /// the stream; avoid repeatedly appending values for the same field.</remarks>
-        /// <typeparam name="TValue">The data-type of the field.</typeparam>
-        /// <param name="format">The data-format to use when encoding the value.</param>
-        /// <param name="instance">The extensible object to append the value to.</param>
-        /// <param name="tag">The field identifier; the tag should not be defined as a known data-field for the instance.</param>
-        /// <param name="value">The value to append.</param>
-        public static void AppendValue<TValue>(IExtensible instance, int tag, DataFormat format, TValue value)
-        {
-            ExtensibleUtil.AppendExtendValue(RuntimeTypeModel.Default, instance, tag, format, value);
-        }
-        /// <summary>
-        /// Queries an extensible object for an additional (unexpected) data-field for the instance.
-        /// The value returned is the composed value after merging any duplicated content; if the
-        /// value is "repeated" (a list), then use GetValues instead.
-        /// </summary>
-        /// <typeparam name="TValue">The data-type of the field.</typeparam>
-        /// <param name="instance">The extensible object to obtain the value from.</param>
-        /// <param name="tag">The field identifier; the tag should not be defined as a known data-field for the instance.</param>
-        /// <returns>The effective value of the field, or the default value if not found.</returns>
-        public static TValue GetValue<TValue>(IExtensible instance, int tag)
-        {
-            return GetValue<TValue>(instance, tag, DataFormat.Default);
-        }
-
-        /// <summary>
-        /// Queries an extensible object for an additional (unexpected) data-field for the instance.
-        /// The value returned is the composed value after merging any duplicated content; if the
-        /// value is "repeated" (a list), then use GetValues instead.
-        /// </summary>
-        /// <typeparam name="TValue">The data-type of the field.</typeparam>
-        /// <param name="instance">The extensible object to obtain the value from.</param>
-        /// <param name="tag">The field identifier; the tag should not be defined as a known data-field for the instance.</param>
-        /// <param name="format">The data-format to use when decoding the value.</param>
-        /// <returns>The effective value of the field, or the default value if not found.</returns>
-        public static TValue GetValue<TValue>(IExtensible instance, int tag, DataFormat format)
-        {
-            TryGetValue<TValue>(instance, tag, format, out TValue value);
-            return value;
-        }
-
-        /// <summary>
-        /// Queries an extensible object for an additional (unexpected) data-field for the instance.
-        /// The value returned (in "value") is the composed value after merging any duplicated content;
-        /// if the value is "repeated" (a list), then use GetValues instead.
-        /// </summary>
-        /// <typeparam name="TValue">The data-type of the field.</typeparam>
-        /// <param name="value">The effective value of the field, or the default value if not found.</param>
-        /// <param name="instance">The extensible object to obtain the value from.</param>
-        /// <param name="tag">The field identifier; the tag should not be defined as a known data-field for the instance.</param>
-        /// <returns>True if data for the field was present, false otherwise.</returns>
-        public static bool TryGetValue<TValue>(IExtensible instance, int tag, out TValue value)
-        {
-            return TryGetValue<TValue>(instance, tag, DataFormat.Default, out value);
-        }
-
-        /// <summary>
-        /// Queries an extensible object for an additional (unexpected) data-field for the instance.
-        /// The value returned (in "value") is the composed value after merging any duplicated content;
-        /// if the value is "repeated" (a list), then use GetValues instead.
-        /// </summary>
-        /// <typeparam name="TValue">The data-type of the field.</typeparam>
-        /// <param name="value">The effective value of the field, or the default value if not found.</param>
-        /// <param name="instance">The extensible object to obtain the value from.</param>
-        /// <param name="tag">The field identifier; the tag should not be defined as a known data-field for the instance.</param>
-        /// <param name="format">The data-format to use when decoding the value.</param>
-        /// <returns>True if data for the field was present, false otherwise.</returns>
-        public static bool TryGetValue<TValue>(IExtensible instance, int tag, DataFormat format, out TValue value)
-        {
-            return TryGetValue<TValue>(instance, tag, format, false, out value);
-        }
-
-        /// <summary>
-        /// Queries an extensible object for an additional (unexpected) data-field for the instance.
-        /// The value returned (in "value") is the composed value after merging any duplicated content;
-        /// if the value is "repeated" (a list), then use GetValues instead.
-        /// </summary>
-        /// <typeparam name="TValue">The data-type of the field.</typeparam>
-        /// <param name="value">The effective value of the field, or the default value if not found.</param>
-        /// <param name="instance">The extensible object to obtain the value from.</param>
-        /// <param name="tag">The field identifier; the tag should not be defined as a known data-field for the instance.</param>
-        /// <param name="format">The data-format to use when decoding the value.</param>
-        /// <param name="allowDefinedTag">Allow tags that are present as part of the definition; for example, to query unknown enum values.</param>
-        /// <returns>True if data for the field was present, false otherwise.</returns>
-        public static bool TryGetValue<TValue>(IExtensible instance, int tag, DataFormat format, bool allowDefinedTag, out TValue value)
-        {
-            value = default;
-            bool set = false;
-            foreach (TValue val in ExtensibleUtil.GetExtendedValues<TValue>(instance, tag, format, true, allowDefinedTag))
-            {
-                // expecting at most one yield...
-                // but don't break; need to read entire stream
-                value = val;
-                set = true;
-            }
-
-            return set;
-        }
-
-        /// <summary>
-        /// Queries an extensible object for an additional (unexpected) data-field for the instance.
-        /// Each occurrence of the field is yielded separately, making this usage suitable for "repeated"
-        /// (list) fields.
-        /// </summary>
-        /// <remarks>The extended data is processed lazily as the enumerator is iterated.</remarks>
-        /// <typeparam name="TValue">The data-type of the field.</typeparam>
-        /// <param name="instance">The extensible object to obtain the value from.</param>
-        /// <param name="tag">The field identifier; the tag should not be defined as a known data-field for the instance.</param>
-        /// <returns>An enumerator that yields each occurrence of the field.</returns>
-        public static IEnumerable<TValue> GetValues<TValue>(IExtensible instance, int tag)
-        {
-            return ExtensibleUtil.GetExtendedValues<TValue>(instance, tag, DataFormat.Default, false, false);
-        }
-
-        /// <summary>
-        /// Queries an extensible object for an additional (unexpected) data-field for the instance.
-        /// Each occurrence of the field is yielded separately, making this usage suitable for "repeated"
-        /// (list) fields.
-        /// </summary>
-        /// <remarks>The extended data is processed lazily as the enumerator is iterated.</remarks>
-        /// <typeparam name="TValue">The data-type of the field.</typeparam>
-        /// <param name="instance">The extensible object to obtain the value from.</param>
-        /// <param name="tag">The field identifier; the tag should not be defined as a known data-field for the instance.</param>
-        /// <param name="format">The data-format to use when decoding the value.</param>
-        /// <returns>An enumerator that yields each occurrence of the field.</returns>
-        public static IEnumerable<TValue> GetValues<TValue>(IExtensible instance, int tag, DataFormat format)
-        {
-            return ExtensibleUtil.GetExtendedValues<TValue>(instance, tag, format, false, false);
-        }
-#endif
-
-        /// <summary>
-        /// Queries an extensible object for an additional (unexpected) data-field for the instance.
-        /// The value returned (in "value") is the composed value after merging any duplicated content;
-        /// if the value is "repeated" (a list), then use GetValues instead.
-        /// </summary>
-        /// <param name="type">The data-type of the field.</param>
-        /// <param name="model">The model to use for configuration.</param>
-        /// <param name="value">The effective value of the field, or the default value if not found.</param>
-        /// <param name="instance">The extensible object to obtain the value from.</param>
-        /// <param name="tag">The field identifier; the tag should not be defined as a known data-field for the instance.</param>
-        /// <param name="format">The data-format to use when decoding the value.</param>
-        /// <param name="allowDefinedTag">Allow tags that are present as part of the definition; for example, to query unknown enum values.</param>
-        /// <returns>True if data for the field was present, false otherwise.</returns>
-        public static bool TryGetValue(TypeModel model, Type type, IExtensible instance, int tag, DataFormat format, bool allowDefinedTag, out object value)
-        {
-            value = null;
-            bool set = false;
-            foreach (object val in ExtensibleUtil.GetExtendedValues(model, type, instance, tag, format, true, allowDefinedTag))
-            {
-                // expecting at most one yield...
-                // but don't break; need to read entire stream
-                value = val;
-                set = true;
-            }
-
-            return set;
-        }
-
-        /// <summary>
-        /// Queries an extensible object for an additional (unexpected) data-field for the instance.
-        /// Each occurrence of the field is yielded separately, making this usage suitable for "repeated"
-        /// (list) fields.
-        /// </summary>
-        /// <remarks>The extended data is processed lazily as the enumerator is iterated.</remarks>
-        /// <param name="model">The model to use for configuration.</param>
-        /// <param name="type">The data-type of the field.</param>
-        /// <param name="instance">The extensible object to obtain the value from.</param>
-        /// <param name="tag">The field identifier; the tag should not be defined as a known data-field for the instance.</param>
-        /// <param name="format">The data-format to use when decoding the value.</param>
-        /// <returns>An enumerator that yields each occurrence of the field.</returns>
-        public static IEnumerable GetValues(TypeModel model, Type type, IExtensible instance, int tag, DataFormat format)
-        {
-            return ExtensibleUtil.GetExtendedValues(model, type, instance, tag, format, false, false);
-        }
-
-        /// <summary>
-        /// Appends the value as an additional (unexpected) data-field for the instance.
-        /// Note that for non-repeated sub-objects, this equates to a merge operation;
-        /// for repeated sub-objects this adds a new instance to the set; for simple
-        /// values the new value supercedes the old value.
-        /// </summary>
-        /// <remarks>Note that appending a value does not remove the old value from
-        /// the stream; avoid repeatedly appending values for the same field.</remarks>
-        /// <param name="model">The model to use for configuration.</param>
-        /// <param name="format">The data-format to use when encoding the value.</param>
-        /// <param name="instance">The extensible object to append the value to.</param>
-        /// <param name="tag">The field identifier; the tag should not be defined as a known data-field for the instance.</param>
-        /// <param name="value">The value to append.</param>
-        public static void AppendValue(TypeModel model, IExtensible instance, int tag, DataFormat format, object value)
-        {
-            ExtensibleUtil.AppendExtendValue(model, instance, tag, format, value);
-        }
-    }
-}

+ 0 - 118
ThirdParty/protobuf-net/ExtensibleUtil.cs

@@ -1,118 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.IO;
-using ProtoBuf.Meta;
-
-namespace ProtoBuf
-{
-    /// <summary>
-    /// This class acts as an internal wrapper allowing us to do a dynamic
-    /// methodinfo invoke; an't put into Serializer as don't want on public
-    /// API; can't put into Serializer&lt;T&gt; since we need to invoke
-    /// across classes
-    /// </summary>
-    internal static class ExtensibleUtil
-    {
-
-#if !NO_RUNTIME
-        /// <summary>
-        /// All this does is call GetExtendedValuesTyped with the correct type for "instance";
-        /// this ensures that we don't get issues with subclasses declaring conflicting types -
-        /// the caller must respect the fields defined for the type they pass in.
-        /// </summary>
-        internal static IEnumerable<TValue> GetExtendedValues<TValue>(IExtensible instance, int tag, DataFormat format, bool singleton, bool allowDefinedTag)
-        {
-            foreach (TValue value in GetExtendedValues(RuntimeTypeModel.Default, typeof(TValue), instance, tag, format, singleton, allowDefinedTag))
-            {
-                yield return value;
-            }
-        }
-#endif
-        /// <summary>
-        /// All this does is call GetExtendedValuesTyped with the correct type for "instance";
-        /// this ensures that we don't get issues with subclasses declaring conflicting types -
-        /// the caller must respect the fields defined for the type they pass in.
-        /// </summary>
-        internal static IEnumerable GetExtendedValues(TypeModel model, Type type, IExtensible instance, int tag, DataFormat format, bool singleton, bool allowDefinedTag)
-        {
-            if (instance == null) throw new ArgumentNullException(nameof(instance));
-            if (tag <= 0) throw new ArgumentOutOfRangeException(nameof(tag));
-            IExtension extn = instance.GetExtensionObject(false);
-
-            if (extn == null)
-            {
-                yield break;
-            }
-
-            Stream stream = extn.BeginQuery();
-            object value = null;
-            ProtoReader reader = null;
-            try
-            {
-                SerializationContext ctx = new SerializationContext();
-                reader = ProtoReader.Create(stream, model, ctx, ProtoReader.TO_EOF);
-                while (model.TryDeserializeAuxiliaryType(reader, format, tag, type, ref value, true, true, false, false, null) && value != null)
-                {
-                    if (!singleton)
-                    {
-                        yield return value;
-
-                        value = null; // fresh item each time
-                    }
-                }
-                if (singleton && value != null)
-                {
-                    yield return value;
-                }
-            }
-            finally
-            {
-                ProtoReader.Recycle(reader);
-                extn.EndQuery(stream);
-            }
-        }
-
-        internal static void AppendExtendValue(TypeModel model, IExtensible instance, int tag, DataFormat format, object value)
-        {
-            if (instance == null) throw new ArgumentNullException(nameof(instance));
-            if (value == null) throw new ArgumentNullException(nameof(value));
-
-            // TODO
-            //model.CheckTagNotInUse(tag);
-
-            // obtain the extension object and prepare to write
-            IExtension extn = instance.GetExtensionObject(true);
-            if (extn == null) throw new InvalidOperationException("No extension object available; appended data would be lost.");
-            bool commit = false;
-            Stream stream = extn.BeginAppend();
-            try
-            {
-                using (ProtoWriter writer = ProtoWriter.Create(stream, model, null))
-                {
-                    model.TrySerializeAuxiliaryType(writer, null, format, tag, value, false, null);
-                    writer.Close();
-                }
-                commit = true;
-            }
-            finally
-            {
-                extn.EndAppend(stream, commit);
-            }
-        }
-
-        //        /// <summary>
-        //        /// Stores the given value into the instance's stream; the serializer
-        //        /// is inferred from TValue and format.
-        //        /// </summary>
-        //        /// <remarks>Needs to be public to be callable thru reflection in Silverlight</remarks>
-        //        public static void AppendExtendValueTyped<TSource, TValue>(
-        //            TypeModel model, TSource instance, int tag, DataFormat format, TValue value)
-        //            where TSource : class, IExtensible
-        //        {
-        //            AppendExtendValue(model, instance, tag, format, value);
-        //        }
-
-    }
-
-}

binární
ThirdParty/protobuf-net/GlobalSuppressions.cs


+ 0 - 638
ThirdParty/protobuf-net/Helpers.cs

@@ -1,638 +0,0 @@
-
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.IO;
-using System.Text;
-#if COREFX
-using System.Linq;
-#endif
-#if PROFILE259
-using System.Reflection;
-using System.Linq;
-#else
-using System.Reflection;
-#endif
-
-namespace ProtoBuf
-{
-    /// <summary>
-    /// Not all frameworks are created equal (fx1.1 vs fx2.0,
-    /// micro-framework, compact-framework,
-    /// silverlight, etc). This class simply wraps up a few things that would
-    /// otherwise make the real code unnecessarily messy, providing fallback
-    /// implementations if necessary.
-    /// </summary>
-    internal sealed class Helpers
-    {
-        private Helpers() { }
-
-        public static StringBuilder AppendLine(StringBuilder builder)
-        {
-            return builder.AppendLine();
-        }
-
-        [System.Diagnostics.Conditional("DEBUG")]
-        public static void DebugWriteLine(string message, object obj)
-        {
-#if DEBUG
-            string suffix;
-            try
-            {
-                suffix = obj == null ? "(null)" : obj.ToString();
-            }
-            catch
-            {
-                suffix = "(exception)";
-            }
-            DebugWriteLine(message + ": " + suffix);
-#endif
-        }
-        [System.Diagnostics.Conditional("DEBUG")]
-        public static void DebugWriteLine(string message)
-        {
-#if DEBUG
-            System.Diagnostics.Debug.WriteLine(message);
-#endif
-        }
-        [System.Diagnostics.Conditional("TRACE")]
-        public static void TraceWriteLine(string message)
-        {
-#if TRACE
-#if CF2 || PORTABLE || COREFX || PROFILE259
-			System.Diagnostics.Debug.WriteLine(message);
-#else
-            System.Diagnostics.Trace.WriteLine(message);
-#endif
-#endif
-        }
-
-        [System.Diagnostics.Conditional("DEBUG")]
-        public static void DebugAssert(bool condition, string message)
-        {
-#if DEBUG
-            if (!condition)
-            {
-                System.Diagnostics.Debug.Assert(false, message);
-            }
-#endif
-        }
-        [System.Diagnostics.Conditional("DEBUG")]
-        public static void DebugAssert(bool condition, string message, params object[] args)
-        {
-#if DEBUG
-            if (!condition) DebugAssert(false, string.Format(message, args));
-#endif
-        }
-        [System.Diagnostics.Conditional("DEBUG")]
-        public static void DebugAssert(bool condition)
-        {
-#if DEBUG   
-            if (!condition && System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Break();
-            System.Diagnostics.Debug.Assert(condition);
-#endif
-        }
-#if !NO_RUNTIME
-        public static void Sort(int[] keys, object[] values)
-        {
-            // bubble-sort; it'll work on MF, has small code,
-            // and works well-enough for our sizes. This approach
-            // also allows us to do `int` compares without having
-            // to go via IComparable etc, so win:win
-            bool swapped;
-            do
-            {
-                swapped = false;
-                for (int i = 1; i < keys.Length; i++)
-                {
-                    if (keys[i - 1] > keys[i])
-                    {
-                        int tmpKey = keys[i];
-                        keys[i] = keys[i - 1];
-                        keys[i - 1] = tmpKey;
-                        object tmpValue = values[i];
-                        values[i] = values[i - 1];
-                        values[i - 1] = tmpValue;
-                        swapped = true;
-                    }
-                }
-            } while (swapped);
-        }
-#endif
-
-#if COREFX
-		internal static MemberInfo GetInstanceMember(TypeInfo declaringType, string name)
-        {
-            var members = declaringType.AsType().GetMember(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
-            switch(members.Length)
-            {
-                case 0: return null;
-                case 1: return members[0];
-                default: throw new AmbiguousMatchException(name);
-            }
-        }
-        internal static MethodInfo GetInstanceMethod(Type declaringType, string name)
-        {
-            foreach (MethodInfo method in declaringType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
-            {
-                if (method.Name == name) return method;
-            }
-            return null;
-        }
-        internal static MethodInfo GetInstanceMethod(TypeInfo declaringType, string name)
-        {
-            return GetInstanceMethod(declaringType.AsType(), name); ;
-        }
-        internal static MethodInfo GetStaticMethod(Type declaringType, string name)
-        {
-            foreach (MethodInfo method in declaringType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))
-            {
-                if (method.Name == name) return method;
-            }
-            return null;
-        }
-
-        internal static MethodInfo GetStaticMethod(TypeInfo declaringType, string name)
-        {
-            return GetStaticMethod(declaringType.AsType(), name);
-        }
-        internal static MethodInfo GetStaticMethod(Type declaringType, string name, Type[] parameterTypes)
-        {
-            foreach(MethodInfo method in declaringType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))
-            {
-                if (method.Name == name && IsMatch(method.GetParameters(), parameterTypes)) return method;
-            }
-            return null;
-        }
-        internal static MethodInfo GetInstanceMethod(Type declaringType, string name, Type[] parameterTypes)
-        {
-            foreach (MethodInfo method in declaringType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
-            {
-                if (method.Name == name && IsMatch(method.GetParameters(), parameterTypes)) return method;
-            }
-            return null;
-        }
-        internal static MethodInfo GetInstanceMethod(TypeInfo declaringType, string name, Type[] types)
-        {
-            return GetInstanceMethod(declaringType.AsType(), name, types);
-        }
-#elif PROFILE259
-        internal static MemberInfo GetInstanceMember(TypeInfo declaringType, string name)
-        {
-            IEnumerable<MemberInfo> members = declaringType.DeclaredMembers;
-            IList<MemberInfo> found = new List<MemberInfo>();
-            foreach (MemberInfo member in members)
-            {
-                if (member.Name.Equals(name))
-                {
-                    found.Add(member);
-                }
-            }
-            switch (found.Count)
-            {
-                case 0: return null;
-                case 1: return found.First();
-                default: throw new AmbiguousMatchException(name);
-            }
-        }
-        internal static MethodInfo GetInstanceMethod(Type declaringType, string name)
-        {
-            var methods = declaringType.GetRuntimeMethods();
-            foreach (MethodInfo method in methods)
-            {
-                if (method.Name == name)
-                {
-                    return method;
-                }
-            }
-            return null;
-        }
-        internal static MethodInfo GetInstanceMethod(TypeInfo declaringType, string name)
-        {
-            return GetInstanceMethod(declaringType.AsType(), name); ;
-        }
-        internal static MethodInfo GetStaticMethod(Type declaringType, string name)
-        {
-            var methods = declaringType.GetRuntimeMethods();
-            foreach (MethodInfo method in methods)
-            {
-                if (method.Name == name)
-                {
-                    return method;
-                }
-            }
-            return null;
-        }
-
-        internal static MethodInfo GetStaticMethod(TypeInfo declaringType, string name)
-        {
-            return GetStaticMethod(declaringType.AsType(), name);
-        }
-        internal static MethodInfo GetStaticMethod(Type declaringType, string name, Type[] parameterTypes)
-        {
-            var methods = declaringType.GetRuntimeMethods();
-            foreach (MethodInfo method in methods)
-            {
-                if (method.Name == name &&
-                    IsMatch(method.GetParameters(), parameterTypes))
-                {
-                    return method;
-                }
-            }
-            return null;
-        }
-        internal static MethodInfo GetInstanceMethod(Type declaringType, string name, Type[] parameterTypes)
-        {
-            var methods = declaringType.GetRuntimeMethods();
-            foreach (MethodInfo method in methods)
-            {
-                if (method.Name == name &&
-                    IsMatch(method.GetParameters(), parameterTypes))
-                {
-                    return method;
-                }
-            }
-            return null;
-        }
-        internal static MethodInfo GetInstanceMethod(TypeInfo declaringType, string name, Type[] types)
-        {
-            return GetInstanceMethod(declaringType.AsType(), name, types);
-        }
-#else
-        internal static MethodInfo GetInstanceMethod(Type declaringType, string name)
-        {
-            return declaringType.GetMethod(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
-        }
-        internal static MethodInfo GetStaticMethod(Type declaringType, string name)
-        {
-            return declaringType.GetMethod(name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
-        }
-        internal static MethodInfo GetStaticMethod(Type declaringType, string name, Type[] parameterTypes)
-        {
-#if PORTABLE
-            foreach (MethodInfo method in declaringType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))
-            {
-                if (method.Name == name && IsMatch(method.GetParameters(), parameterTypes)) return method;
-            }
-            return null;
-#else
-            return declaringType.GetMethod(name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, parameterTypes, null);
-#endif
-        }
-        internal static MethodInfo GetInstanceMethod(Type declaringType, string name, Type[] types)
-        {
-            if (types == null) types = EmptyTypes;
-#if PORTABLE || COREFX
-            MethodInfo method = declaringType.GetMethod(name, types);
-            if (method != null && method.IsStatic) method = null;
-            return method;
-#else
-            return declaringType.GetMethod(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
-                null, types, null);
-#endif
-        }
-#endif
-
-        internal static bool IsSubclassOf(Type type, Type baseClass)
-        {
-#if COREFX || PROFILE259
-            return type.GetTypeInfo().IsSubclassOf(baseClass);
-#else
-            return type.IsSubclassOf(baseClass);
-#endif
-        }
-
-        public readonly static Type[] EmptyTypes =
-#if PORTABLE || CF2 || CF35 || PROFILE259
-            new Type[0];
-#else
-            Type.EmptyTypes;
-#endif
-
-#if COREFX || PROFILE259
-        private static readonly Type[] knownTypes = new Type[] {
-                typeof(bool), typeof(char), typeof(sbyte), typeof(byte),
-                typeof(short), typeof(ushort), typeof(int), typeof(uint),
-                typeof(long), typeof(ulong), typeof(float), typeof(double),
-                typeof(decimal), typeof(string),
-                typeof(DateTime), typeof(TimeSpan), typeof(Guid), typeof(Uri),
-                typeof(byte[]), typeof(Type)};
-        private static readonly ProtoTypeCode[] knownCodes = new ProtoTypeCode[] {
-            ProtoTypeCode.Boolean, ProtoTypeCode.Char, ProtoTypeCode.SByte, ProtoTypeCode.Byte,
-            ProtoTypeCode.Int16, ProtoTypeCode.UInt16, ProtoTypeCode.Int32, ProtoTypeCode.UInt32,
-            ProtoTypeCode.Int64, ProtoTypeCode.UInt64, ProtoTypeCode.Single, ProtoTypeCode.Double,
-            ProtoTypeCode.Decimal, ProtoTypeCode.String,
-            ProtoTypeCode.DateTime, ProtoTypeCode.TimeSpan, ProtoTypeCode.Guid, ProtoTypeCode.Uri,
-            ProtoTypeCode.ByteArray, ProtoTypeCode.Type
-        };
-
-#endif
-
-        public static ProtoTypeCode GetTypeCode(Type type)
-        {
-#if COREFX || PROFILE259
-            if (IsEnum(type))
-            {
-                type = Enum.GetUnderlyingType(type);
-            }
-            int idx = Array.IndexOf<Type>(knownTypes, type);
-            if (idx >= 0) return knownCodes[idx];
-            return type == null ? ProtoTypeCode.Empty : ProtoTypeCode.Unknown;
-#else
-            TypeCode code = Type.GetTypeCode(type);
-            switch (code)
-            {
-                case TypeCode.Empty:
-                case TypeCode.Boolean:
-                case TypeCode.Char:
-                case TypeCode.SByte:
-                case TypeCode.Byte:
-                case TypeCode.Int16:
-                case TypeCode.UInt16:
-                case TypeCode.Int32:
-                case TypeCode.UInt32:
-                case TypeCode.Int64:
-                case TypeCode.UInt64:
-                case TypeCode.Single:
-                case TypeCode.Double:
-                case TypeCode.Decimal:
-                case TypeCode.DateTime:
-                case TypeCode.String:
-                    return (ProtoTypeCode)code;
-            }
-            if (type == typeof(TimeSpan)) return ProtoTypeCode.TimeSpan;
-            if (type == typeof(Guid)) return ProtoTypeCode.Guid;
-            if (type == typeof(Uri)) return ProtoTypeCode.Uri;
-#if PORTABLE
-            // In PCLs, the Uri type may not match (WinRT uses Internal/Uri, .Net uses System/Uri), so match on the full name instead
-            if (type.FullName == typeof(Uri).FullName) return ProtoTypeCode.Uri;
-#endif
-            if (type == typeof(byte[])) return ProtoTypeCode.ByteArray;
-            if (type == typeof(Type)) return ProtoTypeCode.Type;
-
-            return ProtoTypeCode.Unknown;
-#endif
-        }
-
-        internal static Type GetUnderlyingType(Type type)
-        {
-            return Nullable.GetUnderlyingType(type);
-        }
-
-        internal static bool IsValueType(Type type)
-        {
-#if COREFX || PROFILE259
-            return type.GetTypeInfo().IsValueType;
-#else
-            return type.IsValueType;
-#endif
-        }
-        internal static bool IsSealed(Type type)
-        {
-#if COREFX || PROFILE259
-            return type.GetTypeInfo().IsSealed;
-#else
-            return type.IsSealed;
-#endif
-        }
-        internal static bool IsClass(Type type)
-        {
-#if COREFX || PROFILE259
-            return type.GetTypeInfo().IsClass;
-#else
-            return type.IsClass;
-#endif
-        }
-
-        internal static bool IsEnum(Type type)
-        {
-#if COREFX || PROFILE259
-            return type.GetTypeInfo().IsEnum;
-#else
-            return type.IsEnum;
-#endif
-        }
-
-        internal static MethodInfo GetGetMethod(PropertyInfo property, bool nonPublic, bool allowInternal)
-        {
-            if (property == null) return null;
-#if COREFX || PROFILE259
-            MethodInfo method = property.GetMethod;
-            if (!nonPublic && method != null && !method.IsPublic) method = null;
-            return method;
-#else
-            MethodInfo method = property.GetGetMethod(nonPublic);
-            if (method == null && !nonPublic && allowInternal)
-            { // could be "internal" or "protected internal"; look for a non-public, then back-check
-                method = property.GetGetMethod(true);
-                if (method == null && !(method.IsAssembly || method.IsFamilyOrAssembly))
-                {
-                    method = null;
-                }
-            }
-            return method;
-#endif
-        }
-        internal static MethodInfo GetSetMethod(PropertyInfo property, bool nonPublic, bool allowInternal)
-        {
-            if (property == null) return null;
-#if COREFX || PROFILE259
-            MethodInfo method = property.SetMethod;
-            if (!nonPublic && method != null && !method.IsPublic) method = null;
-            return method;
-#else
-            MethodInfo method = property.GetSetMethod(nonPublic);
-            if (method == null && !nonPublic && allowInternal)
-            { // could be "internal" or "protected internal"; look for a non-public, then back-check
-                method = property.GetGetMethod(true);
-                if (method == null && !(method.IsAssembly || method.IsFamilyOrAssembly))
-                {
-                    method = null;
-                }
-            }
-            return method;
-#endif
-        }
-
-#if COREFX || PORTABLE || PROFILE259
-        private static bool IsMatch(ParameterInfo[] parameters, Type[] parameterTypes)
-        {
-            if (parameterTypes == null) parameterTypes = EmptyTypes;
-            if (parameters.Length != parameterTypes.Length) return false;
-            for (int i = 0; i < parameters.Length; i++)
-            {
-                if (parameters[i].ParameterType != parameterTypes[i]) return false;
-            }
-            return true;
-        }
-#endif
-#if COREFX || PROFILE259
-        internal static ConstructorInfo GetConstructor(Type type, Type[] parameterTypes, bool nonPublic)
-        {
-            return GetConstructor(type.GetTypeInfo(), parameterTypes, nonPublic);
-        }
-        internal static ConstructorInfo GetConstructor(TypeInfo type, Type[] parameterTypes, bool nonPublic)
-        {
-            return GetConstructors(type, nonPublic).SingleOrDefault(ctor => IsMatch(ctor.GetParameters(), parameterTypes));
-        }
-        internal static ConstructorInfo[] GetConstructors(TypeInfo typeInfo, bool nonPublic)
-        {
-            return typeInfo.DeclaredConstructors.Where(c => !c.IsStatic && ((!nonPublic && c.IsPublic) || nonPublic)).ToArray();
-        }
-        internal static PropertyInfo GetProperty(Type type, string name, bool nonPublic)
-        {
-            return GetProperty(type.GetTypeInfo(), name, nonPublic);
-        }
-        internal static PropertyInfo GetProperty(TypeInfo type, string name, bool nonPublic)
-        {
-            return type.GetDeclaredProperty(name);
-        }
-#else
-
-        internal static ConstructorInfo GetConstructor(Type type, Type[] parameterTypes, bool nonPublic)
-        {
-#if PORTABLE || COREFX
-            // pretty sure this will only ever return public, but...
-            ConstructorInfo ctor = type.GetConstructor(parameterTypes);
-            return (ctor != null && (nonPublic || ctor.IsPublic)) ? ctor : null;
-#else
-            return type.GetConstructor(
-                nonPublic ? BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic
-                          : BindingFlags.Instance | BindingFlags.Public,
-                    null, parameterTypes, null);
-#endif
-
-        }
-        internal static ConstructorInfo[] GetConstructors(Type type, bool nonPublic)
-        {
-            return type.GetConstructors(
-                nonPublic ? BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic
-                          : BindingFlags.Instance | BindingFlags.Public);
-        }
-        internal static PropertyInfo GetProperty(Type type, string name, bool nonPublic)
-        {
-            return type.GetProperty(name,
-                nonPublic ? BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic
-                          : BindingFlags.Instance | BindingFlags.Public);
-        }
-#endif
-
-
-        internal static object ParseEnum(Type type, string value)
-        {
-            return Enum.Parse(type, value, true);
-        }
-
-
-        internal static MemberInfo[] GetInstanceFieldsAndProperties(Type type, bool publicOnly)
-        {
-#if PROFILE259
-            var members = new List<MemberInfo>();
-            foreach (FieldInfo field in type.GetRuntimeFields())
-            {
-                if (field.IsStatic) continue;
-                if (field.IsPublic || !publicOnly) members.Add(field);
-            }
-            foreach (PropertyInfo prop in type.GetRuntimeProperties())
-            {
-                MethodInfo getter = Helpers.GetGetMethod(prop, true, true);
-                if (getter == null || getter.IsStatic) continue;
-                if (getter.IsPublic || !publicOnly) members.Add(prop);
-            }
-            return members.ToArray();
-#else
-            BindingFlags flags = publicOnly ? BindingFlags.Public | BindingFlags.Instance : BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic;
-            PropertyInfo[] props = type.GetProperties(flags);
-            FieldInfo[] fields = type.GetFields(flags);
-            MemberInfo[] members = new MemberInfo[fields.Length + props.Length];
-            props.CopyTo(members, 0);
-            fields.CopyTo(members, props.Length);
-            return members;
-#endif
-        }
-
-        internal static Type GetMemberType(MemberInfo member)
-        {
-#if PORTABLE || COREFX || PROFILE259
-            if (member is PropertyInfo prop) return prop.PropertyType;
-            FieldInfo fld = member as FieldInfo;
-            return fld?.FieldType;
-#else
-            switch (member.MemberType)
-            {
-                case MemberTypes.Field: return ((FieldInfo)member).FieldType;
-                case MemberTypes.Property: return ((PropertyInfo)member).PropertyType;
-                default: return null;
-            }
-#endif
-        }
-
-        internal static bool IsAssignableFrom(Type target, Type type)
-        {
-#if PROFILE259
-            return target.GetTypeInfo().IsAssignableFrom(type.GetTypeInfo());
-#else
-            return target.IsAssignableFrom(type);
-#endif
-        }
-        internal static Assembly GetAssembly(Type type)
-        {
-#if COREFX || PROFILE259
-            return type.GetTypeInfo().Assembly;
-#else
-            return type.Assembly;
-#endif
-        }
-        internal static byte[] GetBuffer(MemoryStream ms)
-        {
-#if COREFX
-            if(!ms.TryGetBuffer(out var segment))
-            {
-                throw new InvalidOperationException("Unable to obtain underlying MemoryStream buffer");
-            } else if(segment.Offset != 0)
-            {
-                throw new InvalidOperationException("Underlying MemoryStream buffer was not zero-offset");
-            } else
-            {
-                return segment.Array;
-            }
-#elif PORTABLE || PROFILE259
-            return ms.ToArray();
-#else
-            return ms.GetBuffer();
-#endif
-        }
-    }
-    /// <summary>
-    /// Intended to be a direct map to regular TypeCode, but:
-    /// - with missing types
-    /// - existing on WinRT
-    /// </summary>
-    internal enum ProtoTypeCode
-    {
-        Empty = 0,
-        Unknown = 1, // maps to TypeCode.Object
-        Boolean = 3,
-        Char = 4,
-        SByte = 5,
-        Byte = 6,
-        Int16 = 7,
-        UInt16 = 8,
-        Int32 = 9,
-        UInt32 = 10,
-        Int64 = 11,
-        UInt64 = 12,
-        Single = 13,
-        Double = 14,
-        Decimal = 15,
-        DateTime = 16,
-        String = 18,
-
-        // additions
-        TimeSpan = 100,
-        ByteArray = 101,
-        Guid = 102,
-        Uri = 103,
-        Type = 104
-    }
-}

+ 0 - 23
ThirdParty/protobuf-net/IExtensible.cs

@@ -1,23 +0,0 @@
-
-namespace ProtoBuf
-{
-    /// <summary>
-    /// Indicates that the implementing type has support for protocol-buffer
-    /// <see cref="IExtension">extensions</see>.
-    /// </summary>
-    /// <remarks>Can be implemented by deriving from Extensible.</remarks>
-    public interface IExtensible
-    {
-        /// <summary>
-        /// Retrieves the <see cref="IExtension">extension</see> object for the current
-        /// instance, optionally creating it if it does not already exist.
-        /// </summary>
-        /// <param name="createIfMissing">Should a new extension object be
-        /// created if it does not already exist?</param>
-        /// <returns>The extension object if it exists (or was created), or null
-        /// if the extension object does not exist or is not available.</returns>
-        /// <remarks>The <c>createIfMissing</c> argument is false during serialization,
-        /// and true during deserialization upon encountering unexpected fields.</remarks>
-        IExtension GetExtensionObject(bool createIfMissing);
-    }
-}

+ 0 - 58
ThirdParty/protobuf-net/IExtension.cs

@@ -1,58 +0,0 @@
-
-using System.IO;
-namespace ProtoBuf
-{
-    /// <summary>
-    /// Provides addition capability for supporting unexpected fields during
-    /// protocol-buffer serialization/deserialization. This allows for loss-less
-    /// round-trip/merge, even when the data is not fully understood.
-    /// </summary>
-    public interface IExtension
-    {
-        /// <summary>
-        /// Requests a stream into which any unexpected fields can be persisted.
-        /// </summary>
-        /// <returns>A new stream suitable for storing data.</returns>
-        Stream BeginAppend();
-
-        /// <summary>
-        /// Indicates that all unexpected fields have now been stored. The
-        /// implementing class is responsible for closing the stream. If
-        /// "commit" is not true the data may be discarded.
-        /// </summary>
-        /// <param name="stream">The stream originally obtained by BeginAppend.</param>
-        /// <param name="commit">True if the append operation completed successfully.</param>
-        void EndAppend(Stream stream, bool commit);
-
-        /// <summary>
-        /// Requests a stream of the unexpected fields previously stored.
-        /// </summary>
-        /// <returns>A prepared stream of the unexpected fields.</returns>
-        Stream BeginQuery();
-
-        /// <summary>
-        /// Indicates that all unexpected fields have now been read. The
-        /// implementing class is responsible for closing the stream.
-        /// </summary>
-        /// <param name="stream">The stream originally obtained by BeginQuery.</param>
-        void EndQuery(Stream stream);
-
-        /// <summary>
-        /// Requests the length of the raw binary stream; this is used
-        /// when serializing sub-entities to indicate the expected size.
-        /// </summary>
-        /// <returns>The length of the binary stream representing unexpected data.</returns>
-        int GetLength();
-    }
-
-    /// <summary>
-    /// Provides the ability to remove all existing extension data
-    /// </summary>
-    public interface IExtensionResettable : IExtension
-    {
-        /// <summary>
-        /// Remove all existing extension data
-        /// </summary>
-        void Reset();
-    }
-}

+ 0 - 13
ThirdParty/protobuf-net/IProtoInputT.cs

@@ -1,13 +0,0 @@
-namespace ProtoBuf
-{
-    /// <summary>
-    /// Represents the ability to deserialize values from an input of type <typeparamref name="TInput"/>
-    /// </summary>
-    public interface IProtoInput<TInput>
-    {
-        /// <summary>
-        /// Deserialize a value from the input
-        /// </summary>
-        T Deserialize<T>(TInput source, T value = default, object userState = null);
-    }
-}

+ 0 - 55
ThirdParty/protobuf-net/IProtoOutputT.cs

@@ -1,55 +0,0 @@
-using System;
-
-namespace ProtoBuf
-{
-    /// <summary>
-    /// Represents the ability to serialize values to an output of type <typeparamref name="TOutput"/>
-    /// </summary>
-    public interface IProtoOutput<TOutput>
-    {
-        /// <summary>
-        /// Serialize the provided value
-        /// </summary>
-        void Serialize<T>(TOutput destination, T value, object userState = null);
-    }
-
-    /// <summary>
-    /// Represents the ability to serialize values to an output of type <typeparamref name="TOutput"/>
-    /// with pre-computation of the length
-    /// </summary>
-    public interface IMeasuredProtoOutput<TOutput> : IProtoOutput<TOutput>
-    {
-        /// <summary>
-        /// Measure the length of a value in advance of serialization
-        /// </summary>
-        MeasureState<T> Measure<T>(T value, object userState = null);
-
-        /// <summary>
-        /// Serialize the previously measured value
-        /// </summary>
-        void Serialize<T>(MeasureState<T> measured, TOutput destination);
-    }
-
-    /// <summary>
-    /// Represents the outcome of computing the length of an object; since this may have required computing lengths
-    /// for multiple objects, some metadata is retained so that a subsequent serialize operation using
-    /// this instance can re-use the previously calculated lengths. If the object state changes between the
-    /// measure and serialize operations, the behavior is undefined.
-    /// </summary>
-    public struct MeasureState<T> : IDisposable
-        // note: 2.4.* does not actually implement this API;
-        // it only advertises it for 3.* capability/feature-testing, i.e.
-        // callers can check whether a model implements
-        // IMeasuredProtoOutput<Foo>, and *work from that*
-    {
-        /// <summary>
-        /// Releases all resources associated with this value
-        /// </summary>
-        public void Dispose() => throw new NotImplementedException();
-
-        /// <summary>
-        /// Gets the calculated length of this serialize operation, in bytes
-        /// </summary>
-        public long Length => throw new NotImplementedException();
-    }
-}

+ 0 - 29
ThirdParty/protobuf-net/ImplicitFields.cs

@@ -1,29 +0,0 @@
-namespace ProtoBuf
-{
-    /// <summary>
-    /// Specifies the method used to infer field tags for members of the type
-    /// under consideration. Tags are deduced using the invariant alphabetic
-    /// sequence of the members' names; this makes implicit field tags very brittle,
-    /// and susceptible to changes such as field names (normally an isolated
-    /// change).
-    /// </summary>
-    public enum ImplicitFields
-    {
-        /// <summary>
-        /// No members are serialized implicitly; all members require a suitable
-        /// attribute such as [ProtoMember]. This is the recmomended mode for
-        /// most scenarios.
-        /// </summary>
-        None = 0,
-        /// <summary>
-        /// Public properties and fields are eligible for implicit serialization;
-        /// this treats the public API as a contract. Ordering beings from ImplicitFirstTag.
-        /// </summary>
-        AllPublic = 1,
-        /// <summary>
-        /// Public and non-public fields are eligible for implicit serialization;
-        /// this acts as a state/implementation serializer. Ordering beings from ImplicitFirstTag.
-        /// </summary>
-        AllFields = 2
-    }
-}

+ 0 - 44
ThirdParty/protobuf-net/KeyValuePairProxy.cs

@@ -1,44 +0,0 @@
-//using System.Collections.Generic;
-
-//namespace ProtoBuf
-//{
-//    /// <summary>
-//    /// Mutable version of the common key/value pair struct; used during serialization. This type is intended for internal use only and should not
-//    /// be used by calling code; it is required to be public for implementation reasons.
-//    /// </summary>
-//    [ProtoContract]
-//    public struct KeyValuePairSurrogate<TKey,TValue>
-//    {
-//        private TKey key;
-//        private TValue value;
-//        /// <summary>
-//        /// The key of the pair.
-//        /// </summary>
-//        [ProtoMember(1, IsRequired = true)]
-//        public TKey Key { get { return key; } set { key = value; } }
-//        /// <summary>
-//        /// The value of the pair.
-//        /// </summary>
-//        [ProtoMember(2)]
-//        public TValue Value{ get { return value; } set { this.value = value; } }
-//        private KeyValuePairSurrogate(TKey key, TValue value)
-//        {
-//            this.key = key;
-//            this.value = value;
-//        }
-//        /// <summary>
-//        /// Convert a surrogate instance to a standard pair instance.
-//        /// </summary>
-//        public static implicit operator KeyValuePair<TKey, TValue> (KeyValuePairSurrogate<TKey, TValue> value)
-//        {
-//            return new KeyValuePair<TKey,TValue>(value.key, value.value);
-//        }
-//        /// <summary>
-//        /// Convert a standard pair instance to a surrogate instance.
-//        /// </summary>
-//        public static implicit operator KeyValuePairSurrogate<TKey, TValue>(KeyValuePair<TKey, TValue> value)
-//        {
-//            return new KeyValuePairSurrogate<TKey, TValue>(value.Key, value.Value);
-//        }
-//    }
-//}

+ 0 - 108
ThirdParty/protobuf-net/Meta/AttributeMap.cs

@@ -1,108 +0,0 @@
-#if !NO_RUNTIME
-using System;
-using System.Reflection;
-
-namespace ProtoBuf.Meta
-{
-    internal abstract class AttributeMap
-    {
-#if DEBUG
-        [Obsolete("Please use AttributeType instead")]
-        new public Type GetType() => AttributeType;
-#endif
-        public override string ToString() => AttributeType?.FullName ?? "";
-        public abstract bool TryGet(string key, bool publicOnly, out object value);
-        public bool TryGet(string key, out object value)
-        {
-            return TryGet(key, true, out value);
-        }
-        public abstract Type AttributeType { get; }
-        public static AttributeMap[] Create(TypeModel model, Type type, bool inherit)
-        {
-
-#if COREFX || PROFILE259
-			Attribute[] all = System.Linq.Enumerable.ToArray(System.Linq.Enumerable.OfType<Attribute>(type.GetTypeInfo().GetCustomAttributes(inherit)));
-#else
-            object[] all = type.GetCustomAttributes(inherit);
-#endif
-            AttributeMap[] result = new AttributeMap[all.Length];
-            for(int i = 0 ; i < all.Length ; i++)
-            {
-                result[i] = new ReflectionAttributeMap((Attribute)all[i]);
-            }
-            return result;
-        }
-
-        public static AttributeMap[] Create(TypeModel model, MemberInfo member, bool inherit)
-        {
-
-#if COREFX || PROFILE259
-			Attribute[] all = System.Linq.Enumerable.ToArray(System.Linq.Enumerable.OfType<Attribute>(member.GetCustomAttributes(inherit)));
-#else
-            object[] all = member.GetCustomAttributes(inherit);
-#endif
-            AttributeMap[] result = new AttributeMap[all.Length];
-            for(int i = 0 ; i < all.Length ; i++)
-            {
-                result[i] = new ReflectionAttributeMap((Attribute)all[i]);
-            }
-            return result;
-        }
-        public static AttributeMap[] Create(TypeModel model, Assembly assembly)
-        {
-#if COREFX || PROFILE259
-			Attribute[] all = System.Linq.Enumerable.ToArray(assembly.GetCustomAttributes());
-#else
-            const bool inherit = false;
-            object[] all = assembly.GetCustomAttributes(inherit);
-#endif
-            AttributeMap[] result = new AttributeMap[all.Length];
-            for(int i = 0 ; i < all.Length ; i++)
-            {
-                result[i] = new ReflectionAttributeMap((Attribute)all[i]);
-            }
-            return result;
-
-        }
-
-        public abstract object Target { get; }
-
-        private sealed class ReflectionAttributeMap : AttributeMap
-        {
-            private readonly Attribute attribute;
-
-            public ReflectionAttributeMap(Attribute attribute)
-            {
-                this.attribute = attribute;
-            }
-
-            public override object Target => attribute;
-
-            public override Type AttributeType => attribute.GetType();
-
-            public override bool TryGet(string key, bool publicOnly, out object value)
-            {
-                MemberInfo[] members = Helpers.GetInstanceFieldsAndProperties(attribute.GetType(), publicOnly);
-                foreach (MemberInfo member in members)
-                {
-                    if (string.Equals(member.Name, key, StringComparison.OrdinalIgnoreCase))
-                    {
-                        if (member is PropertyInfo prop) {
-                            value = prop.GetValue(attribute, null);
-                            return true;
-                        }
-                        if (member is FieldInfo field) {
-                            value = field.GetValue(attribute);
-                            return true;
-                        }
-
-                        throw new NotSupportedException(member.GetType().Name);
-                    }
-                }
-                value = null;
-                return false;
-            }
-        }
-    }
-}
-#endif

+ 0 - 267
ThirdParty/protobuf-net/Meta/BasicList.cs

@@ -1,267 +0,0 @@
-using System;
-using System.Collections;
-
-namespace ProtoBuf.Meta
-{
-    internal sealed class MutableList : BasicList
-    {
-        /*  Like BasicList, but allows existing values to be changed
-         */
-        public new object this[int index]
-        {
-            get { return head[index]; }
-            set { head[index] = value; }
-        }
-        public void RemoveLast()
-        {
-            head.RemoveLastWithMutate();
-        }
-
-        public void Clear()
-        {
-            head.Clear();
-        }
-    }
-
-    internal class BasicList : IEnumerable
-    {
-        /* Requirements:
-         *   - Fast access by index
-         *   - Immutable in the tail, so a node can be read (iterated) without locking
-         *   - Lock-free tail handling must match the memory mode; struct for Node
-         *     wouldn't work as "read" would not be atomic
-         *   - Only operation required is append, but this shouldn't go out of its
-         *     way to be inefficient
-         *   - Assume that the caller is handling thread-safety (to co-ordinate with
-         *     other code); no attempt to be thread-safe
-         *   - Assume that the data is private; internal data structure is allowed to
-         *     be mutable (i.e. array is fine as long as we don't screw it up)
-         */
-        private static readonly Node nil = new Node(null, 0);
-
-        public void CopyTo(Array array, int offset)
-        {
-            head.CopyTo(array, offset);
-        }
-
-        protected Node head = nil;
-
-        public int Add(object value)
-        {
-            return (head = head.Append(value)).Length - 1;
-        }
-
-        public object this[int index] => head[index];
-
-        //public object TryGet(int index)
-        //{
-        //    return head.TryGet(index);
-        //}
-
-        public void Trim() { head = head.Trim(); }
-
-        public int Count => head.Length;
-
-        IEnumerator IEnumerable.GetEnumerator() => new NodeEnumerator(head);
-
-        public NodeEnumerator GetEnumerator() => new NodeEnumerator(head);
-
-        public struct NodeEnumerator : IEnumerator
-        {
-            private int position;
-            private readonly Node node;
-            internal NodeEnumerator(Node node)
-            {
-                this.position = -1;
-                this.node = node;
-            }
-            void IEnumerator.Reset() { position = -1; }
-            public object Current { get { return node[position]; } }
-            public bool MoveNext()
-            {
-                int len = node.Length;
-                return (position <= len) && (++position < len);
-            }
-        }
-
-        internal sealed class Node
-        {
-            public object this[int index]
-            {
-                get
-                {
-                    if (index >= 0 && index < length)
-                    {
-                        return data[index];
-                    }
-                    throw new ArgumentOutOfRangeException(nameof(index));
-                }
-                set
-                {
-                    if (index >= 0 && index < length)
-                    {
-                        data[index] = value;
-                    }
-                    else
-                    {
-                        throw new ArgumentOutOfRangeException(nameof(index));
-                    }
-                }
-            }
-            //public object TryGet(int index)
-            //{
-            //    return (index >= 0 && index < length) ? data[index] : null;
-            //}
-            private readonly object[] data;
-
-            private int length;
-            public int Length => length;
-
-            internal Node(object[] data, int length)
-            {
-                Helpers.DebugAssert((data == null && length == 0) ||
-                    (data != null && length > 0 && length <= data.Length));
-                this.data = data;
-
-                this.length = length;
-            }
-
-            public void RemoveLastWithMutate()
-            {
-                if (length == 0) throw new InvalidOperationException();
-                length -= 1;
-            }
-
-            public Node Append(object value)
-            {
-                object[] newData;
-                int newLength = length + 1;
-                if (data == null)
-                {
-                    newData = new object[10];
-                }
-                else if (length == data.Length)
-                {
-                    newData = new object[data.Length * 2];
-                    Array.Copy(data, newData, length);
-                }
-                else
-                {
-                    newData = data;
-                }
-                newData[length] = value;
-                return new Node(newData, newLength);
-            }
-
-            public Node Trim()
-            {
-                if (length == 0 || length == data.Length) return this;
-                object[] newData = new object[length];
-                Array.Copy(data, newData, length);
-                return new Node(newData, length);
-            }
-
-            internal int IndexOfString(string value)
-            {
-                for (int i = 0; i < length; i++)
-                {
-                    if ((string)value == (string)data[i]) return i;
-                }
-                return -1;
-            }
-
-            internal int IndexOfReference(object instance)
-            {
-                for (int i = 0; i < length; i++)
-                {
-                    if ((object)instance == (object)data[i]) return i;
-                } // ^^^ (object) above should be preserved, even if this was typed; needs
-                  // to be a reference check
-                return -1;
-            }
-
-            internal int IndexOf(MatchPredicate predicate, object ctx)
-            {
-                for (int i = 0; i < length; i++)
-                {
-                    if (predicate(data[i], ctx)) return i;
-                }
-                return -1;
-            }
-
-            internal void CopyTo(Array array, int offset)
-            {
-                if (length > 0)
-                {
-                    Array.Copy(data, 0, array, offset, length);
-                }
-            }
-
-            internal void Clear()
-            {
-                if (data != null)
-                {
-                    Array.Clear(data, 0, data.Length);
-                }
-                length = 0;
-            }
-        }
-
-        internal int IndexOf(MatchPredicate predicate, object ctx)
-        {
-            return head.IndexOf(predicate, ctx);
-        }
-
-        internal int IndexOfString(string value)
-        {
-            return head.IndexOfString(value);
-        }
-
-        internal int IndexOfReference(object instance)
-        {
-            return head.IndexOfReference(instance);
-        }
-
-        internal delegate bool MatchPredicate(object value, object ctx);
-
-        internal bool Contains(object value)
-        {
-            foreach (object obj in this)
-            {
-                if (object.Equals(obj, value)) return true;
-            }
-            return false;
-        }
-
-        internal sealed class Group
-        {
-            public readonly int First;
-            public readonly BasicList Items;
-            public Group(int first)
-            {
-                this.First = first;
-                this.Items = new BasicList();
-            }
-        }
-
-        internal static BasicList GetContiguousGroups(int[] keys, object[] values)
-        {
-            if (keys == null) throw new ArgumentNullException(nameof(keys));
-            if (values == null) throw new ArgumentNullException(nameof(values));
-            if (values.Length < keys.Length) throw new ArgumentException("Not all keys are covered by values", nameof(values));
-            BasicList outer = new BasicList();
-            Group group = null;
-            for (int i = 0; i < keys.Length; i++)
-            {
-                if (i == 0 || keys[i] != keys[i - 1]) { group = null; }
-                if (group == null)
-                {
-                    group = new Group(keys[i]);
-                    outer.Add(group);
-                }
-                group.Items.Add(values[i]);
-            }
-            return outer;
-        }
-    }
-}

+ 0 - 110
ThirdParty/protobuf-net/Meta/CallbackSet.cs

@@ -1,110 +0,0 @@
-#if !NO_RUNTIME
-using System;
-using System.Reflection;
-
-namespace ProtoBuf.Meta
-{
-    /// <summary>
-    /// Represents the set of serialization callbacks to be used when serializing/deserializing a type.
-    /// </summary>
-    public class CallbackSet
-    {
-        private readonly MetaType metaType;
-        internal CallbackSet(MetaType metaType)
-        {
-            this.metaType = metaType ?? throw new ArgumentNullException(nameof(metaType));
-        }
-
-        internal MethodInfo this[TypeModel.CallbackType callbackType]
-        {
-            get
-            {
-                switch (callbackType)
-                {
-                    case TypeModel.CallbackType.BeforeSerialize: return beforeSerialize;
-                    case TypeModel.CallbackType.AfterSerialize: return afterSerialize;
-                    case TypeModel.CallbackType.BeforeDeserialize: return beforeDeserialize;
-                    case TypeModel.CallbackType.AfterDeserialize: return afterDeserialize;
-                    default: throw new ArgumentException("Callback type not supported: " + callbackType.ToString(), "callbackType");
-                }
-            }
-        }
-
-        internal static bool CheckCallbackParameters(TypeModel model, MethodInfo method)
-        {
-            ParameterInfo[] args = method.GetParameters();
-            for (int i = 0; i < args.Length; i++)
-            {
-                Type paramType = args[i].ParameterType;
-                if (paramType == model.MapType(typeof(SerializationContext))) { }
-                else if (paramType == model.MapType(typeof(System.Type))) { }
-#if PLAT_BINARYFORMATTER
-                else if (paramType == model.MapType(typeof(System.Runtime.Serialization.StreamingContext))) { }
-#endif
-                else return false;
-            }
-            return true;
-        }
-
-        private MethodInfo SanityCheckCallback(TypeModel model, MethodInfo callback)
-        {
-            metaType.ThrowIfFrozen();
-            if (callback == null) return callback; // fine
-            if (callback.IsStatic) throw new ArgumentException("Callbacks cannot be static", nameof(callback));
-            if (callback.ReturnType != model.MapType(typeof(void))
-                || !CheckCallbackParameters(model, callback))
-            {
-                throw CreateInvalidCallbackSignature(callback);
-            }
-            return callback;
-        }
-
-        internal static Exception CreateInvalidCallbackSignature(MethodInfo method)
-        {
-            return new NotSupportedException("Invalid callback signature in " + method.DeclaringType.FullName + "." + method.Name);
-        }
-
-        private MethodInfo beforeSerialize, afterSerialize, beforeDeserialize, afterDeserialize;
-
-        /// <summary>Called before serializing an instance</summary>
-        public MethodInfo BeforeSerialize
-        {
-            get { return beforeSerialize; }
-            set { beforeSerialize = SanityCheckCallback(metaType.Model, value); }
-        }
-
-        /// <summary>Called before deserializing an instance</summary>
-        public MethodInfo BeforeDeserialize
-        {
-            get { return beforeDeserialize; }
-            set { beforeDeserialize = SanityCheckCallback(metaType.Model, value); }
-        }
-
-        /// <summary>Called after serializing an instance</summary>
-        public MethodInfo AfterSerialize
-        {
-            get { return afterSerialize; }
-            set { afterSerialize = SanityCheckCallback(metaType.Model, value); }
-        }
-
-        /// <summary>Called after deserializing an instance</summary>
-        public MethodInfo AfterDeserialize
-        {
-            get { return afterDeserialize; }
-            set { afterDeserialize = SanityCheckCallback(metaType.Model, value); }
-        }
-
-        /// <summary>
-        /// True if any callback is set, else False
-        /// </summary>
-        public bool NonTrivial
-        {
-            get
-            {
-                return beforeSerialize != null || beforeDeserialize != null
-                    || afterSerialize != null || afterDeserialize != null;
-            }
-        }
-    }
-}
-#endif

+ 0 - 2160
ThirdParty/protobuf-net/Meta/MetaType.cs

@@ -1,2160 +0,0 @@
-#if !NO_RUNTIME
-using System;
-using System.Collections;
-using System.Text;
-using ProtoBuf.Serializers;
-using System.Reflection;
-using System.Collections.Generic;
-
-#if PROFILE259
-using System.Linq;
-#endif
-
-namespace ProtoBuf.Meta
-{
-    /// <summary>
-    /// Represents a type at runtime for use with protobuf, allowing the field mappings (etc) to be defined
-    /// </summary>
-    public class MetaType : ISerializerProxy
-    {
-        internal sealed class Comparer : IComparer, IComparer<MetaType>
-        {
-            public static readonly Comparer Default = new Comparer();
-            public int Compare(object x, object y)
-            {
-                return Compare(x as MetaType, y as MetaType);
-            }
-            public int Compare(MetaType x, MetaType y)
-            {
-                if (ReferenceEquals(x, y)) return 0;
-                if (x == null) return -1;
-                if (y == null) return 1;
-
-                return string.Compare(x.GetSchemaTypeName(), y.GetSchemaTypeName(), StringComparison.Ordinal);
-            }
-        }
-        /// <summary>
-        /// Get the name of the type being represented
-        /// </summary>
-        public override string ToString()
-        {
-            return type.ToString();
-        }
-
-        IProtoSerializer ISerializerProxy.Serializer => Serializer;
-        private MetaType baseType;
-
-        /// <summary>
-        /// Gets the base-type for this type
-        /// </summary>
-        public MetaType BaseType => baseType;
-
-        internal TypeModel Model => model;
-
-        /// <summary>
-        /// When used to compile a model, should public serialization/deserialzation methods
-        /// be included for this type?
-        /// </summary>
-        public bool IncludeSerializerMethod
-        {   // negated to minimize common-case / initializer
-            get { return !HasFlag(OPTIONS_PrivateOnApi); }
-            set { SetFlag(OPTIONS_PrivateOnApi, !value, true); }
-        }
-
-        /// <summary>
-        /// Should this type be treated as a reference by default?
-        /// </summary>
-        public bool AsReferenceDefault
-        {
-            get { return HasFlag(OPTIONS_AsReferenceDefault); }
-            set { SetFlag(OPTIONS_AsReferenceDefault, value, true); }
-        }
-
-        private BasicList subTypes;
-        private bool IsValidSubType(Type subType)
-        {
-#if COREFX || PROFILE259
-            return typeInfo.IsAssignableFrom(subType.GetTypeInfo());
-#else
-            return type.IsAssignableFrom(subType);
-#endif
-        }
-        /// <summary>
-        /// Adds a known sub-type to the inheritance model
-        /// </summary>
-        public MetaType AddSubType(int fieldNumber, Type derivedType)
-        {
-            return AddSubType(fieldNumber, derivedType, DataFormat.Default);
-        }
-        /// <summary>
-        /// Adds a known sub-type to the inheritance model
-        /// </summary>
-        public MetaType AddSubType(int fieldNumber, Type derivedType, DataFormat dataFormat)
-        {
-            if (derivedType == null) throw new ArgumentNullException("derivedType");
-            if (fieldNumber < 1) throw new ArgumentOutOfRangeException("fieldNumber");
-#if COREFX || COREFX || PROFILE259
-			if (!(typeInfo.IsClass || typeInfo.IsInterface) || typeInfo.IsSealed) {
-#else
-            if (!(type.IsClass || type.IsInterface) || type.IsSealed)
-            {
-#endif
-                throw new InvalidOperationException("Sub-types can only be added to non-sealed classes");
-            }
-            if (!IsValidSubType(derivedType))
-            {
-                throw new ArgumentException(derivedType.Name + " is not a valid sub-type of " + type.Name, "derivedType");
-            }
-            MetaType derivedMeta = model[derivedType];
-            ThrowIfFrozen();
-            derivedMeta.ThrowIfFrozen();
-            SubType subType = new SubType(fieldNumber, derivedMeta, dataFormat);
-            ThrowIfFrozen();
-
-            derivedMeta.SetBaseType(this); // includes ThrowIfFrozen
-            if (subTypes == null) subTypes = new BasicList();
-            subTypes.Add(subType);
-            model.ResetKeyCache();
-            return this;
-        }
-#if COREFX || PROFILE259
-		internal static readonly TypeInfo ienumerable = typeof(IEnumerable).GetTypeInfo();
-#else
-        internal static readonly Type ienumerable = typeof(IEnumerable);
-#endif
-        private void SetBaseType(MetaType baseType)
-        {
-            if (baseType == null) throw new ArgumentNullException("baseType");
-            if (this.baseType == baseType) return;
-            if (this.baseType != null) throw new InvalidOperationException($"Type '{this.baseType.Type.FullName}' can only participate in one inheritance hierarchy");
-
-            MetaType type = baseType;
-            while (type != null)
-            {
-                if (ReferenceEquals(type, this)) throw new InvalidOperationException($"Cyclic inheritance of '{this.baseType.Type.FullName}' is not allowed");
-                type = type.baseType;
-            }
-            this.baseType = baseType;
-        }
-
-        private CallbackSet callbacks;
-
-        /// <summary>
-        /// Indicates whether the current type has defined callbacks 
-        /// </summary>
-        public bool HasCallbacks => callbacks != null && callbacks.NonTrivial;
-
-        /// <summary>
-        /// Indicates whether the current type has defined subtypes
-        /// </summary>
-        public bool HasSubtypes => subTypes != null && subTypes.Count != 0;
-
-        /// <summary>
-        /// Returns the set of callbacks defined for this type
-        /// </summary>
-        public CallbackSet Callbacks
-        {
-            get
-            {
-                if (callbacks == null) callbacks = new CallbackSet(this);
-                return callbacks;
-            }
-        }
-
-        private bool IsValueType
-        {
-            get
-            {
-#if COREFX || PROFILE259
-				return typeInfo.IsValueType;
-#else
-                return type.IsValueType;
-#endif
-            }
-        }
-        /// <summary>
-        /// Assigns the callbacks to use during serialiation/deserialization.
-        /// </summary>
-        /// <param name="beforeSerialize">The method (or null) called before serialization begins.</param>
-        /// <param name="afterSerialize">The method (or null) called when serialization is complete.</param>
-        /// <param name="beforeDeserialize">The method (or null) called before deserialization begins (or when a new instance is created during deserialization).</param>
-        /// <param name="afterDeserialize">The method (or null) called when deserialization is complete.</param>
-        /// <returns>The set of callbacks.</returns>
-        public MetaType SetCallbacks(MethodInfo beforeSerialize, MethodInfo afterSerialize, MethodInfo beforeDeserialize, MethodInfo afterDeserialize)
-        {
-            CallbackSet callbacks = Callbacks;
-            callbacks.BeforeSerialize = beforeSerialize;
-            callbacks.AfterSerialize = afterSerialize;
-            callbacks.BeforeDeserialize = beforeDeserialize;
-            callbacks.AfterDeserialize = afterDeserialize;
-            return this;
-        }
-        /// <summary>
-        /// Assigns the callbacks to use during serialiation/deserialization.
-        /// </summary>
-        /// <param name="beforeSerialize">The name of the method (or null) called before serialization begins.</param>
-        /// <param name="afterSerialize">The name of the method (or null) called when serialization is complete.</param>
-        /// <param name="beforeDeserialize">The name of the method (or null) called before deserialization begins (or when a new instance is created during deserialization).</param>
-        /// <param name="afterDeserialize">The name of the method (or null) called when deserialization is complete.</param>
-        /// <returns>The set of callbacks.</returns>
-        public MetaType SetCallbacks(string beforeSerialize, string afterSerialize, string beforeDeserialize, string afterDeserialize)
-        {
-            if (IsValueType) throw new InvalidOperationException();
-            CallbackSet callbacks = Callbacks;
-            callbacks.BeforeSerialize = ResolveMethod(beforeSerialize, true);
-            callbacks.AfterSerialize = ResolveMethod(afterSerialize, true);
-            callbacks.BeforeDeserialize = ResolveMethod(beforeDeserialize, true);
-            callbacks.AfterDeserialize = ResolveMethod(afterDeserialize, true);
-            return this;
-        }
-
-        internal string GetSchemaTypeName()
-        {
-            if (surrogate != null) return model[surrogate].GetSchemaTypeName();
-
-            if (!string.IsNullOrEmpty(name)) return name;
-
-            string typeName = type.Name;
-            if (type
-#if COREFX || PROFILE259
-				.GetTypeInfo()
-#endif
-                .IsGenericType)
-            {
-                var sb = new StringBuilder(typeName);
-                int split = typeName.IndexOf('`');
-                if (split >= 0) sb.Length = split;
-                foreach (Type arg in type
-#if COREFX || PROFILE259
-					.GetTypeInfo().GenericTypeArguments
-#else
-                    .GetGenericArguments()
-#endif
-                    )
-                {
-                    sb.Append('_');
-                    Type tmp = arg;
-                    int key = model.GetKey(ref tmp);
-                    MetaType mt;
-                    if (key >= 0 && (mt = model[tmp]) != null && mt.surrogate == null) // <=== need to exclude surrogate to avoid chance of infinite loop
-                    {
-
-                        sb.Append(mt.GetSchemaTypeName());
-                    }
-                    else
-                    {
-                        sb.Append(tmp.Name);
-                    }
-                }
-                return sb.ToString();
-            }
-
-            return typeName;
-        }
-
-        private string name;
-
-        /// <summary>
-        /// Gets or sets the name of this contract.
-        /// </summary>
-        public string Name
-        {
-            get
-            {
-                return name;
-            }
-            set
-            {
-                ThrowIfFrozen();
-                name = value;
-            }
-        }
-
-        private MethodInfo factory;
-        /// <summary>
-        /// Designate a factory-method to use to create instances of this type
-        /// </summary>
-        public MetaType SetFactory(MethodInfo factory)
-        {
-            model.VerifyFactory(factory, type);
-            ThrowIfFrozen();
-            this.factory = factory;
-            return this;
-        }
-
-        /// <summary>
-        /// Designate a factory-method to use to create instances of this type
-        /// </summary>
-        public MetaType SetFactory(string factory)
-        {
-            return SetFactory(ResolveMethod(factory, false));
-        }
-
-        private MethodInfo ResolveMethod(string name, bool instance)
-        {
-            if (string.IsNullOrEmpty(name)) return null;
-#if COREFX
-            return instance ? Helpers.GetInstanceMethod(typeInfo, name) : Helpers.GetStaticMethod(typeInfo, name);
-#else
-            return instance ? Helpers.GetInstanceMethod(type, name) : Helpers.GetStaticMethod(type, name);
-#endif
-        }
-
-        private readonly RuntimeTypeModel model;
-
-        internal static Exception InbuiltType(Type type)
-        {
-            return new ArgumentException("Data of this type has inbuilt behaviour, and cannot be added to a model in this way: " + type.FullName);
-        }
-
-        internal MetaType(RuntimeTypeModel model, Type type, MethodInfo factory)
-        {
-            this.factory = factory;
-            if (model == null) throw new ArgumentNullException("model");
-            if (type == null) throw new ArgumentNullException("type");
-
-            if (type.IsArray) throw InbuiltType(type);
-            IProtoSerializer coreSerializer = model.TryGetBasicTypeSerializer(type);
-            if (coreSerializer != null)
-            {
-                throw InbuiltType(type);
-            }
-
-            this.type = type;
-#if COREFX || PROFILE259
-			this.typeInfo = type.GetTypeInfo();
-#endif
-            this.model = model;
-
-            if (Helpers.IsEnum(type))
-            {
-#if COREFX || PROFILE259
-				EnumPassthru = typeInfo.IsDefined(typeof(FlagsAttribute), false);
-#else
-                EnumPassthru = type.IsDefined(model.MapType(typeof(FlagsAttribute)), false);
-#endif
-            }
-        }
-#if COREFX || PROFILE259
-		private readonly TypeInfo typeInfo;
-#endif
-        /// <summary>
-        /// Throws an exception if the type has been made immutable
-        /// </summary>
-        protected internal void ThrowIfFrozen()
-        {
-            if ((flags & OPTIONS_Frozen) != 0) throw new InvalidOperationException("The type cannot be changed once a serializer has been generated for " + type.FullName);
-        }
-
-        // internal void Freeze() { flags |= OPTIONS_Frozen; }
-
-        private readonly Type type;
-        /// <summary>
-        /// The runtime type that the meta-type represents
-        /// </summary>
-        public Type Type => type;
-
-        private IProtoTypeSerializer serializer;
-        internal IProtoTypeSerializer Serializer
-        {
-            get
-            {
-                if (serializer == null)
-                {
-                    int opaqueToken = 0;
-                    try
-                    {
-                        model.TakeLock(ref opaqueToken);
-                        if (serializer == null)
-                        { // double-check, but our main purpse with this lock is to ensure thread-safety with
-                            // serializers needing to wait until another thread has finished adding the properties
-                            SetFlag(OPTIONS_Frozen, true, false);
-                            serializer = BuildSerializer();
-#if FEAT_COMPILER
-                            if (model.AutoCompile) CompileInPlace();
-#endif
-                        }
-                    }
-                    finally
-                    {
-                        model.ReleaseLock(opaqueToken);
-                    }
-                }
-                return serializer;
-            }
-        }
-        internal bool IsList
-        {
-            get
-            {
-                Type itemType = IgnoreListHandling ? null : TypeModel.GetListItemType(model, type);
-                return itemType != null;
-            }
-        }
-        private IProtoTypeSerializer BuildSerializer()
-        {
-            if (Helpers.IsEnum(type))
-            {
-                return new TagDecorator(ProtoBuf.Serializer.ListItemTag, WireType.Variant, false, new EnumSerializer(type, GetEnumMap()));
-            }
-            Type itemType = IgnoreListHandling ? null : TypeModel.GetListItemType(model, type);
-            if (itemType != null)
-            {
-                if (surrogate != null)
-                {
-                    throw new ArgumentException("Repeated data (a list, collection, etc) has inbuilt behaviour and cannot use a surrogate");
-                }
-                if (subTypes != null && subTypes.Count != 0)
-                {
-                    throw new ArgumentException("Repeated data (a list, collection, etc) has inbuilt behaviour and cannot be subclassed");
-                }
-                Type defaultType = null;
-                ResolveListTypes(model, type, ref itemType, ref defaultType);
-                ValueMember fakeMember = new ValueMember(model, ProtoBuf.Serializer.ListItemTag, type, itemType, defaultType, DataFormat.Default);
-                return new TypeSerializer(model, type, new int[] { ProtoBuf.Serializer.ListItemTag }, new IProtoSerializer[] { fakeMember.Serializer }, null, true, true, null, constructType, factory);
-            }
-            if (surrogate != null)
-            {
-                MetaType mt = model[surrogate], mtBase;
-                while ((mtBase = mt.baseType) != null) { mt = mtBase; }
-                return new SurrogateSerializer(model, type, surrogate, mt.Serializer);
-            }
-            if (IsAutoTuple)
-            {
-                ConstructorInfo ctor = ResolveTupleConstructor(type, out MemberInfo[] mapping);
-                if (ctor == null) throw new InvalidOperationException();
-                return new TupleSerializer(model, ctor, mapping);
-            }
-
-            fields.Trim();
-            int fieldCount = fields.Count;
-            int subTypeCount = subTypes == null ? 0 : subTypes.Count;
-            int[] fieldNumbers = new int[fieldCount + subTypeCount];
-            IProtoSerializer[] serializers = new IProtoSerializer[fieldCount + subTypeCount];
-            int i = 0;
-            if (subTypeCount != 0)
-            {
-                foreach (SubType subType in subTypes)
-                {
-#if COREFX || PROFILE259
-					if (!subType.DerivedType.IgnoreListHandling && ienumerable.IsAssignableFrom(subType.DerivedType.Type.GetTypeInfo()))
-#else
-                    if (!subType.DerivedType.IgnoreListHandling && model.MapType(ienumerable).IsAssignableFrom(subType.DerivedType.Type))
-#endif
-                    {
-                        throw new ArgumentException("Repeated data (a list, collection, etc) has inbuilt behaviour and cannot be used as a subclass");
-                    }
-                    fieldNumbers[i] = subType.FieldNumber;
-                    serializers[i++] = subType.Serializer;
-                }
-            }
-            if (fieldCount != 0)
-            {
-                foreach (ValueMember member in fields)
-                {
-                    fieldNumbers[i] = member.FieldNumber;
-                    serializers[i++] = member.Serializer;
-                }
-            }
-
-            BasicList baseCtorCallbacks = null;
-            MetaType tmp = BaseType;
-
-            while (tmp != null)
-            {
-                MethodInfo method = tmp.HasCallbacks ? tmp.Callbacks.BeforeDeserialize : null;
-                if (method != null)
-                {
-                    if (baseCtorCallbacks == null) baseCtorCallbacks = new BasicList();
-                    baseCtorCallbacks.Add(method);
-                }
-                tmp = tmp.BaseType;
-            }
-            MethodInfo[] arr = null;
-            if (baseCtorCallbacks != null)
-            {
-                arr = new MethodInfo[baseCtorCallbacks.Count];
-                baseCtorCallbacks.CopyTo(arr, 0);
-                Array.Reverse(arr);
-            }
-            return new TypeSerializer(model, type, fieldNumbers, serializers, arr, baseType == null, UseConstructor, callbacks, constructType, factory);
-        }
-
-        [Flags]
-        internal enum AttributeFamily
-        {
-            None = 0, ProtoBuf = 1, DataContractSerialier = 2, XmlSerializer = 4, AutoTuple = 8
-        }
-        static Type GetBaseType(MetaType type)
-        {
-#if COREFX || PROFILE259
-			return type.typeInfo.BaseType;
-#else
-            return type.type.BaseType;
-#endif
-        }
-        internal static bool GetAsReferenceDefault(RuntimeTypeModel model, Type type)
-        {
-            if (type == null) throw new ArgumentNullException(nameof(type));
-            if (Helpers.IsEnum(type)) return false; // never as-ref
-            AttributeMap[] typeAttribs = AttributeMap.Create(model, type, false);
-            for (int i = 0; i < typeAttribs.Length; i++)
-            {
-                if (typeAttribs[i].AttributeType.FullName == "ProtoBuf.ProtoContractAttribute")
-                {
-                    if (typeAttribs[i].TryGet("AsReferenceDefault", out object tmp)) return (bool)tmp;
-                }
-            }
-            return false;
-        }
-
-        internal void ApplyDefaultBehaviour()
-        {
-            Type baseType = GetBaseType(this);
-            if (baseType != null && model.FindWithoutAdd(baseType) == null
-                && GetContractFamily(model, baseType, null) != MetaType.AttributeFamily.None)
-            {
-                model.FindOrAddAuto(baseType, true, false, false);
-            }
-
-            AttributeMap[] typeAttribs = AttributeMap.Create(model, type, false);
-            AttributeFamily family = GetContractFamily(model, type, typeAttribs);
-            if (family == AttributeFamily.AutoTuple)
-            {
-                SetFlag(OPTIONS_AutoTuple, true, true);
-            }
-            bool isEnum = !EnumPassthru && Helpers.IsEnum(type);
-            if (family == AttributeFamily.None && !isEnum) return; // and you'd like me to do what, exactly?
-
-            bool enumShouldUseImplicitPassThru = isEnum;
-            BasicList partialIgnores = null, partialMembers = null;
-            int dataMemberOffset = 0, implicitFirstTag = 1;
-            bool inferTagByName = model.InferTagFromNameDefault;
-            ImplicitFields implicitMode = ImplicitFields.None;
-            string name = null;
-            for (int i = 0; i < typeAttribs.Length; i++)
-            {
-                AttributeMap item = (AttributeMap)typeAttribs[i];
-                object tmp;
-                string fullAttributeTypeName = item.AttributeType.FullName;
-                if (!isEnum && fullAttributeTypeName == "ProtoBuf.ProtoIncludeAttribute")
-                {
-                    int tag = 0;
-                    if (item.TryGet("tag", out tmp)) tag = (int)tmp;
-                    DataFormat dataFormat = DataFormat.Default;
-                    if (item.TryGet("DataFormat", out tmp))
-                    {
-                        dataFormat = (DataFormat)(int)tmp;
-                    }
-                    Type knownType = null;
-                    try
-                    {
-                        if (item.TryGet("knownTypeName", out tmp)) knownType = model.GetType((string)tmp, type
-#if COREFX || PROFILE259
-							.GetTypeInfo()
-#endif
-                            .Assembly);
-                        else if (item.TryGet("knownType", out tmp)) knownType = (Type)tmp;
-                    }
-                    catch (Exception ex)
-                    {
-                        throw new InvalidOperationException("Unable to resolve sub-type of: " + type.FullName, ex);
-                    }
-                    if (knownType == null)
-                    {
-                        throw new InvalidOperationException("Unable to resolve sub-type of: " + type.FullName);
-                    }
-                    if (IsValidSubType(knownType)) AddSubType(tag, knownType, dataFormat);
-                }
-
-                if (fullAttributeTypeName == "ProtoBuf.ProtoPartialIgnoreAttribute")
-                {
-                    if (item.TryGet(nameof(ProtoPartialIgnoreAttribute.MemberName), out tmp) && tmp != null)
-                    {
-                        if (partialIgnores == null) partialIgnores = new BasicList();
-                        partialIgnores.Add((string)tmp);
-                    }
-                }
-                if (!isEnum && fullAttributeTypeName == "ProtoBuf.ProtoPartialMemberAttribute")
-                {
-                    if (partialMembers == null) partialMembers = new BasicList();
-                    partialMembers.Add(item);
-                }
-
-                if (fullAttributeTypeName == "ProtoBuf.ProtoContractAttribute")
-                {
-                    if (item.TryGet(nameof(ProtoContractAttribute.Name), out tmp)) name = (string)tmp;
-                    if (Helpers.IsEnum(type)) // note this is subtly different to isEnum; want to do this even if [Flags]
-                    {
-                        if (item.TryGet(nameof(ProtoContractAttribute.EnumPassthruHasValue), false, out tmp) && (bool)tmp)
-                        {
-                            if (item.TryGet(nameof(ProtoContractAttribute.EnumPassthru), out tmp))
-                            {
-                                EnumPassthru = (bool)tmp;
-                                enumShouldUseImplicitPassThru = false;
-                                if (EnumPassthru) isEnum = false; // no longer treated as an enum
-                            }
-                        }
-                    }
-                    else
-                    {
-                        if (item.TryGet(nameof(ProtoContractAttribute.DataMemberOffset), out tmp)) dataMemberOffset = (int)tmp;
-
-                        if (item.TryGet(nameof(ProtoContractAttribute.InferTagFromNameHasValue), false, out tmp) && (bool)tmp)
-                        {
-                            if (item.TryGet(nameof(ProtoContractAttribute.InferTagFromName), out tmp)) inferTagByName = (bool)tmp;
-                        }
-
-                        if (item.TryGet(nameof(ProtoContractAttribute.ImplicitFields), out tmp) && tmp != null)
-                        {
-                            implicitMode = (ImplicitFields)(int)tmp; // note that this uses the bizarre unboxing rules of enums/underlying-types
-                        }
-
-                        if (item.TryGet(nameof(ProtoContractAttribute.SkipConstructor), out tmp)) UseConstructor = !(bool)tmp;
-                        if (item.TryGet(nameof(ProtoContractAttribute.IgnoreListHandling), out tmp)) IgnoreListHandling = (bool)tmp;
-                        if (item.TryGet(nameof(ProtoContractAttribute.AsReferenceDefault), out tmp)) AsReferenceDefault = (bool)tmp;
-                        if (item.TryGet(nameof(ProtoContractAttribute.ImplicitFirstTag), out tmp) && (int)tmp > 0) implicitFirstTag = (int)tmp;
-                        if (item.TryGet(nameof(ProtoContractAttribute.IsGroup), out tmp)) IsGroup = (bool)tmp;
-
-                        if (item.TryGet(nameof(ProtoContractAttribute.Surrogate), out tmp))
-                        {
-                            SetSurrogate((Type)tmp);
-                        }
-                    }
-                }
-
-                if (fullAttributeTypeName == "System.Runtime.Serialization.DataContractAttribute")
-                {
-                    if (name == null && item.TryGet("Name", out tmp)) name = (string)tmp;
-                }
-                if (fullAttributeTypeName == "System.Xml.Serialization.XmlTypeAttribute")
-                {
-                    if (name == null && item.TryGet("TypeName", out tmp)) name = (string)tmp;
-                }
-            }
-            if (!string.IsNullOrEmpty(name)) Name = name;
-            if (implicitMode != ImplicitFields.None)
-            {
-                family &= AttributeFamily.ProtoBuf; // with implicit fields, **only** proto attributes are important
-            }
-            MethodInfo[] callbacks = null;
-
-            BasicList members = new BasicList();
-
-#if PROFILE259
-			IEnumerable<MemberInfo> foundList;
-            if(isEnum) {
-                foundList = type.GetRuntimeFields();
-            }
-            else
-            {
-                List<MemberInfo> list = new List<MemberInfo>();
-                foreach(PropertyInfo prop in type.GetRuntimeProperties()) {
-                    MethodInfo getter = Helpers.GetGetMethod(prop, false, false);
-                    if(getter != null && !getter.IsStatic) list.Add(prop);
-                }
-                foreach(FieldInfo fld in type.GetRuntimeFields()) if(fld.IsPublic && !fld.IsStatic) list.Add(fld);
-                foreach(MethodInfo mthd in type.GetRuntimeMethods()) if(mthd.IsPublic && !mthd.IsStatic) list.Add(mthd);
-                foundList = list;
-            }
-#else
-            MemberInfo[] foundList = type.GetMembers(isEnum ? BindingFlags.Public | BindingFlags.Static
-                : BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
-#endif
-            bool hasConflictingEnumValue = false;
-            foreach (MemberInfo member in foundList)
-            {
-                if (member.DeclaringType != type) continue;
-                if (member.IsDefined(model.MapType(typeof(ProtoIgnoreAttribute)), true)) continue;
-                if (partialIgnores != null && partialIgnores.Contains(member.Name)) continue;
-
-                bool forced = false, isPublic, isField;
-                Type effectiveType;
-
-                if (member is PropertyInfo property)
-                {
-                    if (isEnum) continue; // wasn't expecting any props!
-                    MemberInfo backingField = null;
-                    if (!property.CanWrite)
-                    {
-                        // roslyn automatically implemented properties, in particular for get-only properties: <{Name}>k__BackingField;
-                        var backingFieldName = $"<{property.Name}>k__BackingField";
-                        foreach (var fieldMemeber in foundList)
-                        {
-                            if ((fieldMemeber as FieldInfo != null) && fieldMemeber.Name == backingFieldName)
-                            {
-                                backingField = fieldMemeber;
-                                break;
-                            }
-                        }
-                    }
-                    effectiveType = property.PropertyType;
-                    isPublic = Helpers.GetGetMethod(property, false, false) != null;
-                    isField = false;
-                    ApplyDefaultBehaviour_AddMembers(model, family, isEnum, partialMembers, dataMemberOffset, inferTagByName, implicitMode, members, member, ref forced, isPublic, isField, ref effectiveType, ref hasConflictingEnumValue, backingField);
-                }
-                else if (member is FieldInfo field)
-                {
-                    effectiveType = field.FieldType;
-                    isPublic = field.IsPublic;
-                    isField = true;
-                    if (isEnum && !field.IsStatic)
-                    { // only care about static things on enums; WinRT has a __value instance field!
-                        continue;
-                    }
-                    ApplyDefaultBehaviour_AddMembers(model, family, isEnum, partialMembers, dataMemberOffset, inferTagByName, implicitMode, members, member, ref forced, isPublic, isField, ref effectiveType, ref hasConflictingEnumValue);
-                }
-                else if (member is MethodInfo method)
-                {
-                    if (isEnum) continue;
-                    AttributeMap[] memberAttribs = AttributeMap.Create(model, method, true);
-                    if (memberAttribs != null && memberAttribs.Length > 0)
-                    {
-                        CheckForCallback(method, memberAttribs, "ProtoBuf.ProtoBeforeSerializationAttribute", ref callbacks, 0);
-                        CheckForCallback(method, memberAttribs, "ProtoBuf.ProtoAfterSerializationAttribute", ref callbacks, 1);
-                        CheckForCallback(method, memberAttribs, "ProtoBuf.ProtoBeforeDeserializationAttribute", ref callbacks, 2);
-                        CheckForCallback(method, memberAttribs, "ProtoBuf.ProtoAfterDeserializationAttribute", ref callbacks, 3);
-                        CheckForCallback(method, memberAttribs, "System.Runtime.Serialization.OnSerializingAttribute", ref callbacks, 4);
-                        CheckForCallback(method, memberAttribs, "System.Runtime.Serialization.OnSerializedAttribute", ref callbacks, 5);
-                        CheckForCallback(method, memberAttribs, "System.Runtime.Serialization.OnDeserializingAttribute", ref callbacks, 6);
-                        CheckForCallback(method, memberAttribs, "System.Runtime.Serialization.OnDeserializedAttribute", ref callbacks, 7);
-                    }
-                }
-            }
-
-            if (isEnum && enumShouldUseImplicitPassThru && !hasConflictingEnumValue)
-            {
-                EnumPassthru = true;
-                // but leave isEnum alone
-            }
-            var arr = new ProtoMemberAttribute[members.Count];
-            members.CopyTo(arr, 0);
-
-            if (inferTagByName || implicitMode != ImplicitFields.None)
-            {
-                Array.Sort(arr);
-                int nextTag = implicitFirstTag;
-                foreach (ProtoMemberAttribute normalizedAttribute in arr)
-                {
-                    if (!normalizedAttribute.TagIsPinned) // if ProtoMember etc sets a tag, we'll trust it
-                    {
-                        normalizedAttribute.Rebase(nextTag++);
-                    }
-                }
-            }
-
-            foreach (ProtoMemberAttribute normalizedAttribute in arr)
-            {
-                ValueMember vm = ApplyDefaultBehaviour(isEnum, normalizedAttribute);
-                if (vm != null)
-                {
-                    Add(vm);
-                }
-            }
-
-            if (callbacks != null)
-            {
-                SetCallbacks(Coalesce(callbacks, 0, 4), Coalesce(callbacks, 1, 5),
-                    Coalesce(callbacks, 2, 6), Coalesce(callbacks, 3, 7));
-            }
-        }
-
-        private static void ApplyDefaultBehaviour_AddMembers(TypeModel model, AttributeFamily family, bool isEnum, BasicList partialMembers, int dataMemberOffset, bool inferTagByName, ImplicitFields implicitMode, BasicList members, MemberInfo member, ref bool forced, bool isPublic, bool isField, ref Type effectiveType, ref bool hasConflictingEnumValue, MemberInfo backingMember = null)
-        {
-            switch (implicitMode)
-            {
-                case ImplicitFields.AllFields:
-                    if (isField) forced = true;
-                    break;
-                case ImplicitFields.AllPublic:
-                    if (isPublic) forced = true;
-                    break;
-            }
-
-            // we just don't like delegate types ;p
-#if COREFX || PROFILE259
-			if (effectiveType.GetTypeInfo().IsSubclassOf(typeof(Delegate))) effectiveType = null;
-#else
-            if (effectiveType.IsSubclassOf(model.MapType(typeof(Delegate)))) effectiveType = null;
-#endif
-            if (effectiveType != null)
-            {
-                ProtoMemberAttribute normalizedAttribute = NormalizeProtoMember(model, member, family, forced, isEnum, partialMembers, dataMemberOffset, inferTagByName, ref hasConflictingEnumValue, backingMember);
-                if (normalizedAttribute != null) members.Add(normalizedAttribute);
-            }
-        }
-
-        static MethodInfo Coalesce(MethodInfo[] arr, int x, int y)
-        {
-            MethodInfo mi = arr[x];
-            if (mi == null) mi = arr[y];
-            return mi;
-        }
-
-        internal static AttributeFamily GetContractFamily(RuntimeTypeModel model, Type type, AttributeMap[] attributes)
-        {
-            AttributeFamily family = AttributeFamily.None;
-
-            if (attributes == null) attributes = AttributeMap.Create(model, type, false);
-
-            for (int i = 0; i < attributes.Length; i++)
-            {
-                switch (attributes[i].AttributeType.FullName)
-                {
-                    case "ProtoBuf.ProtoContractAttribute":
-                        bool tmp = false;
-                        GetFieldBoolean(ref tmp, attributes[i], "UseProtoMembersOnly");
-                        if (tmp) return AttributeFamily.ProtoBuf;
-                        family |= AttributeFamily.ProtoBuf;
-                        break;
-                    case "System.Xml.Serialization.XmlTypeAttribute":
-                        if (!model.AutoAddProtoContractTypesOnly)
-                        {
-                            family |= AttributeFamily.XmlSerializer;
-                        }
-                        break;
-                    case "System.Runtime.Serialization.DataContractAttribute":
-                        if (!model.AutoAddProtoContractTypesOnly)
-                        {
-                            family |= AttributeFamily.DataContractSerialier;
-                        }
-                        break;
-                }
-            }
-            if (family == AttributeFamily.None)
-            { // check for obvious tuples
-                if (ResolveTupleConstructor(type, out MemberInfo[] mapping) != null)
-                {
-                    family |= AttributeFamily.AutoTuple;
-                }
-            }
-            return family;
-        }
-        internal static ConstructorInfo ResolveTupleConstructor(Type type, out MemberInfo[] mappedMembers)
-        {
-            mappedMembers = null;
-            if (type == null) throw new ArgumentNullException(nameof(type));
-#if COREFX || PROFILE259
-			TypeInfo typeInfo = type.GetTypeInfo();
-            if (typeInfo.IsAbstract) return null; // as if!
-            ConstructorInfo[] ctors = Helpers.GetConstructors(typeInfo, false);
-#else
-            if (type.IsAbstract) return null; // as if!
-            ConstructorInfo[] ctors = Helpers.GetConstructors(type, false);
-#endif
-            // need to have an interesting constructor to bother even checking this stuff
-            if (ctors.Length == 0 || (ctors.Length == 1 && ctors[0].GetParameters().Length == 0)) return null;
-
-            MemberInfo[] fieldsPropsUnfiltered = Helpers.GetInstanceFieldsAndProperties(type, true);
-            BasicList memberList = new BasicList();
-            // for most types we'll enforce that you need readonly, because that is what protobuf-net
-            // always did historically; but: if you smell so much like a Tuple that it is *in your name*,
-            // we'll let you past that
-            bool demandReadOnly = type.Name.IndexOf("Tuple", StringComparison.OrdinalIgnoreCase) < 0;
-            for (int i = 0; i < fieldsPropsUnfiltered.Length; i++)
-            {
-                if (fieldsPropsUnfiltered[i] is PropertyInfo prop)
-                {
-                    if (!prop.CanRead) return null; // no use if can't read
-                    if (demandReadOnly && prop.CanWrite && Helpers.GetSetMethod(prop, false, false) != null) return null; // don't allow a public set (need to allow non-public to handle Mono's KeyValuePair<,>)
-                    memberList.Add(prop);
-                }
-                else
-                {
-                    if (fieldsPropsUnfiltered[i] is FieldInfo field)
-                    {
-                        if (demandReadOnly && !field.IsInitOnly) return null; // all public fields must be readonly to be counted a tuple
-                        memberList.Add(field);
-                    }
-                }
-            }
-            if (memberList.Count == 0)
-            {
-                return null;
-            }
-
-            MemberInfo[] members = new MemberInfo[memberList.Count];
-            memberList.CopyTo(members, 0);
-
-            int[] mapping = new int[members.Length];
-            int found = 0;
-            ConstructorInfo result = null;
-            mappedMembers = new MemberInfo[mapping.Length];
-            for (int i = 0; i < ctors.Length; i++)
-            {
-                ParameterInfo[] parameters = ctors[i].GetParameters();
-
-                if (parameters.Length != members.Length) continue;
-
-                // reset the mappings to test
-                for (int j = 0; j < mapping.Length; j++) mapping[j] = -1;
-
-                for (int j = 0; j < parameters.Length; j++)
-                {
-                    for (int k = 0; k < members.Length; k++)
-                    {
-                        if (string.Compare(parameters[j].Name, members[k].Name, StringComparison.OrdinalIgnoreCase) != 0) continue;
-                        Type memberType = Helpers.GetMemberType(members[k]);
-                        if (memberType != parameters[j].ParameterType) continue;
-
-                        mapping[j] = k;
-                    }
-                }
-                // did we map all?
-                bool notMapped = false;
-                for (int j = 0; j < mapping.Length; j++)
-                {
-                    if (mapping[j] < 0)
-                    {
-                        notMapped = true;
-                        break;
-                    }
-                    mappedMembers[j] = members[mapping[j]];
-                }
-
-                if (notMapped) continue;
-                found++;
-                result = ctors[i];
-
-            }
-            return found == 1 ? result : null;
-        }
-
-        private static void CheckForCallback(MethodInfo method, AttributeMap[] attributes, string callbackTypeName, ref MethodInfo[] callbacks, int index)
-        {
-            for (int i = 0; i < attributes.Length; i++)
-            {
-                if (attributes[i].AttributeType.FullName == callbackTypeName)
-                {
-                    if (callbacks == null) { callbacks = new MethodInfo[8]; }
-                    else if (callbacks[index] != null)
-                    {
-#if COREFX || PROFILE259
-						Type reflected = method.DeclaringType;
-#else
-                        Type reflected = method.ReflectedType;
-#endif
-                        throw new ProtoException("Duplicate " + callbackTypeName + " callbacks on " + reflected.FullName);
-                    }
-                    callbacks[index] = method;
-                }
-            }
-        }
-        private static bool HasFamily(AttributeFamily value, AttributeFamily required)
-        {
-            return (value & required) == required;
-        }
-
-        private static ProtoMemberAttribute NormalizeProtoMember(TypeModel model, MemberInfo member, AttributeFamily family, bool forced, bool isEnum, BasicList partialMembers, int dataMemberOffset, bool inferByTagName, ref bool hasConflictingEnumValue, MemberInfo backingMember = null)
-        {
-            if (member == null || (family == AttributeFamily.None && !isEnum)) return null; // nix
-            int fieldNumber = int.MinValue, minAcceptFieldNumber = inferByTagName ? -1 : 1;
-            string name = null;
-            bool isPacked = false, ignore = false, done = false, isRequired = false, asReference = false, asReferenceHasValue = false, dynamicType = false, tagIsPinned = false, overwriteList = false;
-            DataFormat dataFormat = DataFormat.Default;
-            if (isEnum) forced = true;
-            AttributeMap[] attribs = AttributeMap.Create(model, member, true);
-            AttributeMap attrib;
-
-            if (isEnum)
-            {
-                attrib = GetAttribute(attribs, "ProtoBuf.ProtoIgnoreAttribute");
-                if (attrib != null)
-                {
-                    ignore = true;
-                }
-                else
-                {
-                    attrib = GetAttribute(attribs, "ProtoBuf.ProtoEnumAttribute");
-#if PORTABLE || CF || COREFX || PROFILE259
-					fieldNumber = Convert.ToInt32(((FieldInfo)member).GetValue(null));
-#else
-                    fieldNumber = Convert.ToInt32(((FieldInfo)member).GetRawConstantValue());
-#endif
-                    if (attrib != null)
-                    {
-                        GetFieldName(ref name, attrib, nameof(ProtoEnumAttribute.Name));
-
-                        if ((bool)Helpers.GetInstanceMethod(attrib.AttributeType
-#if COREFX || PROFILE259
-							 .GetTypeInfo()
-#endif
-                            , nameof(ProtoEnumAttribute.HasValue)).Invoke(attrib.Target, null))
-                        {
-                            if (attrib.TryGet(nameof(ProtoEnumAttribute.Value), out object tmp))
-                            {
-                                if (fieldNumber != (int)tmp)
-                                {
-                                    hasConflictingEnumValue = true;
-                                }
-                                fieldNumber = (int)tmp;
-                            }
-                        }
-                    }
-
-                }
-                done = true;
-            }
-
-            if (!ignore && !done) // always consider ProtoMember 
-            {
-                attrib = GetAttribute(attribs, "ProtoBuf.ProtoMemberAttribute");
-                GetIgnore(ref ignore, attrib, attribs, "ProtoBuf.ProtoIgnoreAttribute");
-
-                if (!ignore && attrib != null)
-                {
-                    GetFieldNumber(ref fieldNumber, attrib, "Tag");
-                    GetFieldName(ref name, attrib, "Name");
-                    GetFieldBoolean(ref isRequired, attrib, "IsRequired");
-                    GetFieldBoolean(ref isPacked, attrib, "IsPacked");
-                    GetFieldBoolean(ref overwriteList, attrib, "OverwriteList");
-                    GetDataFormat(ref dataFormat, attrib, "DataFormat");
-                    GetFieldBoolean(ref asReferenceHasValue, attrib, "AsReferenceHasValue", false);
-
-                    if (asReferenceHasValue)
-                    {
-                        asReferenceHasValue = GetFieldBoolean(ref asReference, attrib, "AsReference", true);
-                    }
-                    GetFieldBoolean(ref dynamicType, attrib, "DynamicType");
-                    done = tagIsPinned = fieldNumber > 0; // note minAcceptFieldNumber only applies to non-proto
-                }
-
-                if (!done && partialMembers != null)
-                {
-                    foreach (AttributeMap ppma in partialMembers)
-                    {
-                        if (ppma.TryGet("MemberName", out object tmp) && (string)tmp == member.Name)
-                        {
-                            GetFieldNumber(ref fieldNumber, ppma, "Tag");
-                            GetFieldName(ref name, ppma, "Name");
-                            GetFieldBoolean(ref isRequired, ppma, "IsRequired");
-                            GetFieldBoolean(ref isPacked, ppma, "IsPacked");
-                            GetFieldBoolean(ref overwriteList, attrib, "OverwriteList");
-                            GetDataFormat(ref dataFormat, ppma, "DataFormat");
-                            GetFieldBoolean(ref asReferenceHasValue, attrib, "AsReferenceHasValue", false);
-
-                            if (asReferenceHasValue)
-                            {
-                                asReferenceHasValue = GetFieldBoolean(ref asReference, ppma, "AsReference", true);
-                            }
-                            GetFieldBoolean(ref dynamicType, ppma, "DynamicType");
-                            if (done = tagIsPinned = fieldNumber > 0) break; // note minAcceptFieldNumber only applies to non-proto
-                        }
-                    }
-                }
-            }
-
-            if (!ignore && !done && HasFamily(family, AttributeFamily.DataContractSerialier))
-            {
-                attrib = GetAttribute(attribs, "System.Runtime.Serialization.DataMemberAttribute");
-                if (attrib != null)
-                {
-                    GetFieldNumber(ref fieldNumber, attrib, "Order");
-                    GetFieldName(ref name, attrib, "Name");
-                    GetFieldBoolean(ref isRequired, attrib, "IsRequired");
-                    done = fieldNumber >= minAcceptFieldNumber;
-                    if (done) fieldNumber += dataMemberOffset; // dataMemberOffset only applies to DCS flags, to allow us to "bump" WCF by a notch
-                }
-            }
-            if (!ignore && !done && HasFamily(family, AttributeFamily.XmlSerializer))
-            {
-                attrib = GetAttribute(attribs, "System.Xml.Serialization.XmlElementAttribute");
-                if (attrib == null) attrib = GetAttribute(attribs, "System.Xml.Serialization.XmlArrayAttribute");
-                GetIgnore(ref ignore, attrib, attribs, "System.Xml.Serialization.XmlIgnoreAttribute");
-                if (attrib != null && !ignore)
-                {
-                    GetFieldNumber(ref fieldNumber, attrib, "Order");
-                    GetFieldName(ref name, attrib, "ElementName");
-                    done = fieldNumber >= minAcceptFieldNumber;
-                }
-            }
-            if (!ignore && !done)
-            {
-                if (GetAttribute(attribs, "System.NonSerializedAttribute") != null) ignore = true;
-            }
-            if (ignore || (fieldNumber < minAcceptFieldNumber && !forced)) return null;
-            ProtoMemberAttribute result = new ProtoMemberAttribute(fieldNumber, forced || inferByTagName)
-            {
-                AsReference = asReference,
-                AsReferenceHasValue = asReferenceHasValue,
-                DataFormat = dataFormat,
-                DynamicType = dynamicType,
-                IsPacked = isPacked,
-                OverwriteList = overwriteList,
-                IsRequired = isRequired,
-                Name = string.IsNullOrEmpty(name) ? member.Name : name,
-                Member = member,
-                BackingMember = backingMember,
-                TagIsPinned = tagIsPinned
-            };
-            return result;
-        }
-
-        private ValueMember ApplyDefaultBehaviour(bool isEnum, ProtoMemberAttribute normalizedAttribute)
-        {
-            MemberInfo member;
-            if (normalizedAttribute == null || (member = normalizedAttribute.Member) == null) return null; // nix
-
-            Type effectiveType = Helpers.GetMemberType(member);
-
-
-            Type itemType = null;
-            Type defaultType = null;
-
-            // check for list types
-            ResolveListTypes(model, effectiveType, ref itemType, ref defaultType);
-            bool ignoreListHandling = false;
-            // but take it back if it is explicitly excluded
-            if (itemType != null)
-            { // looks like a list, but double check for IgnoreListHandling
-                int idx = model.FindOrAddAuto(effectiveType, false, true, false);
-                if (idx >= 0 && (ignoreListHandling = model[effectiveType].IgnoreListHandling))
-                {
-                    itemType = null;
-                    defaultType = null;
-                }
-            }
-            AttributeMap[] attribs = AttributeMap.Create(model, member, true);
-            AttributeMap attrib;
-
-            object defaultValue = null;
-            // implicit zero default
-            if (model.UseImplicitZeroDefaults)
-            {
-                switch (Helpers.GetTypeCode(effectiveType))
-                {
-                    case ProtoTypeCode.Boolean: defaultValue = false; break;
-                    case ProtoTypeCode.Decimal: defaultValue = (decimal)0; break;
-                    case ProtoTypeCode.Single: defaultValue = (float)0; break;
-                    case ProtoTypeCode.Double: defaultValue = (double)0; break;
-                    case ProtoTypeCode.Byte: defaultValue = (byte)0; break;
-                    case ProtoTypeCode.Char: defaultValue = (char)0; break;
-                    case ProtoTypeCode.Int16: defaultValue = (short)0; break;
-                    case ProtoTypeCode.Int32: defaultValue = (int)0; break;
-                    case ProtoTypeCode.Int64: defaultValue = (long)0; break;
-                    case ProtoTypeCode.SByte: defaultValue = (sbyte)0; break;
-                    case ProtoTypeCode.UInt16: defaultValue = (ushort)0; break;
-                    case ProtoTypeCode.UInt32: defaultValue = (uint)0; break;
-                    case ProtoTypeCode.UInt64: defaultValue = (ulong)0; break;
-                    case ProtoTypeCode.TimeSpan: defaultValue = TimeSpan.Zero; break;
-                    case ProtoTypeCode.Guid: defaultValue = Guid.Empty; break;
-                }
-            }
-            if ((attrib = GetAttribute(attribs, "System.ComponentModel.DefaultValueAttribute")) != null)
-            {
-                if (attrib.TryGet("Value", out object tmp)) defaultValue = tmp;
-            }
-            ValueMember vm = ((isEnum || normalizedAttribute.Tag > 0))
-                ? new ValueMember(model, type, normalizedAttribute.Tag, member, effectiveType, itemType, defaultType, normalizedAttribute.DataFormat, defaultValue)
-                    : null;
-            if (vm != null)
-            {
-                vm.BackingMember = normalizedAttribute.BackingMember;
-#if COREFX || PROFILE259
-				TypeInfo finalType = typeInfo;
-#else
-                Type finalType = type;
-#endif
-                PropertyInfo prop = Helpers.GetProperty(finalType, member.Name + "Specified", true);
-                MethodInfo getMethod = Helpers.GetGetMethod(prop, true, true);
-                if (getMethod == null || getMethod.IsStatic) prop = null;
-                if (prop != null)
-                {
-                    vm.SetSpecified(getMethod, Helpers.GetSetMethod(prop, true, true));
-                }
-                else
-                {
-                    MethodInfo method = Helpers.GetInstanceMethod(finalType, "ShouldSerialize" + member.Name, Helpers.EmptyTypes);
-                    if (method != null && method.ReturnType == model.MapType(typeof(bool)))
-                    {
-                        vm.SetSpecified(method, null);
-                    }
-                }
-                if (!string.IsNullOrEmpty(normalizedAttribute.Name)) vm.SetName(normalizedAttribute.Name);
-                vm.IsPacked = normalizedAttribute.IsPacked;
-                vm.IsRequired = normalizedAttribute.IsRequired;
-                vm.OverwriteList = normalizedAttribute.OverwriteList;
-                if (normalizedAttribute.AsReferenceHasValue)
-                {
-                    vm.AsReference = normalizedAttribute.AsReference;
-                }
-                vm.DynamicType = normalizedAttribute.DynamicType;
-
-                vm.IsMap = ignoreListHandling ? false : vm.ResolveMapTypes(out var _, out var _, out var _);
-                if (vm.IsMap) // is it even *allowed* to be a map?
-                {
-                    if ((attrib = GetAttribute(attribs, "ProtoBuf.ProtoMapAttribute")) != null)
-                    {
-                        if (attrib.TryGet(nameof(ProtoMapAttribute.DisableMap), out object tmp) && (bool)tmp)
-                        {
-                            vm.IsMap = false;
-                        }
-                        else
-                        {
-                            if (attrib.TryGet(nameof(ProtoMapAttribute.KeyFormat), out tmp)) vm.MapKeyFormat = (DataFormat)tmp;
-                            if (attrib.TryGet(nameof(ProtoMapAttribute.ValueFormat), out tmp)) vm.MapValueFormat = (DataFormat)tmp;
-                        }
-                    }
-                }
-
-            }
-            return vm;
-        }
-
-        private static void GetDataFormat(ref DataFormat value, AttributeMap attrib, string memberName)
-        {
-            if ((attrib == null) || (value != DataFormat.Default)) return;
-            if (attrib.TryGet(memberName, out object obj) && obj != null) value = (DataFormat)obj;
-        }
-
-        private static void GetIgnore(ref bool ignore, AttributeMap attrib, AttributeMap[] attribs, string fullName)
-        {
-            if (ignore || attrib == null) return;
-            ignore = GetAttribute(attribs, fullName) != null;
-            return;
-        }
-
-        private static void GetFieldBoolean(ref bool value, AttributeMap attrib, string memberName)
-        {
-            GetFieldBoolean(ref value, attrib, memberName, true);
-        }
-        private static bool GetFieldBoolean(ref bool value, AttributeMap attrib, string memberName, bool publicOnly)
-        {
-            if (attrib == null) return false;
-            if (value) return true;
-            if (attrib.TryGet(memberName, publicOnly, out object obj) && obj != null)
-            {
-                value = (bool)obj;
-                return true;
-            }
-            return false;
-        }
-
-        private static void GetFieldNumber(ref int value, AttributeMap attrib, string memberName)
-        {
-            if (attrib == null || value > 0) return;
-            if (attrib.TryGet(memberName, out object obj) && obj != null) value = (int)obj;
-        }
-
-        private static void GetFieldName(ref string name, AttributeMap attrib, string memberName)
-        {
-            if (attrib == null || !string.IsNullOrEmpty(name)) return;
-            if (attrib.TryGet(memberName, out object obj) && obj != null) name = (string)obj;
-        }
-
-        private static AttributeMap GetAttribute(AttributeMap[] attribs, string fullName)
-        {
-            for (int i = 0; i < attribs.Length; i++)
-            {
-                AttributeMap attrib = attribs[i];
-                if (attrib != null && attrib.AttributeType.FullName == fullName) return attrib;
-            }
-            return null;
-        }
-
-        /// <summary>
-        /// Adds a member (by name) to the MetaType
-        /// </summary>        
-        public MetaType Add(int fieldNumber, string memberName)
-        {
-            AddField(fieldNumber, memberName, null, null, null);
-            return this;
-        }
-
-        /// <summary>
-        /// Adds a member (by name) to the MetaType, returning the ValueMember rather than the fluent API.
-        /// This is otherwise identical to Add.
-        /// </summary>
-        public ValueMember AddField(int fieldNumber, string memberName)
-        {
-            return AddField(fieldNumber, memberName, null, null, null);
-        }
-
-        /// <summary>
-        /// Gets or sets whether the type should use a parameterless constructor (the default),
-        /// or whether the type should skip the constructor completely. This option is not supported
-        /// on compact-framework.
-        /// </summary>
-        public bool UseConstructor
-        { // negated to have defaults as flat zero
-            get { return !HasFlag(OPTIONS_SkipConstructor); }
-            set { SetFlag(OPTIONS_SkipConstructor, !value, true); }
-        }
-
-        /// <summary>
-        /// The concrete type to create when a new instance of this type is needed; this may be useful when dealing
-        /// with dynamic proxies, or with interface-based APIs
-        /// </summary>
-        public Type ConstructType
-        {
-            get { return constructType; }
-            set
-            {
-                ThrowIfFrozen();
-                constructType = value;
-            }
-        }
-
-        private Type constructType;
-        /// <summary>
-        /// Adds a member (by name) to the MetaType
-        /// </summary>     
-        public MetaType Add(string memberName)
-        {
-            Add(GetNextFieldNumber(), memberName);
-            return this;
-        }
-
-        Type surrogate;
-        /// <summary>
-        /// Performs serialization of this type via a surrogate; all
-        /// other serialization options are ignored and handled
-        /// by the surrogate's configuration.
-        /// </summary>
-        public void SetSurrogate(Type surrogateType)
-        {
-            if (surrogateType == type) surrogateType = null;
-            if (surrogateType != null)
-            {
-                // note that BuildSerializer checks the **CURRENT TYPE** is OK to be surrogated
-                if (surrogateType != null && Helpers.IsAssignableFrom(model.MapType(typeof(IEnumerable)), surrogateType))
-                {
-                    throw new ArgumentException("Repeated data (a list, collection, etc) has inbuilt behaviour and cannot be used as a surrogate");
-                }
-            }
-            ThrowIfFrozen();
-            this.surrogate = surrogateType;
-            // no point in offering chaining; no options are respected
-        }
-
-        internal MetaType GetSurrogateOrSelf()
-        {
-            if (surrogate != null) return model[surrogate];
-            return this;
-        }
-
-        internal MetaType GetSurrogateOrBaseOrSelf(bool deep)
-        {
-            if (surrogate != null) return model[surrogate];
-            MetaType snapshot = this.baseType;
-            if (snapshot != null)
-            {
-                if (deep)
-                {
-                    MetaType tmp;
-                    do
-                    {
-                        tmp = snapshot;
-                        snapshot = snapshot.baseType;
-                    } while (snapshot != null);
-                    return tmp;
-                }
-                return snapshot;
-            }
-            return this;
-        }
-
-        private int GetNextFieldNumber()
-        {
-            int maxField = 0;
-            foreach (ValueMember member in fields)
-            {
-                if (member.FieldNumber > maxField) maxField = member.FieldNumber;
-            }
-            if (subTypes != null)
-            {
-                foreach (SubType subType in subTypes)
-                {
-                    if (subType.FieldNumber > maxField) maxField = subType.FieldNumber;
-                }
-            }
-            return maxField + 1;
-        }
-
-        /// <summary>
-        /// Adds a set of members (by name) to the MetaType
-        /// </summary>     
-        public MetaType Add(params string[] memberNames)
-        {
-            if (memberNames == null) throw new ArgumentNullException("memberNames");
-            int next = GetNextFieldNumber();
-            for (int i = 0; i < memberNames.Length; i++)
-            {
-                Add(next++, memberNames[i]);
-            }
-            return this;
-        }
-
-        /// <summary>
-        /// Adds a member (by name) to the MetaType
-        /// </summary>        
-        public MetaType Add(int fieldNumber, string memberName, object defaultValue)
-        {
-            AddField(fieldNumber, memberName, null, null, defaultValue);
-            return this;
-        }
-
-        /// <summary>
-        /// Adds a member (by name) to the MetaType, including an itemType and defaultType for representing lists
-        /// </summary>
-        public MetaType Add(int fieldNumber, string memberName, Type itemType, Type defaultType)
-        {
-            AddField(fieldNumber, memberName, itemType, defaultType, null);
-            return this;
-        }
-
-        /// <summary>
-        /// Adds a member (by name) to the MetaType, including an itemType and defaultType for representing lists, returning the ValueMember rather than the fluent API.
-        /// This is otherwise identical to Add.
-        /// </summary>
-        public ValueMember AddField(int fieldNumber, string memberName, Type itemType, Type defaultType)
-        {
-            return AddField(fieldNumber, memberName, itemType, defaultType, null);
-        }
-
-        private ValueMember AddField(int fieldNumber, string memberName, Type itemType, Type defaultType, object defaultValue)
-        {
-            MemberInfo mi = null;
-#if PROFILE259
-			mi = Helpers.IsEnum(type) ? type.GetTypeInfo().GetDeclaredField(memberName) : Helpers.GetInstanceMember(type.GetTypeInfo(), memberName);
-
-#else
-            MemberInfo[] members = type.GetMember(memberName, Helpers.IsEnum(type) ? BindingFlags.Static | BindingFlags.Public : BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
-            if (members != null && members.Length == 1) mi = members[0];
-#endif
-            if (mi == null) throw new ArgumentException("Unable to determine member: " + memberName, "memberName");
-
-            Type miType;
-            PropertyInfo pi = null;
-            FieldInfo fi = null;
-#if PORTABLE || COREFX || PROFILE259
-			pi = mi as PropertyInfo;
-            if (pi == null)
-            {
-                fi = mi as FieldInfo;
-                if (fi == null)
-                {
-                    throw new NotSupportedException(mi.GetType().Name);
-                }
-                else
-                {
-                    miType = fi.FieldType;
-                }
-            }
-            else
-            {
-                miType = pi.PropertyType;
-            }
-#else
-            switch (mi.MemberType)
-            {
-                case MemberTypes.Field:
-                    fi = (FieldInfo)mi;
-                    miType = fi.FieldType; break;
-                case MemberTypes.Property:
-                    pi = (PropertyInfo)mi;
-                    miType = pi.PropertyType; break;
-                default:
-                    throw new NotSupportedException(mi.MemberType.ToString());
-            }
-#endif
-            ResolveListTypes(model, miType, ref itemType, ref defaultType);
-
-            MemberInfo backingField = null;
-            if (pi?.CanWrite == false)
-            {
-                string name = $"<{((PropertyInfo)mi).Name}>k__BackingField";
-#if PROFILE259
-				var backingMembers = type.GetTypeInfo().DeclaredMembers;
-	            var memberInfos = backingMembers as MemberInfo[] ?? backingMembers.ToArray();
-	            if (memberInfos.Count() == 1)
-	            {
-		            MemberInfo first = memberInfos.FirstOrDefault();
-		            if (first is FieldInfo)
-		            {
-			            backingField = first;
-		            }
-	            }
-#else
-                var backingMembers = type.GetMember($"<{((PropertyInfo)mi).Name}>k__BackingField", Helpers.IsEnum(type) ? BindingFlags.Static | BindingFlags.Public : BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
-                if (backingMembers != null && backingMembers.Length == 1 && (backingMembers[0] as FieldInfo) != null)
-                    backingField = backingMembers[0];
-#endif
-            }
-            ValueMember newField = new ValueMember(model, type, fieldNumber, backingField ?? mi, miType, itemType, defaultType, DataFormat.Default, defaultValue);
-            if (backingField != null)
-                newField.SetName(mi.Name);
-            Add(newField);
-            return newField;
-        }
-
-        internal static void ResolveListTypes(TypeModel model, Type type, ref Type itemType, ref Type defaultType)
-        {
-            if (type == null) return;
-            // handle arrays
-            if (type.IsArray)
-            {
-                if (type.GetArrayRank() != 1)
-                {
-                    throw new NotSupportedException("Multi-dimensional arrays are not supported");
-                }
-                itemType = type.GetElementType();
-                if (itemType == model.MapType(typeof(byte)))
-                {
-                    defaultType = itemType = null;
-                }
-                else
-                {
-                    defaultType = type;
-                }
-            }
-            // handle lists
-            if (itemType == null) { itemType = TypeModel.GetListItemType(model, type); }
-
-            // check for nested data (not allowed)
-            if (itemType != null)
-            {
-                Type nestedItemType = null, nestedDefaultType = null;
-                ResolveListTypes(model, itemType, ref nestedItemType, ref nestedDefaultType);
-                if (nestedItemType != null)
-                {
-                    throw TypeModel.CreateNestedListsNotSupported(type);
-                }
-            }
-
-            if (itemType != null && defaultType == null)
-            {
-#if COREFX || PROFILE259
-				TypeInfo typeInfo = type.GetTypeInfo();
-                if (typeInfo.IsClass && !typeInfo.IsAbstract && Helpers.GetConstructor(typeInfo, Helpers.EmptyTypes, true) != null)
-#else
-                if (type.IsClass && !type.IsAbstract && Helpers.GetConstructor(type, Helpers.EmptyTypes, true) != null)
-#endif
-                {
-                    defaultType = type;
-                }
-                if (defaultType == null)
-                {
-#if COREFX || PROFILE259
-					if (typeInfo.IsInterface)
-#else
-                    if (type.IsInterface)
-#endif
-                    {
-
-                        Type[] genArgs;
-#if COREFX || PROFILE259
-						if (typeInfo.IsGenericType && type.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IDictionary<,>)
-                            && itemType == typeof(System.Collections.Generic.KeyValuePair<,>).MakeGenericType(genArgs = typeInfo.GenericTypeArguments))
-#else
-                        if (type.IsGenericType && type.GetGenericTypeDefinition() == model.MapType(typeof(System.Collections.Generic.IDictionary<,>))
-                            && itemType == model.MapType(typeof(System.Collections.Generic.KeyValuePair<,>)).MakeGenericType(genArgs = type.GetGenericArguments()))
-#endif
-                        {
-                            defaultType = model.MapType(typeof(System.Collections.Generic.Dictionary<,>)).MakeGenericType(genArgs);
-                        }
-                        else
-                        {
-                            defaultType = model.MapType(typeof(System.Collections.Generic.List<>)).MakeGenericType(itemType);
-                        }
-                    }
-                }
-                // verify that the default type is appropriate
-                if (defaultType != null && !Helpers.IsAssignableFrom(type, defaultType)) { defaultType = null; }
-            }
-        }
-
-        private void Add(ValueMember member)
-        {
-            int opaqueToken = 0;
-            try
-            {
-                model.TakeLock(ref opaqueToken);
-                ThrowIfFrozen();
-                fields.Add(member);
-            }
-            finally
-            {
-                model.ReleaseLock(opaqueToken);
-            }
-        }
-
-        /// <summary>
-        /// Returns the ValueMember that matchs a given field number, or null if not found
-        /// </summary>
-        public ValueMember this[int fieldNumber]
-        {
-            get
-            {
-                foreach (ValueMember member in fields)
-                {
-                    if (member.FieldNumber == fieldNumber) return member;
-                }
-                return null;
-            }
-        }
-        /// <summary>
-        /// Returns the ValueMember that matchs a given member (property/field), or null if not found
-        /// </summary>
-        public ValueMember this[MemberInfo member]
-        {
-            get
-            {
-                if (member == null) return null;
-                foreach (ValueMember x in fields)
-                {
-                    if (x.Member == member || x.BackingMember == member) return x;
-                }
-                return null;
-            }
-        }
-        private readonly BasicList fields = new BasicList();
-
-        /// <summary>
-        /// Returns the ValueMember instances associated with this type
-        /// </summary>
-        public ValueMember[] GetFields()
-        {
-            ValueMember[] arr = new ValueMember[fields.Count];
-            fields.CopyTo(arr, 0);
-            Array.Sort(arr, ValueMember.Comparer.Default);
-            return arr;
-        }
-
-        /// <summary>
-        /// Returns the SubType instances associated with this type
-        /// </summary>
-        public SubType[] GetSubtypes()
-        {
-            if (subTypes == null || subTypes.Count == 0) return new SubType[0];
-            SubType[] arr = new SubType[subTypes.Count];
-            subTypes.CopyTo(arr, 0);
-            Array.Sort(arr, SubType.Comparer.Default);
-            return arr;
-        }
-
-        internal IEnumerable<Type> GetAllGenericArguments()
-        {
-            return GetAllGenericArguments(type);
-        }
-
-        private static IEnumerable<Type> GetAllGenericArguments(Type type)
-        {
-
-#if PROFILE259
-	        var genericArguments = type.GetGenericTypeDefinition().GenericTypeArguments;
-#else
-            var genericArguments = type.GetGenericArguments();
-#endif
-            foreach (var arg in genericArguments)
-            {
-                yield return arg;
-                foreach (var inner in GetAllGenericArguments(arg))
-                {
-                    yield return inner;
-                }
-            }
-        }
-
-#if FEAT_COMPILER
-        /// <summary>
-        /// Compiles the serializer for this type; this is *not* a full
-        /// standalone compile, but can significantly boost performance
-        /// while allowing additional types to be added.
-        /// </summary>
-        /// <remarks>An in-place compile can access non-public types / members</remarks>
-        public void CompileInPlace()
-        {
-            serializer = CompiledSerializer.Wrap(Serializer, model);
-        }
-#endif
-
-        internal bool IsDefined(int fieldNumber)
-        {
-            foreach (ValueMember field in fields)
-            {
-                if (field.FieldNumber == fieldNumber) return true;
-            }
-            return false;
-        }
-
-        internal int GetKey(bool demand, bool getBaseKey)
-        {
-            return model.GetKey(type, demand, getBaseKey);
-        }
-
-        internal EnumSerializer.EnumPair[] GetEnumMap()
-        {
-            if (HasFlag(OPTIONS_EnumPassThru)) return null;
-            EnumSerializer.EnumPair[] result = new EnumSerializer.EnumPair[fields.Count];
-            for (int i = 0; i < result.Length; i++)
-            {
-                ValueMember member = (ValueMember)fields[i];
-                int wireValue = member.FieldNumber;
-                object value = member.GetRawEnumValue();
-                result[i] = new EnumSerializer.EnumPair(wireValue, value, member.MemberType);
-            }
-            return result;
-        }
-
-        /// <summary>
-        /// Gets or sets a value indicating that an enum should be treated directly as an int/short/etc, rather
-        /// than enforcing .proto enum rules. This is useful *in particul* for [Flags] enums.
-        /// </summary>
-        public bool EnumPassthru
-        {
-            get { return HasFlag(OPTIONS_EnumPassThru); }
-            set { SetFlag(OPTIONS_EnumPassThru, value, true); }
-        }
-
-        /// <summary>
-        /// Gets or sets a value indicating that this type should NOT be treated as a list, even if it has
-        /// familiar list-like characteristics (enumerable, add, etc)
-        /// </summary>
-        public bool IgnoreListHandling
-        {
-            get { return HasFlag(OPTIONS_IgnoreListHandling); }
-            set { SetFlag(OPTIONS_IgnoreListHandling, value, true); }
-        }
-
-        internal bool Pending
-        {
-            get { return HasFlag(OPTIONS_Pending); }
-            set { SetFlag(OPTIONS_Pending, value, false); }
-        }
-
-        private const ushort
-            OPTIONS_Pending = 1,
-            OPTIONS_EnumPassThru = 2,
-            OPTIONS_Frozen = 4,
-            OPTIONS_PrivateOnApi = 8,
-            OPTIONS_SkipConstructor = 16,
-            OPTIONS_AsReferenceDefault = 32,
-            OPTIONS_AutoTuple = 64,
-            OPTIONS_IgnoreListHandling = 128,
-            OPTIONS_IsGroup = 256;
-
-        private volatile ushort flags;
-        private bool HasFlag(ushort flag) { return (flags & flag) == flag; }
-        private void SetFlag(ushort flag, bool value, bool throwIfFrozen)
-        {
-            if (throwIfFrozen && HasFlag(flag) != value)
-            {
-                ThrowIfFrozen();
-            }
-            if (value)
-                flags |= flag;
-            else
-                flags = (ushort)(flags & ~flag);
-        }
-
-        internal static MetaType GetRootType(MetaType source)
-        {
-            while (source.serializer != null)
-            {
-                MetaType tmp = source.baseType;
-                if (tmp == null) return source;
-                source = tmp; // else loop until we reach something that isn't generated, or is the root
-            }
-
-            // now we get into uncertain territory
-            RuntimeTypeModel model = source.model;
-            int opaqueToken = 0;
-            try
-            {
-                model.TakeLock(ref opaqueToken);
-
-                MetaType tmp;
-                while ((tmp = source.baseType) != null) source = tmp;
-                return source;
-
-            }
-            finally
-            {
-                model.ReleaseLock(opaqueToken);
-            }
-        }
-
-        internal bool IsPrepared()
-        {
-#if FEAT_COMPILER
-            return serializer is CompiledSerializer;
-#else
-            return false;
-#endif
-        }
-
-        internal IEnumerable Fields => this.fields;
-
-        internal static StringBuilder NewLine(StringBuilder builder, int indent)
-        {
-            return Helpers.AppendLine(builder).Append(' ', indent * 3);
-        }
-
-        internal bool IsAutoTuple => HasFlag(OPTIONS_AutoTuple);
-
-        /// <summary>
-        /// Indicates whether this type should always be treated as a "group" (rather than a string-prefixed sub-message)
-        /// </summary>
-        public bool IsGroup
-        {
-            get { return HasFlag(OPTIONS_IsGroup); }
-            set { SetFlag(OPTIONS_IsGroup, value, true); }
-        }
-
-        internal void WriteSchema(StringBuilder builder, int indent, ref RuntimeTypeModel.CommonImports imports, ProtoSyntax syntax)
-        {
-            if (surrogate != null) return; // nothing to write
-
-            ValueMember[] fieldsArr = new ValueMember[fields.Count];
-            fields.CopyTo(fieldsArr, 0);
-            Array.Sort(fieldsArr, ValueMember.Comparer.Default);
-
-            if (IsList)
-            {
-                string itemTypeName = model.GetSchemaTypeName(TypeModel.GetListItemType(model, type), DataFormat.Default, false, false, ref imports);
-                NewLine(builder, indent).Append("message ").Append(GetSchemaTypeName()).Append(" {");
-                NewLine(builder, indent + 1).Append("repeated ").Append(itemTypeName).Append(" items = 1;");
-                NewLine(builder, indent).Append('}');
-            }
-            else if (IsAutoTuple)
-            { // key-value-pair etc
-
-                if (ResolveTupleConstructor(type, out MemberInfo[] mapping) != null)
-                {
-                    NewLine(builder, indent).Append("message ").Append(GetSchemaTypeName()).Append(" {");
-                    for (int i = 0; i < mapping.Length; i++)
-                    {
-                        Type effectiveType;
-                        if (mapping[i] is PropertyInfo property)
-                        {
-                            effectiveType = property.PropertyType;
-                        }
-                        else if (mapping[i] is FieldInfo field)
-                        {
-                            effectiveType = field.FieldType;
-                        }
-                        else
-                        {
-                            throw new NotSupportedException("Unknown member type: " + mapping[i].GetType().Name);
-                        }
-                        NewLine(builder, indent + 1).Append(syntax == ProtoSyntax.Proto2 ? "optional " : "").Append(model.GetSchemaTypeName(effectiveType, DataFormat.Default, false, false, ref imports).Replace('.', '_'))
-                            .Append(' ').Append(mapping[i].Name).Append(" = ").Append(i + 1).Append(';');
-                    }
-                    NewLine(builder, indent).Append('}');
-                }
-            }
-            else if (Helpers.IsEnum(type))
-            {
-                NewLine(builder, indent).Append("enum ").Append(GetSchemaTypeName()).Append(" {");
-                if (fieldsArr.Length == 0 && EnumPassthru)
-                {
-                    if (type
-#if COREFX || PROFILE259
-					.GetTypeInfo()
-#endif
-.IsDefined(model.MapType(typeof(FlagsAttribute)), false))
-                    {
-                        NewLine(builder, indent + 1).Append("// this is a composite/flags enumeration");
-                    }
-                    else
-                    {
-                        NewLine(builder, indent + 1).Append("// this enumeration will be passed as a raw value");
-                    }
-                    foreach (FieldInfo field in
-#if PROFILE259
-						type.GetRuntimeFields()
-#else
-                        type.GetFields()
-#endif
-
-                        )
-                    {
-                        if (field.IsStatic && field.IsLiteral)
-                        {
-                            object enumVal;
-#if PORTABLE || CF || NETSTANDARD1_3 || NETSTANDARD1_4 || PROFILE259 || UAP
-							enumVal = Convert.ChangeType(field.GetValue(null), Enum.GetUnderlyingType(field.FieldType), System.Globalization.CultureInfo.InvariantCulture);
-#else
-                            enumVal = field.GetRawConstantValue();
-#endif
-                            NewLine(builder, indent + 1).Append(field.Name).Append(" = ").Append(enumVal).Append(";");
-                        }
-                    }
-
-                }
-                else
-                {
-                    Dictionary<int, int> countByField = new Dictionary<int, int>(fieldsArr.Length);
-                    bool needsAlias = false;
-                    foreach (var field in fieldsArr)
-                    {
-                        if (countByField.ContainsKey(field.FieldNumber))
-                        {  // no point actually counting; that's enough to know we have a problem
-                            needsAlias = true;
-                            break;
-                        }
-                        countByField.Add(field.FieldNumber, 1);
-                    }
-                    if (needsAlias)
-                    {   // duplicated value requires allow_alias
-                        NewLine(builder, indent + 1).Append("option allow_alias = true;");
-                    }
-
-                    bool haveWrittenZero = false;
-                    // write zero values **first**
-                    foreach (ValueMember member in fieldsArr)
-                    {
-                        if (member.FieldNumber == 0)
-                        {
-                            NewLine(builder, indent + 1).Append(member.Name).Append(" = ").Append(member.FieldNumber).Append(';');
-                            haveWrittenZero = true;
-                        }
-                    }
-                    if (syntax == ProtoSyntax.Proto3 && !haveWrittenZero)
-                    {
-                        NewLine(builder, indent + 1).Append("ZERO = 0; // proto3 requires a zero value as the first item (it can be named anything)");
-                    }
-                    // note array is already sorted, so zero would already be first
-                    foreach (ValueMember member in fieldsArr)
-                    {
-                        if (member.FieldNumber == 0) continue;
-                        NewLine(builder, indent + 1).Append(member.Name).Append(" = ").Append(member.FieldNumber).Append(';');
-                    }
-                }
-                NewLine(builder, indent).Append('}');
-            }
-            else
-            {
-                NewLine(builder, indent).Append("message ").Append(GetSchemaTypeName()).Append(" {");
-                foreach (ValueMember member in fieldsArr)
-                {
-                    string schemaTypeName;
-                    bool hasOption = false;
-                    if (member.IsMap)
-                    {
-                        member.ResolveMapTypes(out var _, out var keyType, out var valueType);
-
-                        var keyTypeName = model.GetSchemaTypeName(keyType, member.MapKeyFormat, false, false, ref imports);
-                        schemaTypeName = model.GetSchemaTypeName(valueType, member.MapKeyFormat, member.AsReference, member.DynamicType, ref imports);
-                        NewLine(builder, indent + 1).Append("map<").Append(keyTypeName).Append(",").Append(schemaTypeName).Append("> ")
-                            .Append(member.Name).Append(" = ").Append(member.FieldNumber).Append(";");
-                    }
-                    else
-                    {
-                        string ordinality = member.ItemType != null ? "repeated " : (syntax == ProtoSyntax.Proto2 ? (member.IsRequired ? "required " : "optional ") : "");
-                        NewLine(builder, indent + 1).Append(ordinality);
-                        if (member.DataFormat == DataFormat.Group) builder.Append("group ");
-                        schemaTypeName = member.GetSchemaTypeName(true, ref imports);
-                        builder.Append(schemaTypeName).Append(" ")
-                             .Append(member.Name).Append(" = ").Append(member.FieldNumber);
-
-                        if (syntax == ProtoSyntax.Proto2 && member.DefaultValue != null && member.IsRequired == false)
-                        {
-                            if (member.DefaultValue is string)
-                            {
-                                AddOption(builder, ref hasOption).Append("default = \"").Append(member.DefaultValue).Append("\"");
-                            }
-                            else if (member.DefaultValue is TimeSpan)
-                            {
-                                // ignore
-                            }
-                            else if (member.DefaultValue is bool)
-                            {   // need to be lower case (issue 304)
-                                AddOption(builder, ref hasOption).Append((bool)member.DefaultValue ? "default = true" : "default = false");
-                            }
-                            else
-                            {
-                                AddOption(builder, ref hasOption).Append("default = ").Append(member.DefaultValue);
-                            }
-                        }
-                        if (CanPack(member.ItemType))
-                        {
-                            if (syntax == ProtoSyntax.Proto2)
-                            {
-                                if (member.IsPacked) AddOption(builder, ref hasOption).Append("packed = true"); // disabled by default
-                            }
-                            else
-                            {
-                                if (!member.IsPacked) AddOption(builder, ref hasOption).Append("packed = false"); // enabled by default
-                            }
-                        }
-                        if (member.AsReference)
-                        {
-                            imports |= RuntimeTypeModel.CommonImports.Protogen;
-                            AddOption(builder, ref hasOption).Append("(.protobuf_net.fieldopt).asRef = true");
-                        }
-                        if (member.DynamicType)
-                        {
-                            imports |= RuntimeTypeModel.CommonImports.Protogen;
-                            AddOption(builder, ref hasOption).Append("(.protobuf_net.fieldopt).dynamicType = true");
-                        }
-                        CloseOption(builder, ref hasOption).Append(';');
-                        if (syntax != ProtoSyntax.Proto2 && member.DefaultValue != null && !member.IsRequired)
-                        {
-                            if (IsImplicitDefault(member.DefaultValue))
-                            {
-                                // don't emit; we're good
-                            }
-                            else
-                            {
-                                builder.Append(" // default value could not be applied: ").Append(member.DefaultValue);
-                            }
-                        }
-                    }
-                    if (schemaTypeName == ".bcl.NetObjectProxy" && member.AsReference && !member.DynamicType) // we know what it is; tell the user
-                    {
-                        builder.Append(" // reference-tracked ").Append(member.GetSchemaTypeName(false, ref imports));
-                    }
-                }
-                if (subTypes != null && subTypes.Count != 0)
-                {
-                    SubType[] subTypeArr = new SubType[subTypes.Count];
-                    subTypes.CopyTo(subTypeArr, 0);
-                    Array.Sort(subTypeArr, SubType.Comparer.Default);
-                    string[] fieldNames = new string[subTypeArr.Length];
-                    for(int i = 0; i < subTypeArr.Length;i++)
-                        fieldNames[i] = subTypeArr[i].DerivedType.GetSchemaTypeName();
-
-                    string fieldName = "subtype";
-                    while (Array.IndexOf(fieldNames, fieldName) >= 0)
-                        fieldName = "_" + fieldName;
-
-                    NewLine(builder, indent + 1).Append("oneof ").Append(fieldName).Append(" {");
-                    for(int i = 0; i < subTypeArr.Length; i++)
-                    {
-                        var subTypeName = fieldNames[i];
-                        NewLine(builder, indent + 2).Append(subTypeName)
-                               .Append(" ").Append(subTypeName).Append(" = ").Append(subTypeArr[i].FieldNumber).Append(';');
-                    }
-                    NewLine(builder, indent + 1).Append("}");
-                }
-                NewLine(builder, indent).Append('}');
-            }
-        }
-
-        private static StringBuilder AddOption(StringBuilder builder, ref bool hasOption)
-        {
-            if (hasOption)
-                return builder.Append(", ");
-            hasOption = true;
-            return builder.Append(" [");
-        }
-
-        private static StringBuilder CloseOption(StringBuilder builder, ref bool hasOption)
-        {
-            if (hasOption)
-            {
-                hasOption = false;
-                return builder.Append("]");
-            }
-            return builder;
-        }
-
-        private static bool IsImplicitDefault(object value)
-        {
-            try
-            {
-                if (value == null) return false;
-                switch (Helpers.GetTypeCode(value.GetType()))
-                {
-                    case ProtoTypeCode.Boolean: return ((bool)value) == false;
-                    case ProtoTypeCode.Byte: return ((byte)value) == (byte)0;
-                    case ProtoTypeCode.Char: return ((char)value) == (char)0;
-                    case ProtoTypeCode.DateTime: return ((DateTime)value) == default;
-                    case ProtoTypeCode.Decimal: return ((decimal)value) == 0M;
-                    case ProtoTypeCode.Double: return ((double)value) == (double)0;
-                    case ProtoTypeCode.Int16: return ((short)value) == (short)0;
-                    case ProtoTypeCode.Int32: return ((int)value) == (int)0;
-                    case ProtoTypeCode.Int64: return ((long)value) == (long)0;
-                    case ProtoTypeCode.SByte: return ((sbyte)value) == (sbyte)0;
-                    case ProtoTypeCode.Single: return ((float)value) == (float)0;
-                    case ProtoTypeCode.String: return ((string)value) == "";
-                    case ProtoTypeCode.TimeSpan: return ((TimeSpan)value) == TimeSpan.Zero;
-                    case ProtoTypeCode.UInt16: return ((ushort)value) == (ushort)0;
-                    case ProtoTypeCode.UInt32: return ((uint)value) == (uint)0;
-                    case ProtoTypeCode.UInt64: return ((ulong)value) == (ulong)0;
-                }
-            }
-            catch { }
-            return false;
-        }
-
-        private static bool CanPack(Type type)
-        {
-            if (type == null) return false;
-            switch (Helpers.GetTypeCode(type))
-            {
-                case ProtoTypeCode.Boolean:
-                case ProtoTypeCode.Byte:
-                case ProtoTypeCode.Char:
-                case ProtoTypeCode.Double:
-                case ProtoTypeCode.Int16:
-                case ProtoTypeCode.Int32:
-                case ProtoTypeCode.Int64:
-                case ProtoTypeCode.SByte:
-                case ProtoTypeCode.Single:
-                case ProtoTypeCode.UInt16:
-                case ProtoTypeCode.UInt32:
-                case ProtoTypeCode.UInt64:
-                    return true;
-            }
-            return false;
-        }
-
-        /// <summary>
-        /// Apply a shift to all fields (and sub-types) on this type
-        /// </summary>
-        /// <param name="offset">The change in field number to apply</param>
-        /// <remarks>The resultant field numbers must still all be considered valid</remarks>
-#if !(NETSTANDARD1_0 || NETSTANDARD1_3 || UAP)
-        [System.ComponentModel.Browsable(false)]
-#endif
-        [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
-        public void ApplyFieldOffset(int offset)
-        {
-            if (Helpers.IsEnum(type)) throw new InvalidOperationException("Cannot apply field-offset to an enum");
-            if (offset == 0) return; // nothing to do
-            int opaqueToken = 0;
-            try
-            {
-                model.TakeLock(ref opaqueToken);
-                ThrowIfFrozen();
-
-                if (fields != null)
-                {
-                    foreach(ValueMember field in fields)
-                        AssertValidFieldNumber(field.FieldNumber + offset);
-                }
-                if (subTypes != null)
-                {
-                    foreach (SubType subType in subTypes)
-                        AssertValidFieldNumber(subType.FieldNumber + offset);
-                }
-
-                // we've checked the ranges are all OK; since we're moving everything, we can't overlap ourselves
-                // so: we can just move
-                if (fields != null)
-                {
-                    foreach (ValueMember field in fields)
-                        field.FieldNumber += offset;
-                }
-                if (subTypes != null)
-                {
-                    foreach (SubType subType in subTypes)
-                        subType.FieldNumber += offset;
-                }
-            }
-            finally
-            {
-                model.ReleaseLock(opaqueToken);
-            }
-        }
-
-        internal static void AssertValidFieldNumber(int fieldNumber)
-        {
-            if (fieldNumber < 1) throw new ArgumentOutOfRangeException(nameof(fieldNumber));
-        }
-    }
-}
-#endif

+ 0 - 17
ThirdParty/protobuf-net/Meta/ProtoSyntax.cs

@@ -1,17 +0,0 @@
-namespace ProtoBuf.Meta
-{
-    /// <summary>
-    /// Indiate the variant of the protobuf .proto DSL syntax to use
-    /// </summary>
-    public enum ProtoSyntax
-    {
-        /// <summary>
-        /// https://developers.google.com/protocol-buffers/docs/proto
-        /// </summary>
-        Proto2 = 0,
-        /// <summary>
-        /// https://developers.google.com/protocol-buffers/docs/proto3
-        /// </summary>
-        Proto3 = 1,
-    }
-}

+ 0 - 2006
ThirdParty/protobuf-net/Meta/RuntimeTypeModel.cs

@@ -1,2006 +0,0 @@
-#if !NO_RUNTIME
-using System;
-using System.Collections;
-using System.Text;
-using System.Reflection;
-#if FEAT_COMPILER
-using System.Reflection.Emit;
-#endif
-
-using ProtoBuf.Serializers;
-using System.Threading;
-using System.IO;
-using System.Diagnostics;
-using System.Runtime.CompilerServices;
-
-namespace ProtoBuf.Meta
-{
-    /// <summary>
-    /// Provides protobuf serialization support for a number of types that can be defined at runtime
-    /// </summary>
-    public sealed class RuntimeTypeModel : TypeModel
-    {
-        private ushort options;
-        private const ushort
-           OPTIONS_InferTagFromNameDefault = 1,
-           OPTIONS_IsDefaultModel = 2,
-           OPTIONS_Frozen = 4,
-           OPTIONS_AutoAddMissingTypes = 8,
-#if FEAT_COMPILER
-           OPTIONS_AutoCompile = 16,
-#endif
-           OPTIONS_UseImplicitZeroDefaults = 32,
-           OPTIONS_AllowParseableTypes = 64,
-           OPTIONS_AutoAddProtoContractTypesOnly = 128,
-           OPTIONS_IncludeDateTimeKind = 256,
-           OPTIONS_DoNotInternStrings = 512;
-
-        private bool GetOption(ushort option)
-        {
-            return (options & option) == option;
-        }
-
-        private void SetOption(ushort option, bool value)
-        {
-            if (value) options |= option;
-            else options &= (ushort)~option;
-        }
-
-        /// <summary>
-        /// Global default that
-        /// enables/disables automatic tag generation based on the existing name / order
-        /// of the defined members. See <seealso cref="ProtoContractAttribute.InferTagFromName"/>
-        /// for usage and <b>important warning</b> / explanation.
-        /// You must set the global default before attempting to serialize/deserialize any
-        /// impacted type.
-        /// </summary>
-        public bool InferTagFromNameDefault
-        {
-            get { return GetOption(OPTIONS_InferTagFromNameDefault); }
-            set { SetOption(OPTIONS_InferTagFromNameDefault, value); }
-        }
-
-        /// <summary>
-        /// Global default that determines whether types are considered serializable
-        /// if they have [DataContract] / [XmlType]. With this enabled, <b>ONLY</b>
-        /// types marked as [ProtoContract] are added automatically.
-        /// </summary>
-        public bool AutoAddProtoContractTypesOnly
-        {
-            get { return GetOption(OPTIONS_AutoAddProtoContractTypesOnly); }
-            set { SetOption(OPTIONS_AutoAddProtoContractTypesOnly, value); }
-        }
-
-        /// <summary>
-        /// Global switch that enables or disables the implicit
-        /// handling of "zero defaults"; meanning: if no other default is specified,
-        /// it assumes bools always default to false, integers to zero, etc.
-        /// 
-        /// If this is disabled, no such assumptions are made and only *explicit*
-        /// default values are processed. This is enabled by default to 
-        /// preserve similar logic to v1.
-        /// </summary>
-        public bool UseImplicitZeroDefaults
-        {
-            get { return GetOption(OPTIONS_UseImplicitZeroDefaults); }
-            set
-            {
-                if (!value && GetOption(OPTIONS_IsDefaultModel))
-                {
-                    throw new InvalidOperationException("UseImplicitZeroDefaults cannot be disabled on the default model");
-                }
-                SetOption(OPTIONS_UseImplicitZeroDefaults, value);
-            }
-        }
-
-        /// <summary>
-        /// Global switch that determines whether types with a <c>.ToString()</c> and a <c>Parse(string)</c>
-        /// should be serialized as strings.
-        /// </summary>
-        public bool AllowParseableTypes
-        {
-            get { return GetOption(OPTIONS_AllowParseableTypes); }
-            set { SetOption(OPTIONS_AllowParseableTypes, value); }
-        }
-
-        /// <summary>
-        /// Global switch that determines whether DateTime serialization should include the <c>Kind</c> of the date/time.
-        /// </summary>
-        public bool IncludeDateTimeKind
-        {
-            get { return GetOption(OPTIONS_IncludeDateTimeKind); }
-            set { SetOption(OPTIONS_IncludeDateTimeKind, value); }
-        }
-
-        /// <summary>
-        /// Global switch that determines whether a single instance of the same string should be used during deserialization.
-        /// </summary>
-        /// <remarks>Note this does not use the global .NET string interner</remarks>
-        public bool InternStrings
-        {
-            get { return !GetOption(OPTIONS_DoNotInternStrings); }
-            set { SetOption(OPTIONS_DoNotInternStrings, !value); }
-        }
-
-        /// <summary>
-        /// Should the <c>Kind</c> be included on date/time values?
-        /// </summary>
-        protected internal override bool SerializeDateTimeKind()
-        {
-            return GetOption(OPTIONS_IncludeDateTimeKind);
-        }
-
-        private sealed class Singleton
-        {
-            private Singleton() { }
-            internal static readonly RuntimeTypeModel Value = new RuntimeTypeModel(true);
-        }
-
-        /// <summary>
-        /// The default model, used to support ProtoBuf.Serializer
-        /// </summary>
-        public static RuntimeTypeModel Default => Singleton.Value;
-
-        /// <summary>
-        /// Returns a sequence of the Type instances that can be
-        /// processed by this model.
-        /// </summary>
-        public IEnumerable GetTypes() => types;
-
-        /// <summary>
-        /// Suggest a .proto definition for the given type
-        /// </summary>
-        /// <param name="type">The type to generate a .proto definition for, or <c>null</c> to generate a .proto that represents the entire model</param>
-        /// <returns>The .proto definition as a string</returns>
-        /// <param name="syntax">The .proto syntax to use</param>
-        public override string GetSchema(Type type, ProtoSyntax syntax)
-        {
-            BasicList requiredTypes = new BasicList();
-            MetaType primaryType = null;
-            bool isInbuiltType = false;
-            if (type == null)
-            { // generate for the entire model
-                foreach (MetaType meta in types)
-                {
-                    MetaType tmp = meta.GetSurrogateOrBaseOrSelf(false);
-                    if (!requiredTypes.Contains(tmp))
-                    { // ^^^ note that the type might have been added as a descendent
-                        requiredTypes.Add(tmp);
-                        CascadeDependents(requiredTypes, tmp);
-                    }
-                }
-            }
-            else
-            {
-                Type tmp = Helpers.GetUnderlyingType(type);
-                if (tmp != null) type = tmp;
-
-                WireType defaultWireType;
-                isInbuiltType = (ValueMember.TryGetCoreSerializer(this, DataFormat.Default, type, out defaultWireType, false, false, false, false) != null);
-                if (!isInbuiltType)
-                {
-                    //Agenerate just relative to the supplied type
-                    int index = FindOrAddAuto(type, false, false, false);
-                    if (index < 0) throw new ArgumentException("The type specified is not a contract-type", "type");
-
-                    // get the required types
-                    primaryType = ((MetaType)types[index]).GetSurrogateOrBaseOrSelf(false);
-                    requiredTypes.Add(primaryType);
-                    CascadeDependents(requiredTypes, primaryType);
-                }
-            }
-
-            // use the provided type's namespace for the "package"
-            StringBuilder headerBuilder = new StringBuilder();
-            string package = null;
-
-            if (!isInbuiltType)
-            {
-                IEnumerable typesForNamespace = primaryType == null ? types : requiredTypes;
-                foreach (MetaType meta in typesForNamespace)
-                {
-                    if (meta.IsList) continue;
-                    string tmp = meta.Type.Namespace;
-                    if (!string.IsNullOrEmpty(tmp))
-                    {
-                        if (tmp.StartsWith("System.")) continue;
-                        if (package == null)
-                        { // haven't seen any suggestions yet
-                            package = tmp;
-                        }
-                        else if (package == tmp)
-                        { // that's fine; a repeat of the one we already saw
-                        }
-                        else
-                        { // something else; have confliucting suggestions; abort
-                            package = null;
-                            break;
-                        }
-                    }
-                }
-            }
-            switch (syntax)
-            {
-                case ProtoSyntax.Proto2:
-                    headerBuilder.AppendLine(@"syntax = ""proto2"";");
-                    break;
-                case ProtoSyntax.Proto3:
-                    headerBuilder.AppendLine(@"syntax = ""proto3"";");
-                    break;
-                default:
-                    throw new ArgumentOutOfRangeException(nameof(syntax));
-            }
-
-            if (!string.IsNullOrEmpty(package))
-            {
-                headerBuilder.Append("package ").Append(package).Append(';');
-                Helpers.AppendLine(headerBuilder);
-            }
-
-            var imports = CommonImports.None;
-            StringBuilder bodyBuilder = new StringBuilder();
-            // sort them by schema-name
-            MetaType[] metaTypesArr = new MetaType[requiredTypes.Count];
-            requiredTypes.CopyTo(metaTypesArr, 0);
-            Array.Sort(metaTypesArr, MetaType.Comparer.Default);
-
-            // write the messages
-            if (isInbuiltType)
-            {
-                Helpers.AppendLine(bodyBuilder).Append("message ").Append(type.Name).Append(" {");
-                MetaType.NewLine(bodyBuilder, 1).Append(syntax == ProtoSyntax.Proto2 ? "optional " : "").Append(GetSchemaTypeName(type, DataFormat.Default, false, false, ref imports))
-                    .Append(" value = 1;");
-                Helpers.AppendLine(bodyBuilder).Append('}');
-            }
-            else
-            {
-                for (int i = 0; i < metaTypesArr.Length; i++)
-                {
-                    MetaType tmp = metaTypesArr[i];
-                    if (tmp.IsList && tmp != primaryType) continue;
-                    tmp.WriteSchema(bodyBuilder, 0, ref imports, syntax);
-                }
-            }
-            if ((imports & CommonImports.Bcl) != 0)
-            {
-                headerBuilder.Append("import \"protobuf-net/bcl.proto\"; // schema for protobuf-net's handling of core .NET types");
-                Helpers.AppendLine(headerBuilder);
-            }
-            if ((imports & CommonImports.Protogen) != 0)
-            {
-                headerBuilder.Append("import \"protobuf-net/protogen.proto\"; // custom protobuf-net options");
-                Helpers.AppendLine(headerBuilder);
-            }
-            if ((imports & CommonImports.Timestamp) != 0)
-            {
-                headerBuilder.Append("import \"google/protobuf/timestamp.proto\";");
-                Helpers.AppendLine(headerBuilder);
-            }
-            if ((imports & CommonImports.Duration) != 0)
-            {
-                headerBuilder.Append("import \"google/protobuf/duration.proto\";");
-                Helpers.AppendLine(headerBuilder);
-            }
-            return Helpers.AppendLine(headerBuilder.Append(bodyBuilder)).ToString();
-        }
-        [Flags]
-        internal enum CommonImports
-        {
-            None = 0,
-            Bcl = 1,
-            Timestamp = 2,
-            Duration = 4,
-            Protogen = 8
-        }
-        private void CascadeDependents(BasicList list, MetaType metaType)
-        {
-            MetaType tmp;
-            if (metaType.IsList)
-            {
-                Type itemType = TypeModel.GetListItemType(this, metaType.Type);
-                TryGetCoreSerializer(list, itemType);
-            }
-            else
-            {
-                if (metaType.IsAutoTuple)
-                {
-                    MemberInfo[] mapping;
-                    if (MetaType.ResolveTupleConstructor(metaType.Type, out mapping) != null)
-                    {
-                        for (int i = 0; i < mapping.Length; i++)
-                        {
-                            Type type = null;
-                            if (mapping[i] is PropertyInfo) type = ((PropertyInfo)mapping[i]).PropertyType;
-                            else if (mapping[i] is FieldInfo) type = ((FieldInfo)mapping[i]).FieldType;
-                            TryGetCoreSerializer(list, type);
-                        }
-                    }
-                }
-                else
-                {
-                    foreach (ValueMember member in metaType.Fields)
-                    {
-                        Type type = member.ItemType;
-                        if (member.IsMap)
-                        {
-                            member.ResolveMapTypes(out _, out _, out type); // don't need key-type
-                        }
-                        if (type == null) type = member.MemberType;
-                        TryGetCoreSerializer(list, type);
-                    }
-                }
-                foreach (var genericArgument in metaType.GetAllGenericArguments())
-                {
-                    TryGetCoreSerializer(list, genericArgument);
-                }
-                if (metaType.HasSubtypes)
-                {
-                    foreach (SubType subType in metaType.GetSubtypes())
-                    {
-                        tmp = subType.DerivedType.GetSurrogateOrSelf(); // note: exclude base-types!
-                        if (!list.Contains(tmp))
-                        {
-                            list.Add(tmp);
-                            CascadeDependents(list, tmp);
-                        }
-                    }
-                }
-                tmp = metaType.BaseType;
-                if (tmp != null) tmp = tmp.GetSurrogateOrSelf(); // note: already walking base-types; exclude base
-                if (tmp != null && !list.Contains(tmp))
-                {
-                    list.Add(tmp);
-                    CascadeDependents(list, tmp);
-                }
-            }
-        }
-
-        private void TryGetCoreSerializer(BasicList list, Type itemType)
-        {
-            var coreSerializer = ValueMember.TryGetCoreSerializer(this, DataFormat.Default, itemType, out _, false, false, false, false);
-            if (coreSerializer != null)
-            {
-                return;
-            }
-            int index = FindOrAddAuto(itemType, false, false, false);
-            if (index < 0)
-            {
-                return;
-            }
-            var temp = ((MetaType)types[index]).GetSurrogateOrBaseOrSelf(false);
-            if (list.Contains(temp))
-            {
-                return;
-            }
-            // could perhaps also implement as a queue, but this should work OK for sane models
-            list.Add(temp);
-            CascadeDependents(list, temp);
-        }
-
-#if !NO_RUNTIME
-        /// <summary>
-        /// Creates a new runtime model, to which the caller
-        /// can add support for a range of types. A model
-        /// can be used "as is", or can be compiled for
-        /// optimal performance.
-        /// </summary>
-        /// <param name="name">not used currently; this is for compatibility with v3</param>
-        public static RuntimeTypeModel Create(string name = null)
-        {
-            return new RuntimeTypeModel(false);
-        }
-#endif
-
-        private RuntimeTypeModel(bool isDefault)
-        {
-            AutoAddMissingTypes = true;
-            UseImplicitZeroDefaults = true;
-            SetOption(OPTIONS_IsDefaultModel, isDefault);
-#if FEAT_COMPILER && !DEBUG
-            try
-            {
-                AutoCompile = EnableAutoCompile();
-            }
-            catch { } // this is all kinds of brittle on things like UWP
-#endif
-        }
-
-#if FEAT_COMPILER
-        [MethodImpl(MethodImplOptions.NoInlining)]
-        internal static bool EnableAutoCompile()
-        {
-            try
-            {
-                var dm = new DynamicMethod("CheckCompilerAvailable", typeof(bool), new Type[] { typeof(int) });
-                var il = dm.GetILGenerator();
-                il.Emit(OpCodes.Ldarg_0);
-                il.Emit(OpCodes.Ldc_I4, 42);
-                il.Emit(OpCodes.Ceq);
-                il.Emit(OpCodes.Ret);
-                var func = (Predicate<int>)dm.CreateDelegate(typeof(Predicate<int>));
-                return func(42);
-            }
-            catch (Exception ex)
-            {
-                Debug.WriteLine(ex);
-                return false;
-            }
-        }
-#endif
-
-        /// <summary>
-        /// Obtains the MetaType associated with a given Type for the current model,
-        /// allowing additional configuration.
-        /// </summary>
-        public MetaType this[Type type] { get { return (MetaType)types[FindOrAddAuto(type, true, false, false)]; } }
-
-        internal MetaType FindWithoutAdd(Type type)
-        {
-            // this list is thread-safe for reading
-            foreach (MetaType metaType in types)
-            {
-                if (metaType.Type == type)
-                {
-                    if (metaType.Pending) WaitOnLock(metaType);
-                    return metaType;
-                }
-            }
-            // if that failed, check for a proxy
-            Type underlyingType = ResolveProxies(type);
-            return underlyingType == null ? null : FindWithoutAdd(underlyingType);
-        }
-
-        static readonly BasicList.MatchPredicate
-            MetaTypeFinder = new BasicList.MatchPredicate(MetaTypeFinderImpl),
-            BasicTypeFinder = new BasicList.MatchPredicate(BasicTypeFinderImpl);
-
-        static bool MetaTypeFinderImpl(object value, object ctx)
-        {
-            return ((MetaType)value).Type == (Type)ctx;
-        }
-
-        static bool BasicTypeFinderImpl(object value, object ctx)
-        {
-            return ((BasicType)value).Type == (Type)ctx;
-        }
-
-        private void WaitOnLock(MetaType type)
-        {
-            int opaqueToken = 0;
-            try
-            {
-                TakeLock(ref opaqueToken);
-            }
-            finally
-            {
-                ReleaseLock(opaqueToken);
-            }
-        }
-
-        BasicList basicTypes = new BasicList();
-
-        sealed class BasicType
-        {
-            private readonly Type type;
-            public Type Type => type;
-            private readonly IProtoSerializer serializer;
-            public IProtoSerializer Serializer => serializer;
-
-            public BasicType(Type type, IProtoSerializer serializer)
-            {
-                this.type = type;
-                this.serializer = serializer;
-            }
-        }
-        internal IProtoSerializer TryGetBasicTypeSerializer(Type type)
-        {
-            int idx = basicTypes.IndexOf(BasicTypeFinder, type);
-
-            if (idx >= 0) return ((BasicType)basicTypes[idx]).Serializer;
-
-            lock (basicTypes)
-            { // don't need a full model lock for this
-
-                // double-checked
-                idx = basicTypes.IndexOf(BasicTypeFinder, type);
-                if (idx >= 0) return ((BasicType)basicTypes[idx]).Serializer;
-
-                MetaType.AttributeFamily family = MetaType.GetContractFamily(this, type, null);
-                IProtoSerializer ser = family == MetaType.AttributeFamily.None
-                    ? ValueMember.TryGetCoreSerializer(this, DataFormat.Default, type, out WireType defaultWireType, false, false, false, false)
-                    : null;
-
-                if (ser != null) basicTypes.Add(new BasicType(type, ser));
-                return ser;
-            }
-        }
-
-        internal int FindOrAddAuto(Type type, bool demand, bool addWithContractOnly, bool addEvenIfAutoDisabled)
-        {
-            int key = types.IndexOf(MetaTypeFinder, type);
-            MetaType metaType;
-
-            // the fast happy path: meta-types we've already seen
-            if (key >= 0)
-            {
-                metaType = (MetaType)types[key];
-                if (metaType.Pending)
-                {
-                    WaitOnLock(metaType);
-                }
-                return key;
-            }
-
-            // the fast fail path: types that will never have a meta-type
-            bool shouldAdd = AutoAddMissingTypes || addEvenIfAutoDisabled;
-
-            if (!Helpers.IsEnum(type) && TryGetBasicTypeSerializer(type) != null)
-            {
-                if (shouldAdd && !addWithContractOnly) throw MetaType.InbuiltType(type);
-                return -1; // this will never be a meta-type
-            }
-
-            // otherwise: we don't yet know
-
-            // check for proxy types
-            Type underlyingType = ResolveProxies(type);
-            if (underlyingType != null && underlyingType != type)
-            {
-                key = types.IndexOf(MetaTypeFinder, underlyingType);
-                type = underlyingType; // if new added, make it reflect the underlying type
-            }
-
-            if (key < 0)
-            {
-                int opaqueToken = 0;
-                Type origType = type;
-                bool weAdded = false;
-                try
-                {
-                    TakeLock(ref opaqueToken);
-                    // try to recognise a few familiar patterns...
-                    if ((metaType = RecogniseCommonTypes(type)) == null)
-                    { // otherwise, check if it is a contract
-                        MetaType.AttributeFamily family = MetaType.GetContractFamily(this, type, null);
-                        if (family == MetaType.AttributeFamily.AutoTuple)
-                        {
-                            shouldAdd = addEvenIfAutoDisabled = true; // always add basic tuples, such as KeyValuePair
-                        }
-
-                        if (!shouldAdd || (
-                            !Helpers.IsEnum(type) && addWithContractOnly && family == MetaType.AttributeFamily.None)
-                            )
-                        {
-                            if (demand) ThrowUnexpectedType(type);
-                            return key;
-                        }
-                        metaType = Create(type);
-                    }
-
-                    metaType.Pending = true;                    
-                    
-                    // double-checked
-                    int winner = types.IndexOf(MetaTypeFinder, type);
-                    if (winner < 0)
-                    {
-                        ThrowIfFrozen();
-                        key = types.Add(metaType);
-                        weAdded = true;
-                    }
-                    else
-                    {
-                        key = winner;
-                    }
-                    if (weAdded)
-                    {
-                        metaType.ApplyDefaultBehaviour();
-                        metaType.Pending = false;
-                    }
-                }
-                finally
-                {
-                    ReleaseLock(opaqueToken);
-                    if (weAdded)
-                    {
-                        ResetKeyCache();
-                    }
-                }
-            }
-            return key;
-        }
-
-        private MetaType RecogniseCommonTypes(Type type)
-        {
-            //            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(System.Collections.Generic.KeyValuePair<,>))
-            //            {
-            //                MetaType mt = new MetaType(this, type);
-
-            //                Type surrogate = typeof (KeyValuePairSurrogate<,>).MakeGenericType(type.GetGenericArguments());
-
-            //                mt.SetSurrogate(surrogate);
-            //                mt.IncludeSerializerMethod = false;
-            //                mt.Freeze();
-
-            //                MetaType surrogateMeta = (MetaType)types[FindOrAddAuto(surrogate, true, true, true)]; // this forcibly adds it if needed
-            //                if(surrogateMeta.IncludeSerializerMethod)
-            //                { // don't blindly set - it might be frozen
-            //                    surrogateMeta.IncludeSerializerMethod = false;
-            //                }
-            //                surrogateMeta.Freeze();
-            //                return mt;
-            //            }
-            return null;
-        }
-        private MetaType Create(Type type)
-        {
-            ThrowIfFrozen();
-            return new MetaType(this, type, defaultFactory);
-        }
-
-        /// <summary>
-        /// Adds support for an additional type in this model, optionally
-        /// applying inbuilt patterns. If the type is already known to the
-        /// model, the existing type is returned **without** applying
-        /// any additional behaviour.
-        /// </summary>
-        /// <remarks>Inbuilt patterns include:
-        /// [ProtoContract]/[ProtoMember(n)]
-        /// [DataContract]/[DataMember(Order=n)]
-        /// [XmlType]/[XmlElement(Order=n)]
-        /// [On{Des|S}erializ{ing|ed}]
-        /// ShouldSerialize*/*Specified
-        /// </remarks>
-        /// <param name="type">The type to be supported</param>
-        /// <param name="applyDefaultBehaviour">Whether to apply the inbuilt configuration patterns (via attributes etc), or
-        /// just add the type with no additional configuration (the type must then be manually configured).</param>
-        /// <returns>The MetaType representing this type, allowing
-        /// further configuration.</returns>
-        public MetaType Add(Type type, bool applyDefaultBehaviour)
-        {
-            if (type == null) throw new ArgumentNullException("type");
-            MetaType newType = FindWithoutAdd(type);
-            if (newType != null) return newType; // return existing
-            int opaqueToken = 0;
-
-#if COREFX || PROFILE259
-            TypeInfo typeInfo = IntrospectionExtensions.GetTypeInfo(type);
-            if (typeInfo.IsInterface && MetaType.ienumerable.IsAssignableFrom(typeInfo)
-#else
-            if (type.IsInterface && MapType(MetaType.ienumerable).IsAssignableFrom(type)
-#endif
-                    && GetListItemType(this, type) == null)
-            {
-                throw new ArgumentException("IEnumerable[<T>] data cannot be used as a meta-type unless an Add method can be resolved");
-            }
-            try
-            {
-                newType = RecogniseCommonTypes(type);
-                if (newType != null)
-                {
-                    if (!applyDefaultBehaviour)
-                    {
-                        throw new ArgumentException(
-                            "Default behaviour must be observed for certain types with special handling; " + type.FullName,
-                            "applyDefaultBehaviour");
-                    }
-                    // we should assume that type is fully configured, though; no need to re-run:
-                    applyDefaultBehaviour = false;
-                }
-                if (newType == null) newType = Create(type);
-                newType.Pending = true;
-                TakeLock(ref opaqueToken);
-                // double checked
-                if (FindWithoutAdd(type) != null) throw new ArgumentException("Duplicate type", "type");
-                ThrowIfFrozen();
-                types.Add(newType);
-                if (applyDefaultBehaviour) { newType.ApplyDefaultBehaviour(); }
-                newType.Pending = false;
-            }
-            finally
-            {
-                ReleaseLock(opaqueToken);
-                ResetKeyCache();
-            }
-
-            return newType;
-        }
-
-#if FEAT_COMPILER
-        /// <summary>
-        /// Should serializers be compiled on demand? It may be useful
-        /// to disable this for debugging purposes.
-        /// </summary>
-        public bool AutoCompile
-        {
-            get { return GetOption(OPTIONS_AutoCompile); }
-            set { SetOption(OPTIONS_AutoCompile, value); }
-        }
-#endif
-        /// <summary>
-        /// Should support for unexpected types be added automatically?
-        /// If false, an exception is thrown when unexpected types
-        /// are encountered.
-        /// </summary>
-        public bool AutoAddMissingTypes
-        {
-            get { return GetOption(OPTIONS_AutoAddMissingTypes); }
-            set
-            {
-                if (!value && GetOption(OPTIONS_IsDefaultModel))
-                {
-                    throw new InvalidOperationException("The default model must allow missing types");
-                }
-                ThrowIfFrozen();
-                SetOption(OPTIONS_AutoAddMissingTypes, value);
-            }
-        }
-        /// <summary>
-        /// Verifies that the model is still open to changes; if not, an exception is thrown
-        /// </summary>
-        private void ThrowIfFrozen()
-        {
-            if (GetOption(OPTIONS_Frozen)) throw new InvalidOperationException("The model cannot be changed once frozen");
-        }
-
-        /// <summary>
-        /// Prevents further changes to this model
-        /// </summary>
-        public void Freeze()
-        {
-            if (GetOption(OPTIONS_IsDefaultModel)) throw new InvalidOperationException("The default model cannot be frozen");
-            SetOption(OPTIONS_Frozen, true);
-        }
-
-        private readonly BasicList types = new BasicList();
-
-        /// <summary>
-        /// Provides the key that represents a given type in the current model.
-        /// </summary>
-        protected override int GetKeyImpl(Type type)
-        {
-            return GetKey(type, false, true);
-        }
-
-        internal int GetKey(Type type, bool demand, bool getBaseKey)
-        {
-            Helpers.DebugAssert(type != null);
-            try
-            {
-                int typeIndex = FindOrAddAuto(type, demand, true, false);
-                if (typeIndex >= 0)
-                {
-                    MetaType mt = (MetaType)types[typeIndex];
-                    if (getBaseKey)
-                    {
-                        mt = MetaType.GetRootType(mt);
-                        typeIndex = FindOrAddAuto(mt.Type, true, true, false);
-                    }
-                }
-                return typeIndex;
-            }
-            catch (NotSupportedException)
-            {
-                throw; // re-surface "as-is"
-            }
-            catch (Exception ex)
-            {
-                if (ex.Message.IndexOf(type.FullName) >= 0) throw;  // already enough info
-                throw new ProtoException(ex.Message + " (" + type.FullName + ")", ex);
-            }
-        }
-
-        /// <summary>
-        /// Writes a protocol-buffer representation of the given instance to the supplied stream.
-        /// </summary>
-        /// <param name="key">Represents the type (including inheritance) to consider.</param>
-        /// <param name="value">The existing instance to be serialized (cannot be null).</param>
-        /// <param name="dest">The destination stream to write to.</param>
-        protected internal override void Serialize(int key, object value, ProtoWriter dest)
-        {
-            //Helpers.DebugWriteLine("Serialize", value);
-            ((MetaType)types[key]).Serializer.Write(value, dest);
-        }
-
-        /// <summary>
-        /// Applies a protocol-buffer stream to an existing instance (which may be null).
-        /// </summary>
-        /// <param name="key">Represents the type (including inheritance) to consider.</param>
-        /// <param name="value">The existing instance to be modified (can be null).</param>
-        /// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
-        /// <returns>The updated instance; this may be different to the instance argument if
-        /// either the original instance was null, or the stream defines a known sub-type of the
-        /// original instance.</returns>
-        protected internal override object Deserialize(int key, object value, ProtoReader source)
-        {
-            //Helpers.DebugWriteLine("Deserialize", value);
-            IProtoSerializer ser = ((MetaType)types[key]).Serializer;
-            if (value == null && Helpers.IsValueType(ser.ExpectedType))
-            {
-                if (ser.RequiresOldValue) value = Activator.CreateInstance(ser.ExpectedType);
-                return ser.Read(value, source);
-            }
-            else
-            {
-                return ser.Read(value, source);
-            }
-        }
-
-#if FEAT_COMPILER
-        // this is used by some unit-tests; do not remove
-        internal Compiler.ProtoSerializer GetSerializer(IProtoSerializer serializer, bool compiled)
-        {
-            if (serializer == null) throw new ArgumentNullException("serializer");
-#if FEAT_COMPILER
-            if (compiled) return Compiler.CompilerContext.BuildSerializer(serializer, this);
-#endif
-            return new Compiler.ProtoSerializer(serializer.Write);
-        }
-
-        /// <summary>
-        /// Compiles the serializers individually; this is *not* a full
-        /// standalone compile, but can significantly boost performance
-        /// while allowing additional types to be added.
-        /// </summary>
-        /// <remarks>An in-place compile can access non-public types / members</remarks>
-        public void CompileInPlace()
-        {
-            foreach (MetaType type in types)
-            {
-                type.CompileInPlace();
-            }
-        }
-
-#endif
-        //internal override IProtoSerializer GetTypeSerializer(Type type)
-        //{   // this list is thread-safe for reading
-        //    .Serializer;
-        //}
-        //internal override IProtoSerializer GetTypeSerializer(int key)
-        //{   // this list is thread-safe for reading
-        //    MetaType type = (MetaType)types.TryGet(key);
-        //    if (type != null) return type.Serializer;
-        //    throw new KeyNotFoundException();
-
-        //}
-
-#if FEAT_COMPILER
-        private void BuildAllSerializers()
-        {
-            // note that types.Count may increase during this operation, as some serializers
-            // bring other types into play
-            for (int i = 0; i < types.Count; i++)
-            {
-                // the primary purpose of this is to force the creation of the Serializer
-                MetaType mt = (MetaType)types[i];
-                if (mt.Serializer == null)
-                    throw new InvalidOperationException("No serializer available for " + mt.Type.Name);
-            }
-        }
-
-        internal sealed class SerializerPair : IComparable
-        {
-            int IComparable.CompareTo(object obj)
-            {
-                if (obj == null) throw new ArgumentException("obj");
-                SerializerPair other = (SerializerPair)obj;
-
-                // we want to bunch all the items with the same base-type together, but we need the items with a
-                // different base **first**.
-                if (this.BaseKey == this.MetaKey)
-                {
-                    if (other.BaseKey == other.MetaKey)
-                    { // neither is a subclass
-                        return this.MetaKey.CompareTo(other.MetaKey);
-                    }
-                    else
-                    { // "other" (only) is involved in inheritance; "other" should be first
-                        return 1;
-                    }
-                }
-                else
-                {
-                    if (other.BaseKey == other.MetaKey)
-                    { // "this" (only) is involved in inheritance; "this" should be first
-                        return -1;
-                    }
-                    else
-                    { // both are involved in inheritance
-                        int result = this.BaseKey.CompareTo(other.BaseKey);
-                        if (result == 0) result = this.MetaKey.CompareTo(other.MetaKey);
-                        return result;
-                    }
-                }
-            }
-            public readonly int MetaKey, BaseKey;
-            public readonly MetaType Type;
-            public readonly MethodBuilder Serialize, Deserialize;
-            public readonly ILGenerator SerializeBody, DeserializeBody;
-            public SerializerPair(int metaKey, int baseKey, MetaType type, MethodBuilder serialize, MethodBuilder deserialize,
-                ILGenerator serializeBody, ILGenerator deserializeBody)
-            {
-                this.MetaKey = metaKey;
-                this.BaseKey = baseKey;
-                this.Serialize = serialize;
-                this.Deserialize = deserialize;
-                this.SerializeBody = serializeBody;
-                this.DeserializeBody = deserializeBody;
-                this.Type = type;
-            }
-        }
-
-        /// <summary>
-        /// Fully compiles the current model into a static-compiled model instance
-        /// </summary>
-        /// <remarks>A full compilation is restricted to accessing public types / members</remarks>
-        /// <returns>An instance of the newly created compiled type-model</returns>
-        public TypeModel Compile()
-        {
-            CompilerOptions options = new CompilerOptions();
-            return Compile(options);
-        }
-
-        static ILGenerator Override(TypeBuilder type, string name)
-        {
-            MethodInfo baseMethod = type.BaseType.GetMethod(name, BindingFlags.NonPublic | BindingFlags.Instance);
-
-            ParameterInfo[] parameters = baseMethod.GetParameters();
-            Type[] paramTypes = new Type[parameters.Length];
-            for (int i = 0; i < paramTypes.Length; i++)
-            {
-                paramTypes[i] = parameters[i].ParameterType;
-            }
-            MethodBuilder newMethod = type.DefineMethod(baseMethod.Name,
-                (baseMethod.Attributes & ~MethodAttributes.Abstract) | MethodAttributes.Final, baseMethod.CallingConvention, baseMethod.ReturnType, paramTypes);
-            ILGenerator il = newMethod.GetILGenerator();
-            type.DefineMethodOverride(newMethod, baseMethod);
-            return il;
-        }
-
-        /// <summary>
-        /// Represents configuration options for compiling a model to 
-        /// a standalone assembly.
-        /// </summary>
-        public sealed class CompilerOptions
-        {
-            /// <summary>
-            /// Import framework options from an existing type
-            /// </summary>
-            public void SetFrameworkOptions(MetaType from)
-            {
-                if (from == null) throw new ArgumentNullException("from");
-                AttributeMap[] attribs = AttributeMap.Create(from.Model, Helpers.GetAssembly(from.Type));
-                foreach (AttributeMap attrib in attribs)
-                {
-                    if (attrib.AttributeType.FullName == "System.Runtime.Versioning.TargetFrameworkAttribute")
-                    {
-                        object tmp;
-                        if (attrib.TryGet("FrameworkName", out tmp)) TargetFrameworkName = (string)tmp;
-                        if (attrib.TryGet("FrameworkDisplayName", out tmp)) TargetFrameworkDisplayName = (string)tmp;
-                        break;
-                    }
-                }
-            }
-
-            private string targetFrameworkName, targetFrameworkDisplayName, typeName, outputPath, imageRuntimeVersion;
-            private int metaDataVersion;
-            /// <summary>
-            /// The TargetFrameworkAttribute FrameworkName value to burn into the generated assembly
-            /// </summary>
-            public string TargetFrameworkName { get { return targetFrameworkName; } set { targetFrameworkName = value; } }
-
-            /// <summary>
-            /// The TargetFrameworkAttribute FrameworkDisplayName value to burn into the generated assembly
-            /// </summary>
-            public string TargetFrameworkDisplayName { get { return targetFrameworkDisplayName; } set { targetFrameworkDisplayName = value; } }
-            /// <summary>
-            /// The name of the TypeModel class to create
-            /// </summary>
-            public string TypeName { get { return typeName; } set { typeName = value; } }
-
-#if COREFX
-            internal const string NoPersistence = "Assembly persistence not supported on this runtime";
-#endif
-            /// <summary>
-            /// The path for the new dll
-            /// </summary>
-#if COREFX
-            [Obsolete(NoPersistence)]
-#endif
-            public string OutputPath { get { return outputPath; } set { outputPath = value; } }
-            /// <summary>
-            /// The runtime version for the generated assembly
-            /// </summary>
-            public string ImageRuntimeVersion { get { return imageRuntimeVersion; } set { imageRuntimeVersion = value; } }
-            /// <summary>
-            /// The runtime version for the generated assembly
-            /// </summary>
-            public int MetaDataVersion { get { return metaDataVersion; } set { metaDataVersion = value; } }
-
-
-            private Accessibility accessibility = Accessibility.Public;
-            /// <summary>
-            /// The acecssibility of the generated serializer
-            /// </summary>
-            public Accessibility Accessibility { get { return accessibility; } set { accessibility = value; } }
-        }
-
-        /// <summary>
-        /// Type accessibility
-        /// </summary>
-        public enum Accessibility
-        {
-            /// <summary>
-            /// Available to all callers
-            /// </summary>
-            Public,
-            /// <summary>
-            /// Available to all callers in the same assembly, or assemblies specified via [InternalsVisibleTo(...)]
-            /// </summary>
-            Internal
-        }
-
-#if !COREFX
-        /// <summary>
-        /// Fully compiles the current model into a static-compiled serialization dll
-        /// (the serialization dll still requires protobuf-net for support services).
-        /// </summary>
-        /// <remarks>A full compilation is restricted to accessing public types / members</remarks>
-        /// <param name="name">The name of the TypeModel class to create</param>
-        /// <param name="path">The path for the new dll</param>
-        /// <returns>An instance of the newly created compiled type-model</returns>
-        public TypeModel Compile(string name, string path)
-        {
-            CompilerOptions options = new CompilerOptions();
-            options.TypeName = name;
-            options.OutputPath = path;
-            return Compile(options);
-        }
-#endif
-        /// <summary>
-        /// Fully compiles the current model into a static-compiled serialization dll
-        /// (the serialization dll still requires protobuf-net for support services).
-        /// </summary>
-        /// <remarks>A full compilation is restricted to accessing public types / members</remarks>
-        /// <returns>An instance of the newly created compiled type-model</returns>
-        public TypeModel Compile(CompilerOptions options)
-        {
-            if (options == null) throw new ArgumentNullException("options");
-            string typeName = options.TypeName;
-#pragma warning disable 0618
-            string path = options.OutputPath;
-#pragma warning restore 0618
-            BuildAllSerializers();
-            Freeze();
-            bool save = !string.IsNullOrEmpty(path);
-            if (string.IsNullOrEmpty(typeName))
-            {
-                if (save) throw new ArgumentNullException("typeName");
-                typeName = Guid.NewGuid().ToString();
-            }
-
-
-            string assemblyName, moduleName;
-            if (path == null)
-            {
-                assemblyName = typeName;
-                moduleName = assemblyName + ".dll";
-            }
-            else
-            {
-                assemblyName = new System.IO.FileInfo(System.IO.Path.GetFileNameWithoutExtension(path)).Name;
-                moduleName = assemblyName + System.IO.Path.GetExtension(path);
-            }
-
-#if COREFX
-            AssemblyName an = new AssemblyName();
-            an.Name = assemblyName;
-            AssemblyBuilder asm = AssemblyBuilder.DefineDynamicAssembly(an,
-                AssemblyBuilderAccess.Run);
-            ModuleBuilder module = asm.DefineDynamicModule(moduleName);
-#else
-            AssemblyName an = new AssemblyName();
-            an.Name = assemblyName;
-            AssemblyBuilder asm = AppDomain.CurrentDomain.DefineDynamicAssembly(an,
-                (save ? AssemblyBuilderAccess.RunAndSave : AssemblyBuilderAccess.Run)
-                );
-            ModuleBuilder module = save ? asm.DefineDynamicModule(moduleName, path)
-                                        : asm.DefineDynamicModule(moduleName);
-#endif
-
-            WriteAssemblyAttributes(options, assemblyName, asm);
-
-            TypeBuilder type = WriteBasicTypeModel(options, typeName, module);
-
-            int index;
-            bool hasInheritance;
-            SerializerPair[] methodPairs;
-            Compiler.CompilerContext.ILVersion ilVersion;
-            WriteSerializers(options, assemblyName, type, out index, out hasInheritance, out methodPairs, out ilVersion);
-
-            ILGenerator il;
-            int knownTypesCategory;
-            FieldBuilder knownTypes;
-            Type knownTypesLookupType;
-            WriteGetKeyImpl(type, hasInheritance, methodPairs, ilVersion, assemblyName, out il, out knownTypesCategory, out knownTypes, out knownTypesLookupType);
-
-            // trivial flags
-            il = Override(type, "SerializeDateTimeKind");
-            il.Emit(IncludeDateTimeKind ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
-            il.Emit(OpCodes.Ret);
-            // end: trivial flags
-
-            Compiler.CompilerContext ctx = WriteSerializeDeserialize(assemblyName, type, methodPairs, ilVersion, ref il);
-
-            WriteConstructors(type, ref index, methodPairs, ref il, knownTypesCategory, knownTypes, knownTypesLookupType, ctx);
-
-
-#if COREFX
-            Type finalType = type.CreateTypeInfo().AsType();
-#else
-            Type finalType = type.CreateType();
-#endif
-            if (!string.IsNullOrEmpty(path))
-            {
-#if COREFX
-                throw new NotSupportedException(CompilerOptions.NoPersistence);
-#else
-                try
-                {
-                    asm.Save(path);
-                }
-                catch (IOException ex)
-                {
-                    // advertise the file info
-                    throw new IOException(path + ", " + ex.Message, ex);
-                }
-                Helpers.DebugWriteLine("Wrote dll:" + path);
-#endif
-            }
-            return (TypeModel)Activator.CreateInstance(finalType);
-        }
-
-        private void WriteConstructors(TypeBuilder type, ref int index, SerializerPair[] methodPairs, ref ILGenerator il, int knownTypesCategory, FieldBuilder knownTypes, Type knownTypesLookupType, Compiler.CompilerContext ctx)
-        {
-            type.DefineDefaultConstructor(MethodAttributes.Public);
-            il = type.DefineTypeInitializer().GetILGenerator();
-            switch (knownTypesCategory)
-            {
-                case KnownTypes_Array:
-                    {
-                        Compiler.CompilerContext.LoadValue(il, types.Count);
-                        il.Emit(OpCodes.Newarr, ctx.MapType(typeof(System.Type)));
-                        index = 0;
-                        foreach (SerializerPair pair in methodPairs)
-                        {
-                            il.Emit(OpCodes.Dup);
-                            Compiler.CompilerContext.LoadValue(il, index);
-                            il.Emit(OpCodes.Ldtoken, pair.Type.Type);
-                            il.EmitCall(OpCodes.Call, ctx.MapType(typeof(System.Type)).GetMethod("GetTypeFromHandle"), null);
-                            il.Emit(OpCodes.Stelem_Ref);
-                            index++;
-                        }
-                        il.Emit(OpCodes.Stsfld, knownTypes);
-                        il.Emit(OpCodes.Ret);
-                    }
-                    break;
-                case KnownTypes_Dictionary:
-                    {
-                        Compiler.CompilerContext.LoadValue(il, types.Count);
-                        //LocalBuilder loc = il.DeclareLocal(knownTypesLookupType);
-                        il.Emit(OpCodes.Newobj, knownTypesLookupType.GetConstructor(new Type[] { MapType(typeof(int)) }));
-                        il.Emit(OpCodes.Stsfld, knownTypes);
-                        int typeIndex = 0;
-                        foreach (SerializerPair pair in methodPairs)
-                        {
-                            il.Emit(OpCodes.Ldsfld, knownTypes);
-                            il.Emit(OpCodes.Ldtoken, pair.Type.Type);
-                            il.EmitCall(OpCodes.Call, ctx.MapType(typeof(System.Type)).GetMethod("GetTypeFromHandle"), null);
-                            int keyIndex = typeIndex++, lastKey = pair.BaseKey;
-                            if (lastKey != pair.MetaKey) // not a base-type; need to give the index of the base-type
-                            {
-                                keyIndex = -1; // assume epic fail
-                                for (int j = 0; j < methodPairs.Length; j++)
-                                {
-                                    if (methodPairs[j].BaseKey == lastKey && methodPairs[j].MetaKey == lastKey)
-                                    {
-                                        keyIndex = j;
-                                        break;
-                                    }
-                                }
-                            }
-                            Compiler.CompilerContext.LoadValue(il, keyIndex);
-                            il.EmitCall(OpCodes.Callvirt, knownTypesLookupType.GetMethod("Add", new Type[] { MapType(typeof(System.Type)), MapType(typeof(int)) }), null);
-                        }
-                        il.Emit(OpCodes.Ret);
-                    }
-                    break;
-                case KnownTypes_Hashtable:
-                    {
-                        Compiler.CompilerContext.LoadValue(il, types.Count);
-                        il.Emit(OpCodes.Newobj, knownTypesLookupType.GetConstructor(new Type[] { MapType(typeof(int)) }));
-                        il.Emit(OpCodes.Stsfld, knownTypes);
-                        int typeIndex = 0;
-                        foreach (SerializerPair pair in methodPairs)
-                        {
-                            il.Emit(OpCodes.Ldsfld, knownTypes);
-                            il.Emit(OpCodes.Ldtoken, pair.Type.Type);
-                            il.EmitCall(OpCodes.Call, ctx.MapType(typeof(System.Type)).GetMethod("GetTypeFromHandle"), null);
-                            int keyIndex = typeIndex++, lastKey = pair.BaseKey;
-                            if (lastKey != pair.MetaKey) // not a base-type; need to give the index of the base-type
-                            {
-                                keyIndex = -1; // assume epic fail
-                                for (int j = 0; j < methodPairs.Length; j++)
-                                {
-                                    if (methodPairs[j].BaseKey == lastKey && methodPairs[j].MetaKey == lastKey)
-                                    {
-                                        keyIndex = j;
-                                        break;
-                                    }
-                                }
-                            }
-                            Compiler.CompilerContext.LoadValue(il, keyIndex);
-                            il.Emit(OpCodes.Box, MapType(typeof(int)));
-                            il.EmitCall(OpCodes.Callvirt, knownTypesLookupType.GetMethod("Add", new Type[] { MapType(typeof(object)), MapType(typeof(object)) }), null);
-                        }
-                        il.Emit(OpCodes.Ret);
-                    }
-                    break;
-                default:
-                    throw new InvalidOperationException();
-            }
-        }
-
-        private Compiler.CompilerContext WriteSerializeDeserialize(string assemblyName, TypeBuilder type, SerializerPair[] methodPairs, Compiler.CompilerContext.ILVersion ilVersion, ref ILGenerator il)
-        {
-            il = Override(type, "Serialize");
-            Compiler.CompilerContext ctx = new Compiler.CompilerContext(il, false, true, methodPairs, this, ilVersion, assemblyName, MapType(typeof(object)), "Serialize " + type.Name);
-            // arg0 = this, arg1 = key, arg2=obj, arg3=dest
-            Compiler.CodeLabel[] jumpTable = new Compiler.CodeLabel[types.Count];
-            for (int i = 0; i < jumpTable.Length; i++)
-            {
-                jumpTable[i] = ctx.DefineLabel();
-            }
-            il.Emit(OpCodes.Ldarg_1);
-            ctx.Switch(jumpTable);
-            ctx.Return();
-            for (int i = 0; i < jumpTable.Length; i++)
-            {
-                SerializerPair pair = methodPairs[i];
-                ctx.MarkLabel(jumpTable[i]);
-                il.Emit(OpCodes.Ldarg_2);
-                ctx.CastFromObject(pair.Type.Type);
-                il.Emit(OpCodes.Ldarg_3);
-                il.EmitCall(OpCodes.Call, pair.Serialize, null);
-                ctx.Return();
-            }
-
-            il = Override(type, "Deserialize");
-            ctx = new Compiler.CompilerContext(il, false, false, methodPairs, this, ilVersion, assemblyName, MapType(typeof(object)), "Deserialize " + type.Name);
-            // arg0 = this, arg1 = key, arg2=obj, arg3=source
-            for (int i = 0; i < jumpTable.Length; i++)
-            {
-                jumpTable[i] = ctx.DefineLabel();
-            }
-            il.Emit(OpCodes.Ldarg_1);
-            ctx.Switch(jumpTable);
-            ctx.LoadNullRef();
-            ctx.Return();
-            for (int i = 0; i < jumpTable.Length; i++)
-            {
-                SerializerPair pair = methodPairs[i];
-                ctx.MarkLabel(jumpTable[i]);
-                Type keyType = pair.Type.Type;
-                if (Helpers.IsValueType(keyType))
-                {
-                    il.Emit(OpCodes.Ldarg_2);
-                    il.Emit(OpCodes.Ldarg_3);
-                    il.EmitCall(OpCodes.Call, EmitBoxedSerializer(type, i, keyType, methodPairs, this, ilVersion, assemblyName), null);
-                    ctx.Return();
-                }
-                else
-                {
-                    il.Emit(OpCodes.Ldarg_2);
-                    ctx.CastFromObject(keyType);
-                    il.Emit(OpCodes.Ldarg_3);
-                    il.EmitCall(OpCodes.Call, pair.Deserialize, null);
-                    ctx.Return();
-                }
-            }
-            return ctx;
-        }
-
-        private const int KnownTypes_Array = 1, KnownTypes_Dictionary = 2, KnownTypes_Hashtable = 3, KnownTypes_ArrayCutoff = 20;
-        private void WriteGetKeyImpl(TypeBuilder type, bool hasInheritance, SerializerPair[] methodPairs, Compiler.CompilerContext.ILVersion ilVersion, string assemblyName, out ILGenerator il, out int knownTypesCategory, out FieldBuilder knownTypes, out Type knownTypesLookupType)
-        {
-
-            il = Override(type, "GetKeyImpl");
-            Compiler.CompilerContext ctx = new Compiler.CompilerContext(il, false, false, methodPairs, this, ilVersion, assemblyName, MapType(typeof(System.Type), true), "GetKeyImpl");
-
-
-            if (types.Count <= KnownTypes_ArrayCutoff)
-            {
-                knownTypesCategory = KnownTypes_Array;
-                knownTypesLookupType = MapType(typeof(System.Type[]), true);
-            }
-            else
-            {
-                knownTypesLookupType = MapType(typeof(System.Collections.Generic.Dictionary<System.Type, int>), false);
-
-#if !COREFX
-                if (knownTypesLookupType == null)
-                {
-                    knownTypesLookupType = MapType(typeof(Hashtable), true);
-                    knownTypesCategory = KnownTypes_Hashtable;
-                }
-                else
-#endif
-                {
-                    knownTypesCategory = KnownTypes_Dictionary;
-                }
-            }
-            knownTypes = type.DefineField("knownTypes", knownTypesLookupType, FieldAttributes.Private | FieldAttributes.InitOnly | FieldAttributes.Static);
-
-            switch (knownTypesCategory)
-            {
-                case KnownTypes_Array:
-                    {
-                        il.Emit(OpCodes.Ldsfld, knownTypes);
-                        il.Emit(OpCodes.Ldarg_1);
-                        // note that Array.IndexOf is not supported under CF
-                        il.EmitCall(OpCodes.Callvirt, MapType(typeof(IList)).GetMethod(
-                            "IndexOf", new Type[] { MapType(typeof(object)) }), null);
-                        if (hasInheritance)
-                        {
-                            il.DeclareLocal(MapType(typeof(int))); // loc-0
-                            il.Emit(OpCodes.Dup);
-                            il.Emit(OpCodes.Stloc_0);
-
-                            BasicList getKeyLabels = new BasicList();
-                            int lastKey = -1;
-                            for (int i = 0; i < methodPairs.Length; i++)
-                            {
-                                if (methodPairs[i].MetaKey == methodPairs[i].BaseKey) break;
-                                if (lastKey == methodPairs[i].BaseKey)
-                                {   // add the last label again
-                                    getKeyLabels.Add(getKeyLabels[getKeyLabels.Count - 1]);
-                                }
-                                else
-                                {   // add a new unique label
-                                    getKeyLabels.Add(ctx.DefineLabel());
-                                    lastKey = methodPairs[i].BaseKey;
-                                }
-                            }
-                            Compiler.CodeLabel[] subtypeLabels = new Compiler.CodeLabel[getKeyLabels.Count];
-                            getKeyLabels.CopyTo(subtypeLabels, 0);
-
-                            ctx.Switch(subtypeLabels);
-                            il.Emit(OpCodes.Ldloc_0); // not a sub-type; use the original value
-                            il.Emit(OpCodes.Ret);
-
-                            lastKey = -1;
-                            // now output the different branches per sub-type (not derived type)
-                            for (int i = subtypeLabels.Length - 1; i >= 0; i--)
-                            {
-                                if (lastKey != methodPairs[i].BaseKey)
-                                {
-                                    lastKey = methodPairs[i].BaseKey;
-                                    // find the actual base-index for this base-key (i.e. the index of
-                                    // the base-type)
-                                    int keyIndex = -1;
-                                    for (int j = subtypeLabels.Length; j < methodPairs.Length; j++)
-                                    {
-                                        if (methodPairs[j].BaseKey == lastKey && methodPairs[j].MetaKey == lastKey)
-                                        {
-                                            keyIndex = j;
-                                            break;
-                                        }
-                                    }
-                                    ctx.MarkLabel(subtypeLabels[i]);
-                                    Compiler.CompilerContext.LoadValue(il, keyIndex);
-                                    il.Emit(OpCodes.Ret);
-                                }
-                            }
-                        }
-                        else
-                        {
-                            il.Emit(OpCodes.Ret);
-                        }
-                    }
-                    break;
-                case KnownTypes_Dictionary:
-                    {
-                        LocalBuilder result = il.DeclareLocal(MapType(typeof(int)));
-                        Label otherwise = il.DefineLabel();
-                        il.Emit(OpCodes.Ldsfld, knownTypes);
-                        il.Emit(OpCodes.Ldarg_1);
-                        il.Emit(OpCodes.Ldloca_S, result);
-                        il.EmitCall(OpCodes.Callvirt, knownTypesLookupType.GetMethod("TryGetValue", BindingFlags.Instance | BindingFlags.Public), null);
-                        il.Emit(OpCodes.Brfalse_S, otherwise);
-                        il.Emit(OpCodes.Ldloc_S, result);
-                        il.Emit(OpCodes.Ret);
-                        il.MarkLabel(otherwise);
-                        il.Emit(OpCodes.Ldc_I4_M1);
-                        il.Emit(OpCodes.Ret);
-                    }
-                    break;
-                case KnownTypes_Hashtable:
-                    {
-                        Label otherwise = il.DefineLabel();
-                        il.Emit(OpCodes.Ldsfld, knownTypes);
-                        il.Emit(OpCodes.Ldarg_1);
-                        il.EmitCall(OpCodes.Callvirt, knownTypesLookupType.GetProperty("Item").GetGetMethod(), null);
-                        il.Emit(OpCodes.Dup);
-                        il.Emit(OpCodes.Brfalse_S, otherwise);
-                        if (ilVersion == Compiler.CompilerContext.ILVersion.Net1)
-                        {
-                            il.Emit(OpCodes.Unbox, MapType(typeof(int)));
-                            il.Emit(OpCodes.Ldobj, MapType(typeof(int)));
-                        }
-                        else
-                        {
-                            il.Emit(OpCodes.Unbox_Any, MapType(typeof(int)));
-                        }
-                        il.Emit(OpCodes.Ret);
-                        il.MarkLabel(otherwise);
-                        il.Emit(OpCodes.Pop);
-                        il.Emit(OpCodes.Ldc_I4_M1);
-                        il.Emit(OpCodes.Ret);
-                    }
-                    break;
-                default:
-                    throw new InvalidOperationException();
-            }
-        }
-
-        private void WriteSerializers(CompilerOptions options, string assemblyName, TypeBuilder type, out int index, out bool hasInheritance, out SerializerPair[] methodPairs, out Compiler.CompilerContext.ILVersion ilVersion)
-        {
-            Compiler.CompilerContext ctx;
-
-            index = 0;
-            hasInheritance = false;
-            methodPairs = new SerializerPair[types.Count];
-            foreach (MetaType metaType in types)
-            {
-                MethodBuilder writeMethod = type.DefineMethod("Write"
-#if DEBUG
- + metaType.Type.Name
-#endif
-,
-                    MethodAttributes.Private | MethodAttributes.Static, CallingConventions.Standard,
-                    MapType(typeof(void)), new Type[] { metaType.Type, MapType(typeof(ProtoWriter)) });
-
-                MethodBuilder readMethod = type.DefineMethod("Read"
-#if DEBUG
- + metaType.Type.Name
-#endif
-,
-                    MethodAttributes.Private | MethodAttributes.Static, CallingConventions.Standard,
-                    metaType.Type, new Type[] { metaType.Type, MapType(typeof(ProtoReader)) });
-
-                SerializerPair pair = new SerializerPair(
-                    GetKey(metaType.Type, true, false), GetKey(metaType.Type, true, true), metaType,
-                    writeMethod, readMethod, writeMethod.GetILGenerator(), readMethod.GetILGenerator());
-                methodPairs[index++] = pair;
-                if (pair.MetaKey != pair.BaseKey) hasInheritance = true;
-            }
-
-            if (hasInheritance)
-            {
-                Array.Sort(methodPairs);
-            }
-
-            ilVersion = Compiler.CompilerContext.ILVersion.Net2;
-            if (options.MetaDataVersion == 0x10000)
-            {
-                ilVersion = Compiler.CompilerContext.ILVersion.Net1; // old-school!
-            }
-            for (index = 0; index < methodPairs.Length; index++)
-            {
-                SerializerPair pair = methodPairs[index];
-                ctx = new Compiler.CompilerContext(pair.SerializeBody, true, true, methodPairs, this, ilVersion, assemblyName, pair.Type.Type, "SerializeImpl " + pair.Type.Type.Name);
-                MemberInfo returnType = pair.Deserialize.ReturnType
-#if COREFX
-                    .GetTypeInfo()
-#endif
-                    ;
-                ctx.CheckAccessibility(ref returnType);
-                pair.Type.Serializer.EmitWrite(ctx, ctx.InputValue);
-                ctx.Return();
-
-                ctx = new Compiler.CompilerContext(pair.DeserializeBody, true, false, methodPairs, this, ilVersion, assemblyName, pair.Type.Type, "DeserializeImpl " + pair.Type.Type.Name);
-                pair.Type.Serializer.EmitRead(ctx, ctx.InputValue);
-                if (!pair.Type.Serializer.ReturnsValue)
-                {
-                    ctx.LoadValue(ctx.InputValue);
-                }
-                ctx.Return();
-            }
-        }
-
-        private TypeBuilder WriteBasicTypeModel(CompilerOptions options, string typeName, ModuleBuilder module)
-        {
-            Type baseType = MapType(typeof(TypeModel));
-#if COREFX
-            TypeAttributes typeAttributes = (baseType.GetTypeInfo().Attributes & ~TypeAttributes.Abstract) | TypeAttributes.Sealed;
-#else
-            TypeAttributes typeAttributes = (baseType.Attributes & ~TypeAttributes.Abstract) | TypeAttributes.Sealed;
-#endif
-            if (options.Accessibility == Accessibility.Internal)
-            {
-                typeAttributes &= ~TypeAttributes.Public;
-            }
-
-            TypeBuilder type = module.DefineType(typeName, typeAttributes, baseType);
-            return type;
-        }
-
-        private void WriteAssemblyAttributes(CompilerOptions options, string assemblyName, AssemblyBuilder asm)
-        {
-            if (!string.IsNullOrEmpty(options.TargetFrameworkName))
-            {
-                // get [TargetFramework] from mscorlib/equivalent and burn into the new assembly
-                Type versionAttribType = null;
-                try
-                { // this is best-endeavours only
-                    versionAttribType = GetType("System.Runtime.Versioning.TargetFrameworkAttribute", Helpers.GetAssembly(MapType(typeof(string))));
-                }
-                catch { /* don't stress */ }
-                if (versionAttribType != null)
-                {
-                    PropertyInfo[] props;
-                    object[] propValues;
-                    if (string.IsNullOrEmpty(options.TargetFrameworkDisplayName))
-                    {
-                        props = new PropertyInfo[0];
-                        propValues = new object[0];
-                    }
-                    else
-                    {
-                        props = new PropertyInfo[1] { versionAttribType.GetProperty("FrameworkDisplayName") };
-                        propValues = new object[1] { options.TargetFrameworkDisplayName };
-                    }
-                    CustomAttributeBuilder builder = new CustomAttributeBuilder(
-                        versionAttribType.GetConstructor(new Type[] { MapType(typeof(string)) }),
-                        new object[] { options.TargetFrameworkName },
-                        props,
-                        propValues);
-                    asm.SetCustomAttribute(builder);
-                }
-            }
-
-            // copy assembly:InternalsVisibleTo
-            Type internalsVisibleToAttribType = null;
-
-            try
-            {
-                internalsVisibleToAttribType = MapType(typeof(System.Runtime.CompilerServices.InternalsVisibleToAttribute));
-            }
-            catch { /* best endeavors only */ }
-
-            if (internalsVisibleToAttribType != null)
-            {
-                BasicList internalAssemblies = new BasicList(), consideredAssemblies = new BasicList();
-                foreach (MetaType metaType in types)
-                {
-                    Assembly assembly = Helpers.GetAssembly(metaType.Type);
-                    if (consideredAssemblies.IndexOfReference(assembly) >= 0) continue;
-                    consideredAssemblies.Add(assembly);
-
-                    AttributeMap[] assemblyAttribsMap = AttributeMap.Create(this, assembly);
-                    for (int i = 0; i < assemblyAttribsMap.Length; i++)
-                    {
-
-                        if (assemblyAttribsMap[i].AttributeType != internalsVisibleToAttribType) continue;
-
-                        object privelegedAssemblyObj;
-                        assemblyAttribsMap[i].TryGet("AssemblyName", out privelegedAssemblyObj);
-                        string privelegedAssemblyName = privelegedAssemblyObj as string;
-                        if (privelegedAssemblyName == assemblyName || string.IsNullOrEmpty(privelegedAssemblyName)) continue; // ignore
-
-                        if (internalAssemblies.IndexOfString(privelegedAssemblyName) >= 0) continue; // seen it before
-                        internalAssemblies.Add(privelegedAssemblyName);
-
-                        CustomAttributeBuilder builder = new CustomAttributeBuilder(
-                            internalsVisibleToAttribType.GetConstructor(new Type[] { MapType(typeof(string)) }),
-                            new object[] { privelegedAssemblyName });
-                        asm.SetCustomAttribute(builder);
-                    }
-                }
-            }
-        }
-
-        private static MethodBuilder EmitBoxedSerializer(TypeBuilder type, int i, Type valueType, SerializerPair[] methodPairs, TypeModel model, Compiler.CompilerContext.ILVersion ilVersion, string assemblyName)
-        {
-            MethodInfo dedicated = methodPairs[i].Deserialize;
-            MethodBuilder boxedSerializer = type.DefineMethod("_" + i.ToString(), MethodAttributes.Static, CallingConventions.Standard,
-                model.MapType(typeof(object)), new Type[] { model.MapType(typeof(object)), model.MapType(typeof(ProtoReader)) });
-            Compiler.CompilerContext ctx = new Compiler.CompilerContext(boxedSerializer.GetILGenerator(), true, false, methodPairs, model, ilVersion, assemblyName, model.MapType(typeof(object)), "BoxedSerializer " + valueType.Name);
-            ctx.LoadValue(ctx.InputValue);
-            Compiler.CodeLabel @null = ctx.DefineLabel();
-            ctx.BranchIfFalse(@null, true);
-
-            Type mappedValueType = valueType;
-            ctx.LoadValue(ctx.InputValue);
-            ctx.CastFromObject(mappedValueType);
-            ctx.LoadReaderWriter();
-            ctx.EmitCall(dedicated);
-            ctx.CastToObject(mappedValueType);
-            ctx.Return();
-
-            ctx.MarkLabel(@null);
-            using (Compiler.Local typedVal = new Compiler.Local(ctx, mappedValueType))
-            {
-                // create a new valueType
-                ctx.LoadAddress(typedVal, mappedValueType);
-                ctx.EmitCtor(mappedValueType);
-                ctx.LoadValue(typedVal);
-                ctx.LoadReaderWriter();
-                ctx.EmitCall(dedicated);
-                ctx.CastToObject(mappedValueType);
-                ctx.Return();
-            }
-            return boxedSerializer;
-        }
-
-#endif
-        //internal bool IsDefined(Type type, int fieldNumber)
-        //{
-        //    return FindWithoutAdd(type).IsDefined(fieldNumber);
-        //}
-
-        // note that this is used by some of the unit tests
-        internal bool IsPrepared(Type type)
-        {
-            MetaType meta = FindWithoutAdd(type);
-            return meta != null && meta.IsPrepared();
-        }
-
-        internal EnumSerializer.EnumPair[] GetEnumMap(Type type)
-        {
-            int index = FindOrAddAuto(type, false, false, false);
-            return index < 0 ? null : ((MetaType)types[index]).GetEnumMap();
-        }
-
-        private int metadataTimeoutMilliseconds = 5000;
-        /// <summary>
-        /// The amount of time to wait if there are concurrent metadata access operations
-        /// </summary>
-        public int MetadataTimeoutMilliseconds
-        {
-            get { return metadataTimeoutMilliseconds; }
-            set
-            {
-                if (value <= 0) throw new ArgumentOutOfRangeException("MetadataTimeoutMilliseconds");
-                metadataTimeoutMilliseconds = value;
-            }
-        }
-
-#if DEBUG
-        int lockCount;
-        /// <summary>
-        /// Gets how many times a model lock was taken
-        /// </summary>
-        public int LockCount { get { return lockCount; } }
-#endif
-        internal void TakeLock(ref int opaqueToken)
-        {
-            const string message = "Timeout while inspecting metadata; this may indicate a deadlock. This can often be avoided by preparing necessary serializers during application initialization, rather than allowing multiple threads to perform the initial metadata inspection; please also see the LockContended event";
-            opaqueToken = 0;
-#if PORTABLE
-            if(!Monitor.TryEnter(types, metadataTimeoutMilliseconds)) throw new TimeoutException(message);
-            opaqueToken = Interlocked.CompareExchange(ref contentionCounter, 0, 0); // just fetch current value (starts at 1)
-#elif CF2 || CF35
-            int remaining = metadataTimeoutMilliseconds;
-            bool lockTaken;
-            do {
-                lockTaken = Monitor.TryEnter(types);
-                if(!lockTaken)
-                {
-                    if(remaining <= 0) throw new TimeoutException(message);
-                    remaining -= 50;
-                    Thread.Sleep(50);
-                }
-            } while(!lockTaken);
-            opaqueToken = Interlocked.CompareExchange(ref contentionCounter, 0, 0); // just fetch current value (starts at 1)
-#else
-            if (Monitor.TryEnter(types, metadataTimeoutMilliseconds))
-            {
-                opaqueToken = GetContention(); // just fetch current value (starts at 1)
-            }
-            else
-            {
-                AddContention();
-
-                throw new TimeoutException(message);
-            }
-#endif
-
-#if DEBUG // note that here, through all code-paths: we have the lock
-            lockCount++;
-#endif
-        }
-
-        private int contentionCounter = 1;
-#if PLAT_NO_INTERLOCKED
-        private readonly object contentionLock = new object();
-#endif
-        private int GetContention()
-        {
-#if PLAT_NO_INTERLOCKED
-            lock(contentionLock)
-            {
-                return contentionCounter;
-            }
-#else
-            return Interlocked.CompareExchange(ref contentionCounter, 0, 0);
-#endif
-        }
-        private void AddContention()
-        {
-#if PLAT_NO_INTERLOCKED
-            lock(contentionLock)
-            {
-                contentionCounter++;
-            }
-#else
-            Interlocked.Increment(ref contentionCounter);
-#endif
-        }
-
-        internal void ReleaseLock(int opaqueToken)
-        {
-            if (opaqueToken != 0)
-            {
-                Monitor.Exit(types);
-                if (opaqueToken != GetContention()) // contention-count changes since we looked!
-                {
-                    LockContentedEventHandler handler = LockContended;
-                    if (handler != null)
-                    {
-                        // not hugely elegant, but this is such a far-corner-case that it doesn't need to be slick - I'll settle for cross-platform
-                        string stackTrace;
-                        try
-                        {
-                            throw new ProtoException();
-                        }
-                        catch (Exception ex)
-                        {
-                            stackTrace = ex.StackTrace;
-                        }
-
-                        handler(this, new LockContentedEventArgs(stackTrace));
-                    }
-                }
-            }
-        }
-        /// <summary>
-        /// If a lock-contention is detected, this event signals the *owner* of the lock responsible for the blockage, indicating
-        /// what caused the problem; this is only raised if the lock-owning code successfully completes.
-        /// </summary>
-        public event LockContentedEventHandler LockContended;
-
-        internal void ResolveListTypes(Type type, ref Type itemType, ref Type defaultType)
-        {
-            if (type == null) return;
-            if (Helpers.GetTypeCode(type) != ProtoTypeCode.Unknown) return; // don't try this[type] for inbuilts
-
-            // handle arrays
-            if (type.IsArray)
-            {
-                if (type.GetArrayRank() != 1)
-                {
-                    throw new NotSupportedException("Multi-dimension arrays are supported");
-                }
-                itemType = type.GetElementType();
-                if (itemType == MapType(typeof(byte)))
-                {
-                    defaultType = itemType = null;
-                }
-                else
-                {
-                    defaultType = type;
-                }
-            }
-            else
-            {
-                // if not an array, first check it isn't explicitly opted out
-                if (this[type].IgnoreListHandling) return;
-            }
-
-            // handle lists 
-            if (itemType == null) { itemType = TypeModel.GetListItemType(this, type); }
-
-            // check for nested data (not allowed)
-            if (itemType != null)
-            {
-                Type nestedItemType = null, nestedDefaultType = null;
-                ResolveListTypes(itemType, ref nestedItemType, ref nestedDefaultType);
-                if (nestedItemType != null)
-                {
-                    throw TypeModel.CreateNestedListsNotSupported(type);
-                }
-            }
-
-            if (itemType != null && defaultType == null)
-            {
-#if COREFX || PROFILE259
-				TypeInfo typeInfo = IntrospectionExtensions.GetTypeInfo(type);
-                if (typeInfo.IsClass && !typeInfo.IsAbstract && Helpers.GetConstructor(typeInfo, Helpers.EmptyTypes, true) != null)
-#else
-                if (type.IsClass && !type.IsAbstract && Helpers.GetConstructor(type, Helpers.EmptyTypes, true) != null)
-#endif
-                {
-                    defaultType = type;
-                }
-                if (defaultType == null)
-                {
-#if COREFX || PROFILE259
-					if (typeInfo.IsInterface)
-#else
-                    if (type.IsInterface)
-#endif
-                    {
-
-                        Type[] genArgs;
-#if COREFX || PROFILE259
-                        if (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IDictionary<,>)
-                            && itemType == typeof(System.Collections.Generic.KeyValuePair<,>).MakeGenericType(genArgs = typeInfo.GenericTypeArguments))
-#else
-                        if (type.IsGenericType && type.GetGenericTypeDefinition() == MapType(typeof(System.Collections.Generic.IDictionary<,>))
-                            && itemType == MapType(typeof(System.Collections.Generic.KeyValuePair<,>)).MakeGenericType(genArgs = type.GetGenericArguments()))
-#endif
-                        {
-                            defaultType = MapType(typeof(System.Collections.Generic.Dictionary<,>)).MakeGenericType(genArgs);
-                        }
-                        else
-                        {
-                            defaultType = MapType(typeof(System.Collections.Generic.List<>)).MakeGenericType(itemType);
-                        }
-                    }
-                }
-                // verify that the default type is appropriate
-                if (defaultType != null && !Helpers.IsAssignableFrom(type, defaultType)) { defaultType = null; }
-            }
-        }
-
-        internal string GetSchemaTypeName(Type effectiveType, DataFormat dataFormat, bool asReference, bool dynamicType, ref CommonImports imports)
-        {
-            Type tmp = Helpers.GetUnderlyingType(effectiveType);
-            if (tmp != null) effectiveType = tmp;
-
-            if (effectiveType == this.MapType(typeof(byte[]))) return "bytes";
-
-            WireType wireType;
-            IProtoSerializer ser = ValueMember.TryGetCoreSerializer(this, dataFormat, effectiveType, out wireType, false, false, false, false);
-            if (ser == null)
-            {   // model type
-                if (asReference || dynamicType)
-                {
-                    imports |= CommonImports.Bcl;
-                    return ".bcl.NetObjectProxy";
-                }
-                return this[effectiveType].GetSurrogateOrBaseOrSelf(true).GetSchemaTypeName();
-            }
-            else
-            {
-                if (ser is ParseableSerializer)
-                {
-                    if (asReference) imports |= CommonImports.Bcl;
-                    return asReference ? ".bcl.NetObjectProxy" : "string";
-                }
-
-                switch (Helpers.GetTypeCode(effectiveType))
-                {
-                    case ProtoTypeCode.Boolean: return "bool";
-                    case ProtoTypeCode.Single: return "float";
-                    case ProtoTypeCode.Double: return "double";
-                    case ProtoTypeCode.String:
-                        if (asReference) imports |= CommonImports.Bcl;
-                        return asReference ? ".bcl.NetObjectProxy" : "string";
-                    case ProtoTypeCode.Byte:
-                    case ProtoTypeCode.Char:
-                    case ProtoTypeCode.UInt16:
-                    case ProtoTypeCode.UInt32:
-                        switch (dataFormat)
-                        {
-                            case DataFormat.FixedSize: return "fixed32";
-                            default: return "uint32";
-                        }
-                    case ProtoTypeCode.SByte:
-                    case ProtoTypeCode.Int16:
-                    case ProtoTypeCode.Int32:
-                        switch (dataFormat)
-                        {
-                            case DataFormat.ZigZag: return "sint32";
-                            case DataFormat.FixedSize: return "sfixed32";
-                            default: return "int32";
-                        }
-                    case ProtoTypeCode.UInt64:
-                        switch (dataFormat)
-                        {
-                            case DataFormat.FixedSize: return "fixed64";
-                            default: return "uint64";
-                        }
-                    case ProtoTypeCode.Int64:
-                        switch (dataFormat)
-                        {
-                            case DataFormat.ZigZag: return "sint64";
-                            case DataFormat.FixedSize: return "sfixed64";
-                            default: return "int64";
-                        }
-                    case ProtoTypeCode.DateTime:
-                        switch (dataFormat)
-                        {
-                            case DataFormat.FixedSize: return "sint64";
-                            case DataFormat.WellKnown:
-                                imports |= CommonImports.Timestamp;
-                                return ".google.protobuf.Timestamp";
-                            default:
-                                imports |= CommonImports.Bcl;
-                                return ".bcl.DateTime";
-                        }
-                    case ProtoTypeCode.TimeSpan:
-                        switch (dataFormat)
-                        {
-                            case DataFormat.FixedSize: return "sint64";
-                            case DataFormat.WellKnown:
-                                imports |= CommonImports.Duration;
-                                return ".google.protobuf.Duration";
-                            default:
-                                imports |= CommonImports.Bcl;
-                                return ".bcl.TimeSpan";
-                        }
-                    case ProtoTypeCode.Decimal: imports |= CommonImports.Bcl; return ".bcl.Decimal";
-                    case ProtoTypeCode.Guid: imports |= CommonImports.Bcl; return ".bcl.Guid";
-                    case ProtoTypeCode.Type: return "string";
-                    default: throw new NotSupportedException("No .proto map found for: " + effectiveType.FullName);
-                }
-            }
-
-        }
-
-        /// <summary>
-        /// Designate a factory-method to use to create instances of any type; note that this only affect types seen by the serializer *after* setting the factory.
-        /// </summary>
-        public void SetDefaultFactory(MethodInfo methodInfo)
-        {
-            VerifyFactory(methodInfo, null);
-            defaultFactory = methodInfo;
-        }
-        private MethodInfo defaultFactory;
-
-        internal void VerifyFactory(MethodInfo factory, Type type)
-        {
-            if (factory != null)
-            {
-                if (type != null && Helpers.IsValueType(type)) throw new InvalidOperationException();
-                if (!factory.IsStatic) throw new ArgumentException("A factory-method must be static", "factory");
-                if ((type != null && factory.ReturnType != type) && factory.ReturnType != MapType(typeof(object))) throw new ArgumentException("The factory-method must return object" + (type == null ? "" : (" or " + type.FullName)), "factory");
-
-                if (!CallbackSet.CheckCallbackParameters(this, factory)) throw new ArgumentException("Invalid factory signature in " + factory.DeclaringType.FullName + "." + factory.Name, "factory");
-            }
-        }
-
-    }
-    /// <summary>
-    /// Contains the stack-trace of the owning code when a lock-contention scenario is detected
-    /// </summary>
-    public sealed class LockContentedEventArgs : EventArgs
-    {
-        private readonly string ownerStackTrace;
-        internal LockContentedEventArgs(string ownerStackTrace)
-        {
-            this.ownerStackTrace = ownerStackTrace;
-        }
-
-        /// <summary>
-        /// The stack-trace of the code that owned the lock when a lock-contention scenario occurred
-        /// </summary>
-        public string OwnerStackTrace => ownerStackTrace;
-    }
-    /// <summary>
-    /// Event-type that is raised when a lock-contention scenario is detected
-    /// </summary>
-    public delegate void LockContentedEventHandler(object sender, LockContentedEventArgs args);
-}
-#endif

+ 0 - 97
ThirdParty/protobuf-net/Meta/SubType.cs

@@ -1,97 +0,0 @@
-#if !NO_RUNTIME
-using System;
-using System.Collections.Generic;
-using ProtoBuf.Serializers;
-
-namespace ProtoBuf.Meta
-{
-    /// <summary>
-    /// Represents an inherited type in a type hierarchy.
-    /// </summary>
-    public sealed class SubType
-    {
-        internal sealed class Comparer : System.Collections.IComparer, IComparer<SubType>
-        {
-            public static readonly Comparer Default = new Comparer();
-
-            public int Compare(object x, object y)
-            {
-                return Compare(x as SubType, y as SubType);
-            }
-
-            public int Compare(SubType x, SubType y)
-            {
-                if (ReferenceEquals(x, y)) return 0;
-                if (x == null) return -1;
-                if (y == null) return 1;
-
-                return x.FieldNumber.CompareTo(y.FieldNumber);
-            }
-        }
-
-        private int _fieldNumber;
-
-        /// <summary>
-        /// The field-number that is used to encapsulate the data (as a nested
-        /// message) for the derived dype.
-        /// </summary>
-        public int FieldNumber
-        {
-            get => _fieldNumber;
-            internal set
-            {
-                if (_fieldNumber != value)
-                {
-                    MetaType.AssertValidFieldNumber(value);
-                    ThrowIfFrozen();
-                    _fieldNumber = value;
-                }
-            }
-        }
-
-        private void ThrowIfFrozen()
-        {
-            if (serializer != null) throw new InvalidOperationException("The type cannot be changed once a serializer has been generated");
-        }
-
-
-        /// <summary>
-        /// The sub-type to be considered.
-        /// </summary>
-        public MetaType DerivedType => derivedType;
-        private readonly MetaType derivedType;
-
-        /// <summary>
-        /// Creates a new SubType instance.
-        /// </summary>
-        /// <param name="fieldNumber">The field-number that is used to encapsulate the data (as a nested
-        /// message) for the derived dype.</param>
-        /// <param name="derivedType">The sub-type to be considered.</param>
-        /// <param name="format">Specific encoding style to use; in particular, Grouped can be used to avoid buffering, but is not the default.</param>
-        public SubType(int fieldNumber, MetaType derivedType, DataFormat format)
-        {
-            if (derivedType == null) throw new ArgumentNullException(nameof(derivedType));
-            if (fieldNumber <= 0) throw new ArgumentOutOfRangeException(nameof(fieldNumber));
-            _fieldNumber = fieldNumber;
-            this.derivedType = derivedType;
-            this.dataFormat = format;
-        }
-
-        private readonly DataFormat dataFormat;
-
-        private IProtoSerializer serializer;
-
-        internal IProtoSerializer Serializer => serializer ?? (serializer = BuildSerializer());
-
-        private IProtoSerializer BuildSerializer()
-        {
-            // note the caller here is MetaType.BuildSerializer, which already has the sync-lock
-            WireType wireType = WireType.String;
-            if(dataFormat == DataFormat.Group) wireType = WireType.StartGroup; // only one exception
-            
-            IProtoSerializer ser = new SubItemSerializer(derivedType.Type, derivedType.GetKey(false, false), derivedType, false);
-            return new TagDecorator(_fieldNumber, wireType, false, ser);
-        }
-    }
-}
-#endif

+ 0 - 64
ThirdParty/protobuf-net/Meta/TypeFormatEventArgs.cs

@@ -1,64 +0,0 @@
-using System;
-
-namespace ProtoBuf.Meta
-{
-    /// <summary>
-    /// Event arguments needed to perform type-formatting functions; this could be resolving a Type to a string suitable for serialization, or could
-    /// be requesting a Type from a string. If no changes are made, a default implementation will be used (from the assembly-qualified names).
-    /// </summary>
-    public class TypeFormatEventArgs : EventArgs
-    {
-        private Type type;
-        private string formattedName;
-        private readonly bool typeFixed;
-        /// <summary>
-        /// The type involved in this map; if this is initially null, a Type is expected to be provided for the string in FormattedName.
-        /// </summary>
-        public Type Type
-        {
-            get { return type; }
-            set
-            {
-                if (type != value)
-                {
-                    if (typeFixed) throw new InvalidOperationException("The type is fixed and cannot be changed");
-                    type = value;
-                }
-            }
-        }
-
-        /// <summary>
-        /// The formatted-name involved in this map; if this is initially null, a formatted-name is expected from the type in Type.
-        /// </summary>
-        public string FormattedName
-        {
-            get { return formattedName; }
-            set
-            {
-                if (formattedName != value)
-                {
-                    if (!typeFixed) throw new InvalidOperationException("The formatted-name is fixed and cannot be changed");
-                    formattedName = value;
-                }
-            }
-        }
-
-        internal TypeFormatEventArgs(string formattedName)
-        {
-            if (string.IsNullOrEmpty(formattedName)) throw new ArgumentNullException("formattedName");
-            this.formattedName = formattedName;
-            // typeFixed = false; <== implicit
-        }
-
-        internal TypeFormatEventArgs(Type type)
-        {
-            this.type = type ?? throw new ArgumentNullException(nameof(type));
-            typeFixed = true;
-        }
-    }
-
-    /// <summary>
-    /// Delegate type used to perform type-formatting functions; the sender originates as the type-model.
-    /// </summary>
-    public delegate void TypeFormatEventHandler(object sender, TypeFormatEventArgs args);
-}

+ 0 - 45
ThirdParty/protobuf-net/Meta/TypeModel.InputOutput.cs

@@ -1,45 +0,0 @@
-using System;
-using System.IO;
-
-namespace ProtoBuf.Meta
-{
-    partial class TypeModel :
-        IProtoInput<Stream>,
-        IProtoInput<ArraySegment<byte>>,
-        IProtoInput<byte[]>,
-        IProtoOutput<Stream>
-    {
-        static SerializationContext CreateContext(object userState)
-        {
-            if (userState == null)
-                return SerializationContext.Default;
-            if (userState is SerializationContext ctx)
-                return ctx;
-
-            var obj = new SerializationContext { Context = userState };
-            obj.Freeze();
-            return obj;
-        }
-        T IProtoInput<Stream>.Deserialize<T>(Stream source, T value, object userState)
-            => (T)Deserialize(source, value, typeof(T), CreateContext(userState));
-
-        T IProtoInput<ArraySegment<byte>>.Deserialize<T>(ArraySegment<byte> source, T value, object userState)
-        {
-            using (var ms = new MemoryStream(source.Array, source.Offset, source.Count))
-            {
-                return (T)Deserialize(ms, value, typeof(T), CreateContext(userState));
-            }
-        }
-
-        T IProtoInput<byte[]>.Deserialize<T>(byte[] source, T value, object userState)
-        {
-            using (var ms = new MemoryStream(source))
-            {
-                return (T)Deserialize(ms, value, typeof(T), CreateContext(userState));
-            }
-        }
-
-        void IProtoOutput<Stream>.Serialize<T>(Stream destination, T value, object userState)
-            => Serialize(destination, value, CreateContext(userState));
-    }
-}

+ 0 - 1696
ThirdParty/protobuf-net/Meta/TypeModel.cs

@@ -1,1696 +0,0 @@
-using System;
-using System.IO;
-
-using System.Collections;
-using System.Collections.Generic;
-using System.Reflection;
-
-namespace ProtoBuf.Meta
-{
-    /// <summary>
-    /// Provides protobuf serialization support for a number of types
-    /// </summary>
-    public abstract partial class TypeModel
-    {
-#if COREFX
-        internal TypeInfo MapType(TypeInfo type)
-        {
-            return type;
-        }
-#endif
-
-        /// <summary>
-        /// Should the <c>Kind</c> be included on date/time values?
-        /// </summary>
-        protected internal virtual bool SerializeDateTimeKind() { return false; }
-
-        /// <summary>
-        /// Resolve a System.Type to the compiler-specific type
-        /// </summary>
-        protected internal Type MapType(Type type)
-        {
-            return MapType(type, true);
-        }
-        /// <summary>
-        /// Resolve a System.Type to the compiler-specific type
-        /// </summary>
-        protected internal virtual Type MapType(Type type, bool demand)
-        {
-            return type;
-        }
-
-        private WireType GetWireType(ProtoTypeCode code, DataFormat format, ref Type type, out int modelKey)
-        {
-            modelKey = -1;
-            if (Helpers.IsEnum(type))
-            {
-                modelKey = GetKey(ref type);
-                return WireType.Variant;
-            }
-            switch (code)
-            {
-                case ProtoTypeCode.Int64:
-                case ProtoTypeCode.UInt64:
-                    return format == DataFormat.FixedSize ? WireType.Fixed64 : WireType.Variant;
-                case ProtoTypeCode.Int16:
-                case ProtoTypeCode.Int32:
-                case ProtoTypeCode.UInt16:
-                case ProtoTypeCode.UInt32:
-                case ProtoTypeCode.Boolean:
-                case ProtoTypeCode.SByte:
-                case ProtoTypeCode.Byte:
-                case ProtoTypeCode.Char:
-                    return format == DataFormat.FixedSize ? WireType.Fixed32 : WireType.Variant;
-                case ProtoTypeCode.Double:
-                    return WireType.Fixed64;
-                case ProtoTypeCode.Single:
-                    return WireType.Fixed32;
-                case ProtoTypeCode.String:
-                case ProtoTypeCode.DateTime:
-                case ProtoTypeCode.Decimal:
-                case ProtoTypeCode.ByteArray:
-                case ProtoTypeCode.TimeSpan:
-                case ProtoTypeCode.Guid:
-                case ProtoTypeCode.Uri:
-                    return WireType.String;
-            }
-
-            if ((modelKey = GetKey(ref type)) >= 0)
-            {
-                return WireType.String;
-            }
-            return WireType.None;
-        }
-
-
-        /// <summary>
-        /// This is the more "complete" version of Serialize, which handles single instances of mapped types.
-        /// The value is written as a complete field, including field-header and (for sub-objects) a
-        /// length-prefix
-        /// In addition to that, this provides support for:
-        ///  - basic values; individual int / string / Guid / etc
-        ///  - IEnumerable sequences of any type handled by TrySerializeAuxiliaryType
-        ///  
-        /// </summary>
-        internal bool TrySerializeAuxiliaryType(ProtoWriter writer, Type type, DataFormat format, int tag, object value, bool isInsideList, object parentList)
-        {
-            if (type == null) { type = value.GetType(); }
-
-            ProtoTypeCode typecode = Helpers.GetTypeCode(type);
-            // note the "ref type" here normalizes against proxies
-            WireType wireType = GetWireType(typecode, format, ref type, out int modelKey);
-
-
-            if (modelKey >= 0)
-            {   // write the header, but defer to the model
-                if (Helpers.IsEnum(type))
-                { // no header
-                    Serialize(modelKey, value, writer);
-                    return true;
-                }
-                else
-                {
-                    ProtoWriter.WriteFieldHeader(tag, wireType, writer);
-                    switch (wireType)
-                    {
-                        case WireType.None:
-                            throw ProtoWriter.CreateException(writer);
-                        case WireType.StartGroup:
-                        case WireType.String:
-                            // needs a wrapping length etc
-                            SubItemToken token = ProtoWriter.StartSubItem(value, writer);
-                            Serialize(modelKey, value, writer);
-                            ProtoWriter.EndSubItem(token, writer);
-                            return true;
-                        default:
-                            Serialize(modelKey, value, writer);
-                            return true;
-                    }
-                }
-            }
-
-            if (wireType != WireType.None)
-            {
-                ProtoWriter.WriteFieldHeader(tag, wireType, writer);
-            }
-            switch (typecode)
-            {
-                case ProtoTypeCode.Int16: ProtoWriter.WriteInt16((short)value, writer); return true;
-                case ProtoTypeCode.Int32: ProtoWriter.WriteInt32((int)value, writer); return true;
-                case ProtoTypeCode.Int64: ProtoWriter.WriteInt64((long)value, writer); return true;
-                case ProtoTypeCode.UInt16: ProtoWriter.WriteUInt16((ushort)value, writer); return true;
-                case ProtoTypeCode.UInt32: ProtoWriter.WriteUInt32((uint)value, writer); return true;
-                case ProtoTypeCode.UInt64: ProtoWriter.WriteUInt64((ulong)value, writer); return true;
-                case ProtoTypeCode.Boolean: ProtoWriter.WriteBoolean((bool)value, writer); return true;
-                case ProtoTypeCode.SByte: ProtoWriter.WriteSByte((sbyte)value, writer); return true;
-                case ProtoTypeCode.Byte: ProtoWriter.WriteByte((byte)value, writer); return true;
-                case ProtoTypeCode.Char: ProtoWriter.WriteUInt16((ushort)(char)value, writer); return true;
-                case ProtoTypeCode.Double: ProtoWriter.WriteDouble((double)value, writer); return true;
-                case ProtoTypeCode.Single: ProtoWriter.WriteSingle((float)value, writer); return true;
-                case ProtoTypeCode.DateTime:
-                    if (SerializeDateTimeKind())
-                        BclHelpers.WriteDateTimeWithKind((DateTime)value, writer);
-                    else
-                        BclHelpers.WriteDateTime((DateTime)value, writer);
-                    return true;
-                case ProtoTypeCode.Decimal: BclHelpers.WriteDecimal((decimal)value, writer); return true;
-                case ProtoTypeCode.String: ProtoWriter.WriteString((string)value, writer); return true;
-                case ProtoTypeCode.ByteArray: ProtoWriter.WriteBytes((byte[])value, writer); return true;
-                case ProtoTypeCode.TimeSpan: BclHelpers.WriteTimeSpan((TimeSpan)value, writer); return true;
-                case ProtoTypeCode.Guid: BclHelpers.WriteGuid((Guid)value, writer); return true;
-                case ProtoTypeCode.Uri: ProtoWriter.WriteString(((Uri)value).OriginalString, writer); return true;
-            }
-
-            // by now, we should have covered all the simple cases; if we wrote a field-header, we have
-            // forgotten something!
-            Helpers.DebugAssert(wireType == WireType.None);
-
-            // now attempt to handle sequences (including arrays and lists)
-            if (value is IEnumerable sequence)
-            {
-                if (isInsideList) throw CreateNestedListsNotSupported(parentList?.GetType());
-                foreach (object item in sequence)
-                {
-                    if (item == null) { throw new NullReferenceException(); }
-                    if (!TrySerializeAuxiliaryType(writer, null, format, tag, item, true, sequence))
-                    {
-                        ThrowUnexpectedType(item.GetType());
-                    }
-                }
-                return true;
-            }
-            return false;
-        }
-
-        private void SerializeCore(ProtoWriter writer, object value)
-        {
-            if (value == null) throw new ArgumentNullException(nameof(value));
-            Type type = value.GetType();
-            int key = GetKey(ref type);
-            if (key >= 0)
-            {
-                Serialize(key, value, writer);
-            }
-            else if (!TrySerializeAuxiliaryType(writer, type, DataFormat.Default, Serializer.ListItemTag, value, false, null))
-            {
-                ThrowUnexpectedType(type);
-            }
-        }
-
-        /// <summary>
-        /// Writes a protocol-buffer representation of the given instance to the supplied stream.
-        /// </summary>
-        /// <param name="value">The existing instance to be serialized (cannot be null).</param>
-        /// <param name="dest">The destination stream to write to.</param>
-        public void Serialize(Stream dest, object value)
-        {
-            Serialize(dest, value, null);
-        }
-
-        /// <summary>
-        /// Writes a protocol-buffer representation of the given instance to the supplied stream.
-        /// </summary>
-        /// <param name="value">The existing instance to be serialized (cannot be null).</param>
-        /// <param name="dest">The destination stream to write to.</param>
-        /// <param name="context">Additional information about this serialization operation.</param>
-        public void Serialize(Stream dest, object value, SerializationContext context)
-        {
-            using (ProtoWriter writer = ProtoWriter.Create(dest, this, context))
-            {
-                writer.SetRootObject(value);
-                SerializeCore(writer, value);
-                writer.Close();
-            }
-        }
-
-        /// <summary>
-        /// Writes a protocol-buffer representation of the given instance to the supplied writer.
-        /// </summary>
-        /// <param name="value">The existing instance to be serialized (cannot be null).</param>
-        /// <param name="dest">The destination writer to write to.</param>
-        public void Serialize(ProtoWriter dest, object value)
-        {
-            if (dest == null) throw new ArgumentNullException(nameof(dest));
-            dest.CheckDepthFlushlock();
-            dest.SetRootObject(value);
-            SerializeCore(dest, value);
-            dest.CheckDepthFlushlock();
-            ProtoWriter.Flush(dest);
-        }
-
-        /// <summary>
-        /// Applies a protocol-buffer stream to an existing instance (or null), using length-prefixed
-        /// data - useful with network IO.
-        /// </summary>
-        /// <param name="type">The type being merged.</param>
-        /// <param name="value">The existing instance to be modified (can be null).</param>
-        /// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
-        /// <param name="style">How to encode the length prefix.</param>
-        /// <param name="fieldNumber">The tag used as a prefix to each record (only used with base-128 style prefixes).</param>
-        /// <returns>The updated instance; this may be different to the instance argument if
-        /// either the original instance was null, or the stream defines a known sub-type of the
-        /// original instance.</returns>
-        public object DeserializeWithLengthPrefix(Stream source, object value, Type type, PrefixStyle style, int fieldNumber)
-            => DeserializeWithLengthPrefix(source, value, type, style, fieldNumber, null, out long bytesRead);
-
-        /// <summary>
-        /// Applies a protocol-buffer stream to an existing instance (or null), using length-prefixed
-        /// data - useful with network IO.
-        /// </summary>
-        /// <param name="type">The type being merged.</param>
-        /// <param name="value">The existing instance to be modified (can be null).</param>
-        /// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
-        /// <param name="style">How to encode the length prefix.</param>
-        /// <param name="expectedField">The tag used as a prefix to each record (only used with base-128 style prefixes).</param>
-        /// <param name="resolver">Used to resolve types on a per-field basis.</param>
-        /// <returns>The updated instance; this may be different to the instance argument if
-        /// either the original instance was null, or the stream defines a known sub-type of the
-        /// original instance.</returns>
-        public object DeserializeWithLengthPrefix(Stream source, object value, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver)
-            => DeserializeWithLengthPrefix(source, value, type, style, expectedField, resolver, out long bytesRead);
-
-        /// <summary>
-        /// Applies a protocol-buffer stream to an existing instance (or null), using length-prefixed
-        /// data - useful with network IO.
-        /// </summary>
-        /// <param name="type">The type being merged.</param>
-        /// <param name="value">The existing instance to be modified (can be null).</param>
-        /// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
-        /// <param name="style">How to encode the length prefix.</param>
-        /// <param name="expectedField">The tag used as a prefix to each record (only used with base-128 style prefixes).</param>
-        /// <param name="resolver">Used to resolve types on a per-field basis.</param>
-        /// <param name="bytesRead">Returns the number of bytes consumed by this operation (includes length-prefix overheads and any skipped data).</param>
-        /// <returns>The updated instance; this may be different to the instance argument if
-        /// either the original instance was null, or the stream defines a known sub-type of the
-        /// original instance.</returns>
-        public object DeserializeWithLengthPrefix(Stream source, object value, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver, out int bytesRead)
-        {
-            object result = DeserializeWithLengthPrefix(source, value, type, style, expectedField, resolver, out long bytesRead64, out bool haveObject, null);
-            bytesRead = checked((int)bytesRead64);
-            return result;
-        }
-
-        /// <summary>
-        /// Applies a protocol-buffer stream to an existing instance (or null), using length-prefixed
-        /// data - useful with network IO.
-        /// </summary>
-        /// <param name="type">The type being merged.</param>
-        /// <param name="value">The existing instance to be modified (can be null).</param>
-        /// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
-        /// <param name="style">How to encode the length prefix.</param>
-        /// <param name="expectedField">The tag used as a prefix to each record (only used with base-128 style prefixes).</param>
-        /// <param name="resolver">Used to resolve types on a per-field basis.</param>
-        /// <param name="bytesRead">Returns the number of bytes consumed by this operation (includes length-prefix overheads and any skipped data).</param>
-        /// <returns>The updated instance; this may be different to the instance argument if
-        /// either the original instance was null, or the stream defines a known sub-type of the
-        /// original instance.</returns>
-        public object DeserializeWithLengthPrefix(Stream source, object value, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver, out long bytesRead) => DeserializeWithLengthPrefix(source, value, type, style, expectedField, resolver, out bytesRead, out bool haveObject, null);
-
-        private object DeserializeWithLengthPrefix(Stream source, object value, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver, out long bytesRead, out bool haveObject, SerializationContext context)
-        {
-            haveObject = false;
-            bool skip;
-            long len;
-            bytesRead = 0;
-            if (type == null && (style != PrefixStyle.Base128 || resolver == null))
-            {
-                throw new InvalidOperationException("A type must be provided unless base-128 prefixing is being used in combination with a resolver");
-            }
-            do
-            {
-
-                bool expectPrefix = expectedField > 0 || resolver != null;
-                len = ProtoReader.ReadLongLengthPrefix(source, expectPrefix, style, out int actualField, out int tmpBytesRead);
-                if (tmpBytesRead == 0) return value;
-                bytesRead += tmpBytesRead;
-                if (len < 0) return value;
-
-                switch (style)
-                {
-                    case PrefixStyle.Base128:
-                        if (expectPrefix && expectedField == 0 && type == null && resolver != null)
-                        {
-                            type = resolver(actualField);
-                            skip = type == null;
-                        }
-                        else { skip = expectedField != actualField; }
-                        break;
-                    default:
-                        skip = false;
-                        break;
-                }
-
-                if (skip)
-                {
-                    if (len == long.MaxValue) throw new InvalidOperationException();
-                    ProtoReader.Seek(source, len, null);
-                    bytesRead += len;
-                }
-            } while (skip);
-
-            ProtoReader reader = null;
-            try
-            {
-                reader = ProtoReader.Create(source, this, context, len);
-                int key = GetKey(ref type);
-                if (key >= 0 && !Helpers.IsEnum(type))
-                {
-                    value = Deserialize(key, value, reader);
-                }
-                else
-                {
-                    if (!(TryDeserializeAuxiliaryType(reader, DataFormat.Default, Serializer.ListItemTag, type, ref value, true, false, true, false, null) || len == 0))
-                    {
-                        TypeModel.ThrowUnexpectedType(type); // throws
-                    }
-                }
-                bytesRead += reader.LongPosition;
-                haveObject = true;
-                return value;
-            }
-            finally
-            {
-                ProtoReader.Recycle(reader);
-            }
-        }
-
-        /// <summary>
-        /// Reads a sequence of consecutive length-prefixed items from a stream, using
-        /// either base-128 or fixed-length prefixes. Base-128 prefixes with a tag
-        /// are directly comparable to serializing multiple items in succession
-        /// (use the <see cref="Serializer.ListItemTag"/> tag to emulate the implicit behavior
-        /// when serializing a list/array). When a tag is
-        /// specified, any records with different tags are silently omitted. The
-        /// tag is ignored. The tag is ignores for fixed-length prefixes.
-        /// </summary>
-        /// <param name="source">The binary stream containing the serialized records.</param>
-        /// <param name="style">The prefix style used in the data.</param>
-        /// <param name="expectedField">The tag of records to return (if non-positive, then no tag is
-        /// expected and all records are returned).</param>
-        /// <param name="resolver">On a field-by-field basis, the type of object to deserialize (can be null if "type" is specified). </param>
-        /// <param name="type">The type of object to deserialize (can be null if "resolver" is specified).</param>
-        /// <returns>The sequence of deserialized objects.</returns>
-        public IEnumerable DeserializeItems(System.IO.Stream source, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver)
-        {
-            return DeserializeItems(source, type, style, expectedField, resolver, null);
-        }
-        /// <summary>
-        /// Reads a sequence of consecutive length-prefixed items from a stream, using
-        /// either base-128 or fixed-length prefixes. Base-128 prefixes with a tag
-        /// are directly comparable to serializing multiple items in succession
-        /// (use the <see cref="Serializer.ListItemTag"/> tag to emulate the implicit behavior
-        /// when serializing a list/array). When a tag is
-        /// specified, any records with different tags are silently omitted. The
-        /// tag is ignored. The tag is ignores for fixed-length prefixes.
-        /// </summary>
-        /// <param name="source">The binary stream containing the serialized records.</param>
-        /// <param name="style">The prefix style used in the data.</param>
-        /// <param name="expectedField">The tag of records to return (if non-positive, then no tag is
-        /// expected and all records are returned).</param>
-        /// <param name="resolver">On a field-by-field basis, the type of object to deserialize (can be null if "type" is specified). </param>
-        /// <param name="type">The type of object to deserialize (can be null if "resolver" is specified).</param>
-        /// <returns>The sequence of deserialized objects.</returns>
-        /// <param name="context">Additional information about this serialization operation.</param>
-        public IEnumerable DeserializeItems(System.IO.Stream source, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver, SerializationContext context)
-        {
-            return new DeserializeItemsIterator(this, source, type, style, expectedField, resolver, context);
-        }
-
-        /// <summary>
-        /// Reads a sequence of consecutive length-prefixed items from a stream, using
-        /// either base-128 or fixed-length prefixes. Base-128 prefixes with a tag
-        /// are directly comparable to serializing multiple items in succession
-        /// (use the <see cref="Serializer.ListItemTag"/> tag to emulate the implicit behavior
-        /// when serializing a list/array). When a tag is
-        /// specified, any records with different tags are silently omitted. The
-        /// tag is ignored. The tag is ignores for fixed-length prefixes.
-        /// </summary>
-        /// <typeparam name="T">The type of object to deserialize.</typeparam>
-        /// <param name="source">The binary stream containing the serialized records.</param>
-        /// <param name="style">The prefix style used in the data.</param>
-        /// <param name="expectedField">The tag of records to return (if non-positive, then no tag is
-        /// expected and all records are returned).</param>
-        /// <returns>The sequence of deserialized objects.</returns>
-        public IEnumerable<T> DeserializeItems<T>(Stream source, PrefixStyle style, int expectedField)
-        {
-            return DeserializeItems<T>(source, style, expectedField, null);
-        }
-        /// <summary>
-        /// Reads a sequence of consecutive length-prefixed items from a stream, using
-        /// either base-128 or fixed-length prefixes. Base-128 prefixes with a tag
-        /// are directly comparable to serializing multiple items in succession
-        /// (use the <see cref="Serializer.ListItemTag"/> tag to emulate the implicit behavior
-        /// when serializing a list/array). When a tag is
-        /// specified, any records with different tags are silently omitted. The
-        /// tag is ignored. The tag is ignores for fixed-length prefixes.
-        /// </summary>
-        /// <typeparam name="T">The type of object to deserialize.</typeparam>
-        /// <param name="source">The binary stream containing the serialized records.</param>
-        /// <param name="style">The prefix style used in the data.</param>
-        /// <param name="expectedField">The tag of records to return (if non-positive, then no tag is
-        /// expected and all records are returned).</param>
-        /// <returns>The sequence of deserialized objects.</returns>
-        /// <param name="context">Additional information about this serialization operation.</param>
-        public IEnumerable<T> DeserializeItems<T>(Stream source, PrefixStyle style, int expectedField, SerializationContext context)
-        {
-            return new DeserializeItemsIterator<T>(this, source, style, expectedField, context);
-        }
-
-        private sealed class DeserializeItemsIterator<T> : DeserializeItemsIterator,
-            IEnumerator<T>,
-            IEnumerable<T>
-        {
-            IEnumerator<T> IEnumerable<T>.GetEnumerator() { return this; }
-            public new T Current { get { return (T)base.Current; } }
-            void IDisposable.Dispose() { }
-            public DeserializeItemsIterator(TypeModel model, Stream source, PrefixStyle style, int expectedField, SerializationContext context)
-                : base(model, source, model.MapType(typeof(T)), style, expectedField, null, context) { }
-        }
-
-        private class DeserializeItemsIterator : IEnumerator, IEnumerable
-        {
-            IEnumerator IEnumerable.GetEnumerator() { return this; }
-            private bool haveObject;
-            private object current;
-            public bool MoveNext()
-            {
-                if (haveObject)
-                {
-                    current = model.DeserializeWithLengthPrefix(source, null, type, style, expectedField, resolver, out long bytesRead, out haveObject, context);
-                }
-                return haveObject;
-            }
-            void IEnumerator.Reset() { throw new NotSupportedException(); }
-            public object Current { get { return current; } }
-            private readonly Stream source;
-            private readonly Type type;
-            private readonly PrefixStyle style;
-            private readonly int expectedField;
-            private readonly Serializer.TypeResolver resolver;
-            private readonly TypeModel model;
-            private readonly SerializationContext context;
-            public DeserializeItemsIterator(TypeModel model, Stream source, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver, SerializationContext context)
-            {
-                haveObject = true;
-                this.source = source;
-                this.type = type;
-                this.style = style;
-                this.expectedField = expectedField;
-                this.resolver = resolver;
-                this.model = model;
-                this.context = context;
-            }
-        }
-
-        /// <summary>
-        /// Writes a protocol-buffer representation of the given instance to the supplied stream,
-        /// with a length-prefix. This is useful for socket programming,
-        /// as DeserializeWithLengthPrefix can be used to read the single object back
-        /// from an ongoing stream.
-        /// </summary>
-        /// <param name="type">The type being serialized.</param>
-        /// <param name="value">The existing instance to be serialized (cannot be null).</param>
-        /// <param name="style">How to encode the length prefix.</param>
-        /// <param name="dest">The destination stream to write to.</param>
-        /// <param name="fieldNumber">The tag used as a prefix to each record (only used with base-128 style prefixes).</param>
-        public void SerializeWithLengthPrefix(Stream dest, object value, Type type, PrefixStyle style, int fieldNumber)
-        {
-            SerializeWithLengthPrefix(dest, value, type, style, fieldNumber, null);
-        }
-
-        /// <summary>
-        /// Writes a protocol-buffer representation of the given instance to the supplied stream,
-        /// with a length-prefix. This is useful for socket programming,
-        /// as DeserializeWithLengthPrefix can be used to read the single object back
-        /// from an ongoing stream.
-        /// </summary>
-        /// <param name="type">The type being serialized.</param>
-        /// <param name="value">The existing instance to be serialized (cannot be null).</param>
-        /// <param name="style">How to encode the length prefix.</param>
-        /// <param name="dest">The destination stream to write to.</param>
-        /// <param name="fieldNumber">The tag used as a prefix to each record (only used with base-128 style prefixes).</param>
-        /// <param name="context">Additional information about this serialization operation.</param>
-        public void SerializeWithLengthPrefix(Stream dest, object value, Type type, PrefixStyle style, int fieldNumber, SerializationContext context)
-        {
-            if (type == null)
-            {
-                if (value == null) throw new ArgumentNullException(nameof(value));
-                type = MapType(value.GetType());
-            }
-            int key = GetKey(ref type);
-            using (ProtoWriter writer = ProtoWriter.Create(dest, this, context))
-            {
-                switch (style)
-                {
-                    case PrefixStyle.None:
-                        Serialize(key, value, writer);
-                        break;
-                    case PrefixStyle.Base128:
-                    case PrefixStyle.Fixed32:
-                    case PrefixStyle.Fixed32BigEndian:
-                        ProtoWriter.WriteObject(value, key, writer, style, fieldNumber);
-                        break;
-                    default:
-                        throw new ArgumentOutOfRangeException("style");
-                }
-                writer.Close();
-            }
-        }
-        /// <summary>
-        /// Applies a protocol-buffer stream to an existing instance (which may be null).
-        /// </summary>
-        /// <param name="type">The type (including inheritance) to consider.</param>
-        /// <param name="value">The existing instance to be modified (can be null).</param>
-        /// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
-        /// <returns>The updated instance; this may be different to the instance argument if
-        /// either the original instance was null, or the stream defines a known sub-type of the
-        /// original instance.</returns>
-        public object Deserialize(Stream source, object value, Type type)
-        {
-            return Deserialize(source, value, type, null);
-        }
-
-        /// <summary>
-        /// Applies a protocol-buffer stream to an existing instance (which may be null).
-        /// </summary>
-        /// <param name="type">The type (including inheritance) to consider.</param>
-        /// <param name="value">The existing instance to be modified (can be null).</param>
-        /// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
-        /// <returns>The updated instance; this may be different to the instance argument if
-        /// either the original instance was null, or the stream defines a known sub-type of the
-        /// original instance.</returns>
-        /// <param name="context">Additional information about this serialization operation.</param>
-        public object Deserialize(Stream source, object value, Type type, SerializationContext context)
-        {
-            bool autoCreate = PrepareDeserialize(value, ref type);
-            ProtoReader reader = null;
-            try
-            {
-                reader = ProtoReader.Create(source, this, context, ProtoReader.TO_EOF);
-                if (value != null) reader.SetRootObject(value);
-                object obj = DeserializeCore(reader, type, value, autoCreate);
-                reader.CheckFullyConsumed();
-                return obj;
-            }
-            finally
-            {
-                ProtoReader.Recycle(reader);
-            }
-        }
-
-        private bool PrepareDeserialize(object value, ref Type type)
-        {
-            if (type == null)
-            {
-                if (value == null)
-                {
-                    throw new ArgumentNullException(nameof(type));
-                }
-                else
-                {
-                    type = MapType(value.GetType());
-                }
-            }
-
-            bool autoCreate = true;
-            Type underlyingType = Helpers.GetUnderlyingType(type);
-            if (underlyingType != null)
-            {
-                type = underlyingType;
-                autoCreate = false;
-            }
-            return autoCreate;
-        }
-
-        /// <summary>
-        /// Applies a protocol-buffer stream to an existing instance (which may be null).
-        /// </summary>
-        /// <param name="type">The type (including inheritance) to consider.</param>
-        /// <param name="value">The existing instance to be modified (can be null).</param>
-        /// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
-        /// <param name="length">The number of bytes to consume.</param>
-        /// <returns>The updated instance; this may be different to the instance argument if
-        /// either the original instance was null, or the stream defines a known sub-type of the
-        /// original instance.</returns>
-        public object Deserialize(Stream source, object value, System.Type type, int length)
-            => Deserialize(source, value, type, length, null);
-
-        /// <summary>
-        /// Applies a protocol-buffer stream to an existing instance (which may be null).
-        /// </summary>
-        /// <param name="type">The type (including inheritance) to consider.</param>
-        /// <param name="value">The existing instance to be modified (can be null).</param>
-        /// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
-        /// <param name="length">The number of bytes to consume.</param>
-        /// <returns>The updated instance; this may be different to the instance argument if
-        /// either the original instance was null, or the stream defines a known sub-type of the
-        /// original instance.</returns>
-        public object Deserialize(Stream source, object value, System.Type type, long length)
-            => Deserialize(source, value, type, length, null);
-
-        /// <summary>
-        /// Applies a protocol-buffer stream to an existing instance (which may be null).
-        /// </summary>
-        /// <param name="type">The type (including inheritance) to consider.</param>
-        /// <param name="value">The existing instance to be modified (can be null).</param>
-        /// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
-        /// <param name="length">The number of bytes to consume (or -1 to read to the end of the stream).</param>
-        /// <returns>The updated instance; this may be different to the instance argument if
-        /// either the original instance was null, or the stream defines a known sub-type of the
-        /// original instance.</returns>
-        /// <param name="context">Additional information about this serialization operation.</param>
-        public object Deserialize(Stream source, object value, System.Type type, int length, SerializationContext context)
-            => Deserialize(source, value, type, length == int.MaxValue ? long.MaxValue : (long)length, context);
-
-        /// <summary>
-        /// Applies a protocol-buffer stream to an existing instance (which may be null).
-        /// </summary>
-        /// <param name="type">The type (including inheritance) to consider.</param>
-        /// <param name="value">The existing instance to be modified (can be null).</param>
-        /// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
-        /// <param name="length">The number of bytes to consume (or -1 to read to the end of the stream).</param>
-        /// <returns>The updated instance; this may be different to the instance argument if
-        /// either the original instance was null, or the stream defines a known sub-type of the
-        /// original instance.</returns>
-        /// <param name="context">Additional information about this serialization operation.</param>
-        public object Deserialize(Stream source, object value, System.Type type, long length, SerializationContext context)
-        {
-            bool autoCreate = PrepareDeserialize(value, ref type);
-            ProtoReader reader = null;
-            try
-            {
-                reader = ProtoReader.Create(source, this, context, length);
-                if (value != null) reader.SetRootObject(value);
-                object obj = DeserializeCore(reader, type, value, autoCreate);
-                reader.CheckFullyConsumed();
-                return obj;
-            }
-            finally
-            {
-                ProtoReader.Recycle(reader);
-            }
-        }
-
-        /// <summary>
-        /// Applies a protocol-buffer reader to an existing instance (which may be null).
-        /// </summary>
-        /// <param name="type">The type (including inheritance) to consider.</param>
-        /// <param name="value">The existing instance to be modified (can be null).</param>
-        /// <param name="source">The reader to apply to the instance (cannot be null).</param>
-        /// <returns>The updated instance; this may be different to the instance argument if
-        /// either the original instance was null, or the stream defines a known sub-type of the
-        /// original instance.</returns>
-        public object Deserialize(ProtoReader source, object value, System.Type type)
-        {
-            if (source == null) throw new ArgumentNullException("source");
-            bool autoCreate = PrepareDeserialize(value, ref type);
-            if (value != null) source.SetRootObject(value);
-            object obj = DeserializeCore(source, type, value, autoCreate);
-            source.CheckFullyConsumed();
-            return obj;
-        }
-
-        private object DeserializeCore(ProtoReader reader, Type type, object value, bool noAutoCreate)
-        {
-            int key = GetKey(ref type);
-            if (key >= 0 && !Helpers.IsEnum(type))
-            {
-                return Deserialize(key, value, reader);
-            }
-            // this returns true to say we actively found something, but a value is assigned either way (or throws)
-            TryDeserializeAuxiliaryType(reader, DataFormat.Default, Serializer.ListItemTag, type, ref value, true, false, noAutoCreate, false, null);
-            return value;
-        }
-
-#if COREFX
-        private static readonly System.Reflection.TypeInfo ilist = typeof(IList).GetTypeInfo();
-#else
-        private static readonly System.Type ilist = typeof(IList);
-#endif
-        internal static MethodInfo ResolveListAdd(TypeModel model, Type listType, Type itemType, out bool isList)
-        {
-#if COREFX || PROFILE259
-			TypeInfo listTypeInfo = listType.GetTypeInfo();
-#else
-            Type listTypeInfo = listType;
-#endif
-#if PROFILE259
-			isList = model.MapType(ilist).GetTypeInfo().IsAssignableFrom(listTypeInfo);
-#else
-            isList = model.MapType(ilist).IsAssignableFrom(listTypeInfo);
-#endif
-            Type[] types = { itemType };
-            MethodInfo add = Helpers.GetInstanceMethod(listTypeInfo, "Add", types);
-
-#if !NO_GENERICS
-            if (add == null)
-            {   // fallback: look for ICollection<T>'s Add(typedObject) method
-
-                bool forceList = listTypeInfo.IsInterface &&
-                    model.MapType(typeof(System.Collections.Generic.IEnumerable<>)).MakeGenericType(types)
-#if COREFX || PROFILE259
-					.GetTypeInfo()
-#endif
-                    .IsAssignableFrom(listTypeInfo);
-
-#if COREFX || PROFILE259
-				TypeInfo constuctedListType = typeof(System.Collections.Generic.ICollection<>).MakeGenericType(types).GetTypeInfo();
-#else
-                Type constuctedListType = model.MapType(typeof(System.Collections.Generic.ICollection<>)).MakeGenericType(types);
-#endif
-                if (forceList || constuctedListType.IsAssignableFrom(listTypeInfo))
-                {
-                    add = Helpers.GetInstanceMethod(constuctedListType, "Add", types);
-                }
-            }
-
-            if (add == null)
-            {
-
-#if COREFX || PROFILE259
-				foreach (Type tmpType in listTypeInfo.ImplementedInterfaces)
-#else
-                foreach (Type interfaceType in listTypeInfo.GetInterfaces())
-#endif
-                {
-#if COREFX || PROFILE259
-					TypeInfo interfaceType = tmpType.GetTypeInfo();
-#endif
-                    if (interfaceType.Name == "IProducerConsumerCollection`1" && interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition().FullName == "System.Collections.Concurrent.IProducerConsumerCollection`1")
-                    {
-                        add = Helpers.GetInstanceMethod(interfaceType, "TryAdd", types);
-                        if (add != null) break;
-                    }
-                }
-            }
-#endif
-
-            if (add == null)
-            {   // fallback: look for a public list.Add(object) method
-                types[0] = model.MapType(typeof(object));
-                add = Helpers.GetInstanceMethod(listTypeInfo, "Add", types);
-            }
-            if (add == null && isList)
-            {   // fallback: look for IList's Add(object) method
-                add = Helpers.GetInstanceMethod(model.MapType(ilist), "Add", types);
-            }
-            return add;
-        }
-        internal static Type GetListItemType(TypeModel model, Type listType)
-        {
-            Helpers.DebugAssert(listType != null);
-
-#if PROFILE259
-			TypeInfo listTypeInfo = listType.GetTypeInfo();
-            if (listType == typeof(string) || listType.IsArray
-                || !typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(listTypeInfo)) return null;
-#else
-            if (listType == model.MapType(typeof(string)) || listType.IsArray
-                || !model.MapType(typeof(IEnumerable)).IsAssignableFrom(listType)) return null;
-#endif
-
-            BasicList candidates = new BasicList();
-#if PROFILE259
-			foreach (MethodInfo method in listType.GetRuntimeMethods())
-#else
-            foreach (MethodInfo method in listType.GetMethods())
-#endif
-            {
-                if (method.IsStatic || method.Name != "Add") continue;
-                ParameterInfo[] parameters = method.GetParameters();
-                Type paramType;
-                if (parameters.Length == 1 && !candidates.Contains(paramType = parameters[0].ParameterType))
-                {
-                    candidates.Add(paramType);
-                }
-            }
-
-            string name = listType.Name;
-            bool isQueueStack = name != null && (name.IndexOf("Queue") >= 0 || name.IndexOf("Stack") >= 0);
-
-            if (!isQueueStack)
-            {
-                TestEnumerableListPatterns(model, candidates, listType);
-#if PROFILE259
-				foreach (Type iType in listTypeInfo.ImplementedInterfaces)
-                {
-                    TestEnumerableListPatterns(model, candidates, iType);
-                }
-#else
-                foreach (Type iType in listType.GetInterfaces())
-                {
-                    TestEnumerableListPatterns(model, candidates, iType);
-                }
-#endif
-            }
-
-#if PROFILE259
-			// more convenient GetProperty overload not supported on all platforms
-			foreach (PropertyInfo indexer in listType.GetRuntimeProperties())
-            {
-                if (indexer.Name != "Item" || candidates.Contains(indexer.PropertyType)) continue;
-                ParameterInfo[] args = indexer.GetIndexParameters();
-                if (args.Length != 1 || args[0].ParameterType != typeof(int)) continue;
-                MethodInfo getter = indexer.GetMethod;
-                if (getter == null || getter.IsStatic) continue;
-                candidates.Add(indexer.PropertyType);
-            }
-#else
-            // more convenient GetProperty overload not supported on all platforms
-            foreach (PropertyInfo indexer in listType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
-            {
-                if (indexer.Name != "Item" || candidates.Contains(indexer.PropertyType)) continue;
-                ParameterInfo[] args = indexer.GetIndexParameters();
-                if (args.Length != 1 || args[0].ParameterType != model.MapType(typeof(int))) continue;
-                candidates.Add(indexer.PropertyType);
-            }
-#endif
-
-            switch (candidates.Count)
-            {
-                case 0:
-                    return null;
-                case 1:
-                    if ((Type)candidates[0] == listType) return null; // recursive
-                    return (Type)candidates[0];
-                case 2:
-                    if ((Type)candidates[0] != listType && CheckDictionaryAccessors(model, (Type)candidates[0], (Type)candidates[1])) return (Type)candidates[0];
-                    if ((Type)candidates[1] != listType && CheckDictionaryAccessors(model, (Type)candidates[1], (Type)candidates[0])) return (Type)candidates[1];
-                    break;
-            }
-
-            return null;
-        }
-
-        private static void TestEnumerableListPatterns(TypeModel model, BasicList candidates, Type iType)
-        {
-
-#if COREFX || PROFILE259
-			TypeInfo iTypeInfo = iType.GetTypeInfo();
-            if (iTypeInfo.IsGenericType)
-            {
-                Type typeDef = iTypeInfo.GetGenericTypeDefinition();
-                if(
-                   typeDef == model.MapType(typeof(System.Collections.Generic.IEnumerable<>))
-                || typeDef == model.MapType(typeof(System.Collections.Generic.ICollection<>))
-                || typeDef.GetTypeInfo().FullName == "System.Collections.Concurrent.IProducerConsumerCollection`1")
-                {
-                        
-                    Type[] iTypeArgs = iTypeInfo.GenericTypeArguments;
-                    if (!candidates.Contains(iTypeArgs[0]))
-                    {
-                        candidates.Add(iTypeArgs[0]);
-                    }
-                }
-            }
-#else
-            if (iType.IsGenericType)
-            {
-                Type typeDef = iType.GetGenericTypeDefinition();
-                if (typeDef == model.MapType(typeof(System.Collections.Generic.IEnumerable<>))
-                    || typeDef == model.MapType(typeof(System.Collections.Generic.ICollection<>))
-                    || typeDef.FullName == "System.Collections.Concurrent.IProducerConsumerCollection`1")
-                {
-                    Type[] iTypeArgs = iType.GetGenericArguments();
-                    if (!candidates.Contains(iTypeArgs[0]))
-                    {
-                        candidates.Add(iTypeArgs[0]);
-                    }
-                }
-            }
-#endif
-        }
-
-        private static bool CheckDictionaryAccessors(TypeModel model, Type pair, Type value)
-        {
-#if COREFX || PROFILE259
-			TypeInfo finalType = pair.GetTypeInfo();
-            return finalType.IsGenericType && finalType.GetGenericTypeDefinition() == typeof(System.Collections.Generic.KeyValuePair<,>)
-                && finalType.GenericTypeArguments[1] == value;
-#else
-            return pair.IsGenericType && pair.GetGenericTypeDefinition() == model.MapType(typeof(System.Collections.Generic.KeyValuePair<,>))
-                && pair.GetGenericArguments()[1] == value;
-#endif
-        }
-
-        private bool TryDeserializeList(TypeModel model, ProtoReader reader, DataFormat format, int tag, Type listType, Type itemType, ref object value)
-        {
-            MethodInfo addMethod = TypeModel.ResolveListAdd(model, listType, itemType, out bool isList);
-            if (addMethod == null) throw new NotSupportedException("Unknown list variant: " + listType.FullName);
-            bool found = false;
-            object nextItem = null;
-            IList list = value as IList;
-            object[] args = isList ? null : new object[1];
-            BasicList arraySurrogate = listType.IsArray ? new BasicList() : null;
-
-            while (TryDeserializeAuxiliaryType(reader, format, tag, itemType, ref nextItem, true, true, true, true, value ?? listType))
-            {
-                found = true;
-                if (value == null && arraySurrogate == null)
-                {
-                    value = CreateListInstance(listType, itemType);
-                    list = value as IList;
-                }
-                if (list != null)
-                {
-                    list.Add(nextItem);
-                }
-                else if (arraySurrogate != null)
-                {
-                    arraySurrogate.Add(nextItem);
-                }
-                else
-                {
-                    args[0] = nextItem;
-                    addMethod.Invoke(value, args);
-                }
-                nextItem = null;
-            }
-            if (arraySurrogate != null)
-            {
-                Array newArray;
-                if (value != null)
-                {
-                    if (arraySurrogate.Count == 0)
-                    {   // we'll stay with what we had, thanks
-                    }
-                    else
-                    {
-                        Array existing = (Array)value;
-                        newArray = Array.CreateInstance(itemType, existing.Length + arraySurrogate.Count);
-                        Array.Copy(existing, newArray, existing.Length);
-                        arraySurrogate.CopyTo(newArray, existing.Length);
-                        value = newArray;
-                    }
-                }
-                else
-                {
-                    newArray = Array.CreateInstance(itemType, arraySurrogate.Count);
-                    arraySurrogate.CopyTo(newArray, 0);
-                    value = newArray;
-                }
-            }
-            return found;
-        }
-
-        private static object CreateListInstance(Type listType, Type itemType)
-        {
-            Type concreteListType = listType;
-
-            if (listType.IsArray)
-            {
-                return Array.CreateInstance(itemType, 0);
-            }
-
-#if COREFX || PROFILE259
-			TypeInfo listTypeInfo = listType.GetTypeInfo();
-            if (!listTypeInfo.IsClass || listTypeInfo.IsAbstract ||
-                Helpers.GetConstructor(listTypeInfo, Helpers.EmptyTypes, true) == null)
-#else
-            if (!listType.IsClass || listType.IsAbstract ||
-                Helpers.GetConstructor(listType, Helpers.EmptyTypes, true) == null)
-#endif
-            {
-                string fullName;
-                bool handled = false;
-#if COREFX || PROFILE259
-				if (listTypeInfo.IsInterface &&
-#else
-                if (listType.IsInterface &&
-#endif
-                    (fullName = listType.FullName) != null && fullName.IndexOf("Dictionary") >= 0) // have to try to be frugal here...
-                {
-#if COREFX || PROFILE259
-					TypeInfo finalType = listType.GetTypeInfo();
-                    if (finalType.IsGenericType && finalType.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IDictionary<,>))
-                    {
-                        Type[] genericTypes = listType.GenericTypeArguments;
-                        concreteListType = typeof(System.Collections.Generic.Dictionary<,>).MakeGenericType(genericTypes);
-                        handled = true;
-                    }
-#else
-                    if (listType.IsGenericType && listType.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IDictionary<,>))
-                    {
-                        Type[] genericTypes = listType.GetGenericArguments();
-                        concreteListType = typeof(System.Collections.Generic.Dictionary<,>).MakeGenericType(genericTypes);
-                        handled = true;
-                    }
-#endif
-
-#if !PORTABLE && !COREFX && !PROFILE259
-                    if (!handled && listType == typeof(IDictionary))
-                    {
-                        concreteListType = typeof(Hashtable);
-                        handled = true;
-                    }
-#endif
-                }
-
-                if (!handled)
-                {
-                    concreteListType = typeof(System.Collections.Generic.List<>).MakeGenericType(itemType);
-                    handled = true;
-                }
-
-#if !PORTABLE && !COREFX && !PROFILE259
-                if (!handled)
-                {
-                    concreteListType = typeof(ArrayList);
-                    handled = true;
-                }
-#endif
-            }
-            return Activator.CreateInstance(concreteListType);
-        }
-
-        /// <summary>
-        /// This is the more "complete" version of Deserialize, which handles single instances of mapped types.
-        /// The value is read as a complete field, including field-header and (for sub-objects) a
-        /// length-prefix..kmc  
-        /// 
-        /// In addition to that, this provides support for:
-        ///  - basic values; individual int / string / Guid / etc
-        ///  - IList sets of any type handled by TryDeserializeAuxiliaryType
-        /// </summary>
-        internal bool TryDeserializeAuxiliaryType(ProtoReader reader, DataFormat format, int tag, Type type, ref object value, bool skipOtherFields, bool asListItem, bool autoCreate, bool insideList, object parentListOrType)
-        {
-            if (type == null) throw new ArgumentNullException(nameof(type));
-            Type itemType = null;
-            ProtoTypeCode typecode = Helpers.GetTypeCode(type);
-            WireType wiretype = GetWireType(typecode, format, ref type, out int modelKey);
-
-            bool found = false;
-            if (wiretype == WireType.None)
-            {
-                itemType = GetListItemType(this, type);
-                if (itemType == null && type.IsArray && type.GetArrayRank() == 1 && type != typeof(byte[]))
-                {
-                    itemType = type.GetElementType();
-                }
-                if (itemType != null)
-                {
-                    if (insideList) throw TypeModel.CreateNestedListsNotSupported((parentListOrType as Type) ?? (parentListOrType?.GetType()));
-                    found = TryDeserializeList(this, reader, format, tag, type, itemType, ref value);
-                    if (!found && autoCreate)
-                    {
-                        value = CreateListInstance(type, itemType);
-                    }
-                    return found;
-                }
-
-                // otherwise, not a happy bunny...
-                ThrowUnexpectedType(type);
-            }
-
-            // to treat correctly, should read all values
-
-            while (true)
-            {
-                // for convenience (re complex exit conditions), additional exit test here:
-                // if we've got the value, are only looking for one, and we aren't a list - then exit
-                if (found && asListItem) break;
-
-
-                // read the next item
-                int fieldNumber = reader.ReadFieldHeader();
-                if (fieldNumber <= 0) break;
-                if (fieldNumber != tag)
-                {
-                    if (skipOtherFields)
-                    {
-                        reader.SkipField();
-                        continue;
-                    }
-                    throw ProtoReader.AddErrorData(new InvalidOperationException(
-                        "Expected field " + tag.ToString() + ", but found " + fieldNumber.ToString()), reader);
-                }
-                found = true;
-                reader.Hint(wiretype); // handle signed data etc
-
-                if (modelKey >= 0)
-                {
-                    switch (wiretype)
-                    {
-                        case WireType.String:
-                        case WireType.StartGroup:
-                            SubItemToken token = ProtoReader.StartSubItem(reader);
-                            value = Deserialize(modelKey, value, reader);
-                            ProtoReader.EndSubItem(token, reader);
-                            continue;
-                        default:
-                            value = Deserialize(modelKey, value, reader);
-                            continue;
-                    }
-                }
-                switch (typecode)
-                {
-                    case ProtoTypeCode.Int16: value = reader.ReadInt16(); continue;
-                    case ProtoTypeCode.Int32: value = reader.ReadInt32(); continue;
-                    case ProtoTypeCode.Int64: value = reader.ReadInt64(); continue;
-                    case ProtoTypeCode.UInt16: value = reader.ReadUInt16(); continue;
-                    case ProtoTypeCode.UInt32: value = reader.ReadUInt32(); continue;
-                    case ProtoTypeCode.UInt64: value = reader.ReadUInt64(); continue;
-                    case ProtoTypeCode.Boolean: value = reader.ReadBoolean(); continue;
-                    case ProtoTypeCode.SByte: value = reader.ReadSByte(); continue;
-                    case ProtoTypeCode.Byte: value = reader.ReadByte(); continue;
-                    case ProtoTypeCode.Char: value = (char)reader.ReadUInt16(); continue;
-                    case ProtoTypeCode.Double: value = reader.ReadDouble(); continue;
-                    case ProtoTypeCode.Single: value = reader.ReadSingle(); continue;
-                    case ProtoTypeCode.DateTime: value = BclHelpers.ReadDateTime(reader); continue;
-                    case ProtoTypeCode.Decimal: value = BclHelpers.ReadDecimal(reader); continue;
-                    case ProtoTypeCode.String: value = reader.ReadString(); continue;
-                    case ProtoTypeCode.ByteArray: value = ProtoReader.AppendBytes((byte[])value, reader); continue;
-                    case ProtoTypeCode.TimeSpan: value = BclHelpers.ReadTimeSpan(reader); continue;
-                    case ProtoTypeCode.Guid: value = BclHelpers.ReadGuid(reader); continue;
-                    case ProtoTypeCode.Uri: value = new Uri(reader.ReadString(), UriKind.RelativeOrAbsolute); continue;
-                }
-
-            }
-            if (!found && !asListItem && autoCreate)
-            {
-                if (type != typeof(string))
-                {
-                    value = Activator.CreateInstance(type);
-                }
-            }
-            return found;
-        }
-
-#if !NO_RUNTIME
-        /// <summary>
-        /// Creates a new runtime model, to which the caller
-        /// can add support for a range of types. A model
-        /// can be used "as is", or can be compiled for
-        /// optimal performance.
-        /// </summary>
-        [Obsolete("Please use RuntimeTypeModel.Create", false)]
-        public static RuntimeTypeModel Create()
-        {
-            return RuntimeTypeModel.Create();
-        }
-#endif
-
-        /// <summary>
-        /// Applies common proxy scenarios, resolving the actual type to consider
-        /// </summary>
-        protected internal static Type ResolveProxies(Type type)
-        {
-            if (type == null) return null;
-#if !NO_GENERICS
-            if (type.IsGenericParameter) return null;
-            // Nullable<T>
-            Type tmp = Helpers.GetUnderlyingType(type);
-            if (tmp != null) return tmp;
-#endif
-
-#if !CF
-            // EF POCO
-            string fullName = type.FullName;
-            if (fullName != null && fullName.StartsWith("System.Data.Entity.DynamicProxies."))
-            {
-#if COREFX || PROFILE259
-				return type.GetTypeInfo().BaseType;
-#else
-                return type.BaseType;
-#endif
-            }
-
-            // NHibernate
-#if PROFILE259
-			IEnumerable<Type> interfaces = type.GetTypeInfo().ImplementedInterfaces;
-#else
-            Type[] interfaces = type.GetInterfaces();
-#endif
-            foreach (Type t in interfaces)
-            {
-                switch (t.FullName)
-                {
-                    case "NHibernate.Proxy.INHibernateProxy":
-                    case "NHibernate.Proxy.DynamicProxy.IProxy":
-                    case "NHibernate.Intercept.IFieldInterceptorAccessor":
-#if COREFX || PROFILE259
-						return type.GetTypeInfo().BaseType;
-#else
-                        return type.BaseType;
-#endif
-                }
-            }
-#endif
-            return null;
-        }
-
-        /// <summary>
-        /// Indicates whether the supplied type is explicitly modelled by the model
-        /// </summary>
-        public bool IsDefined(Type type) => GetKey(ref type) >= 0;
-
-        readonly Dictionary<Type, KnownTypeKey> knownKeys = new Dictionary<Type, KnownTypeKey>();
-
-        // essentially just a ValueTuple<int,Type> - I just don't want the extra dependency
-        private readonly struct KnownTypeKey
-        {
-            public KnownTypeKey(Type type, int key)
-            {
-                Type = type;
-                Key = key;
-            }
-
-            public int Key { get; }
-
-            public Type Type { get; }
-        }
-
-        /// <summary>
-        /// Provides the key that represents a given type in the current model.
-        /// The type is also normalized for proxies at the same time.
-        /// </summary>
-        protected internal int GetKey(ref Type type)
-        {
-            if (type == null) return -1;
-            int key;
-            lock (knownKeys)
-            {
-                if (knownKeys.TryGetValue(type, out var tuple))
-                {
-                    // the type can be changed via ResolveProxies etc
-#if DEBUG
-                    var actualKey = GetKeyImpl(type);
-                    if(actualKey != tuple.Key)
-                    {
-                        throw new InvalidOperationException(
-                            $"Key cache failure; got {tuple.Key} instead of {actualKey} for '{type.Name}'");
-                    }
-#endif
-                    type = tuple.Type;
-                    return tuple.Key;
-                }
-            }
-            key = GetKeyImpl(type);
-            Type originalType = type;
-            if (key < 0)
-            {
-                Type normalized = ResolveProxies(type);
-                if (normalized != null && normalized != type)
-                {
-                    type = normalized; // hence ref
-                    key = GetKeyImpl(type);
-                }
-            }
-            lock (knownKeys)
-            {
-                knownKeys[originalType] = new KnownTypeKey(type, key);
-            }
-            return key;
-        }
-
-        /// <summary>
-        /// Advertise that a type's key can have changed
-        /// </summary>
-        internal void ResetKeyCache()
-        {
-            // clear *everything* (think: multi-level - can be many descendents)
-            lock(knownKeys)
-            {
-                knownKeys.Clear();
-            }
-        }
-
-        /// <summary>
-        /// Provides the key that represents a given type in the current model.
-        /// </summary>
-        protected abstract int GetKeyImpl(Type type);
-        /// <summary>
-        /// Writes a protocol-buffer representation of the given instance to the supplied stream.
-        /// </summary>
-        /// <param name="key">Represents the type (including inheritance) to consider.</param>
-        /// <param name="value">The existing instance to be serialized (cannot be null).</param>
-        /// <param name="dest">The destination stream to write to.</param>
-        protected internal abstract void Serialize(int key, object value, ProtoWriter dest);
-
-        /// <summary>
-        /// Applies a protocol-buffer stream to an existing instance (which may be null).
-        /// </summary>
-        /// <param name="key">Represents the type (including inheritance) to consider.</param>
-        /// <param name="value">The existing instance to be modified (can be null).</param>
-        /// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
-        /// <returns>The updated instance; this may be different to the instance argument if
-        /// either the original instance was null, or the stream defines a known sub-type of the
-        /// original instance.</returns>
-        protected internal abstract object Deserialize(int key, object value, ProtoReader source);
-
-        //internal ProtoSerializer Create(IProtoSerializer head)
-        //{
-        //    return new RuntimeSerializer(head, this);
-        //}
-        //internal ProtoSerializer Compile
-
-        /// <summary>
-        /// Indicates the type of callback to be used
-        /// </summary>
-        protected internal enum CallbackType
-        {
-            /// <summary>
-            /// Invoked before an object is serialized
-            /// </summary>
-            BeforeSerialize,
-            /// <summary>
-            /// Invoked after an object is serialized
-            /// </summary>
-            AfterSerialize,
-            /// <summary>
-            /// Invoked before an object is deserialized (or when a new instance is created)
-            /// </summary>            
-            BeforeDeserialize,
-            /// <summary>
-            /// Invoked after an object is deserialized
-            /// </summary>
-            AfterDeserialize
-        }
-
-        /// <summary>
-        /// Create a deep clone of the supplied instance; any sub-items are also cloned.
-        /// </summary>
-        public object DeepClone(object value)
-        {
-            if (value == null) return null;
-            Type type = value.GetType();
-            int key = GetKey(ref type);
-
-            if (key >= 0 && !Helpers.IsEnum(type))
-            {
-                using (MemoryStream ms = new MemoryStream())
-                {
-                    using (ProtoWriter writer = ProtoWriter.Create(ms, this, null))
-                    {
-                        writer.SetRootObject(value);
-                        Serialize(key, value, writer);
-                        writer.Close();
-                    }
-                    ms.Position = 0;
-                    ProtoReader reader = null;
-                    try
-                    {
-                        reader = ProtoReader.Create(ms, this, null, ProtoReader.TO_EOF);
-                        return Deserialize(key, null, reader);
-                    }
-                    finally
-                    {
-                        ProtoReader.Recycle(reader);
-                    }
-                }
-            }
-            if (type == typeof(byte[]))
-            {
-                byte[] orig = (byte[])value, clone = new byte[orig.Length];
-                Buffer.BlockCopy(orig, 0, clone, 0, orig.Length);
-                return clone;
-            }
-            else if (GetWireType(Helpers.GetTypeCode(type), DataFormat.Default, ref type, out int modelKey) != WireType.None && modelKey < 0)
-            {   // immutable; just return the original value
-                return value;
-            }
-            using (MemoryStream ms = new MemoryStream())
-            {
-                using (ProtoWriter writer = ProtoWriter.Create(ms, this, null))
-                {
-                    if (!TrySerializeAuxiliaryType(writer, type, DataFormat.Default, Serializer.ListItemTag, value, false, null)) ThrowUnexpectedType(type);
-                    writer.Close();
-                }
-                ms.Position = 0;
-                ProtoReader reader = null;
-                try
-                {
-                    reader = ProtoReader.Create(ms, this, null, ProtoReader.TO_EOF);
-                    value = null; // start from scratch!
-                    TryDeserializeAuxiliaryType(reader, DataFormat.Default, Serializer.ListItemTag, type, ref value, true, false, true, false, null);
-                    return value;
-                }
-                finally
-                {
-                    ProtoReader.Recycle(reader);
-                }
-            }
-        }
-
-        /// <summary>
-        /// Indicates that while an inheritance tree exists, the exact type encountered was not
-        /// specified in that hierarchy and cannot be processed.
-        /// </summary>
-        protected internal static void ThrowUnexpectedSubtype(Type expected, Type actual)
-        {
-            if (expected != TypeModel.ResolveProxies(actual))
-            {
-                throw new InvalidOperationException("Unexpected sub-type: " + actual.FullName);
-            }
-        }
-
-        /// <summary>
-        /// Indicates that the given type was not expected, and cannot be processed.
-        /// </summary>
-        protected internal static void ThrowUnexpectedType(Type type)
-        {
-            string fullName = type == null ? "(unknown)" : type.FullName;
-
-            if (type != null)
-            {
-                Type baseType = type
-#if COREFX || PROFILE259
-					.GetTypeInfo()
-#endif
-                    .BaseType;
-                if (baseType != null && baseType
-#if COREFX || PROFILE259
-					.GetTypeInfo()
-#endif
-                    .IsGenericType && baseType.GetGenericTypeDefinition().Name == "GeneratedMessage`2")
-                {
-                    throw new InvalidOperationException(
-                        "Are you mixing protobuf-net and protobuf-csharp-port? See https://stackoverflow.com/q/11564914/23354; type: " + fullName);
-                }
-            }
-
-            throw new InvalidOperationException("Type is not expected, and no contract can be inferred: " + fullName);
-        }
-
-        internal static Exception CreateNestedListsNotSupported(Type type)
-        {
-            return new NotSupportedException("Nested or jagged lists and arrays are not supported: " + (type?.FullName ?? "(null)"));
-        }
-        
-        /// <summary>
-        /// Indicates that the given type cannot be constructed; it may still be possible to 
-        /// deserialize into existing instances.
-        /// </summary>
-        public static void ThrowCannotCreateInstance(Type type)
-        {
-            throw new ProtoException("No parameterless constructor found for " + (type?.FullName ?? "(null)"));
-        }
-
-        internal static string SerializeType(TypeModel model, System.Type type)
-        {
-            if (model != null)
-            {
-                TypeFormatEventHandler handler = model.DynamicTypeFormatting;
-                if (handler != null)
-                {
-                    TypeFormatEventArgs args = new TypeFormatEventArgs(type);
-                    handler(model, args);
-                    if (!string.IsNullOrEmpty(args.FormattedName)) return args.FormattedName;
-                }
-            }
-            return type.AssemblyQualifiedName;
-        }
-
-        internal static Type DeserializeType(TypeModel model, string value)
-        {
-
-            if (model != null)
-            {
-                TypeFormatEventHandler handler = model.DynamicTypeFormatting;
-                if (handler != null)
-                {
-                    TypeFormatEventArgs args = new TypeFormatEventArgs(value);
-                    handler(model, args);
-                    if (args.Type != null) return args.Type;
-                }
-            }
-            return Type.GetType(value);
-        }
-
-        /// <summary>
-        /// Returns true if the type supplied is either a recognised contract type,
-        /// or a *list* of a recognised contract type. 
-        /// </summary>
-        /// <remarks>Note that primitives always return false, even though the engine
-        /// will, if forced, try to serialize such</remarks>
-        /// <returns>True if this type is recognised as a serializable entity, else false</returns>
-        public bool CanSerializeContractType(Type type) => CanSerialize(type, false, true, true);
-
-        /// <summary>
-        /// Returns true if the type supplied is a basic type with inbuilt handling,
-        /// a recognised contract type, or a *list* of a basic / contract type. 
-        /// </summary>
-        public bool CanSerialize(Type type) => CanSerialize(type, true, true, true);
-
-        /// <summary>
-        /// Returns true if the type supplied is a basic type with inbuilt handling,
-        /// or a *list* of a basic type with inbuilt handling
-        /// </summary>
-        public bool CanSerializeBasicType(Type type) => CanSerialize(type, true, false, true);
-
-        private bool CanSerialize(Type type, bool allowBasic, bool allowContract, bool allowLists)
-        {
-            if (type == null) throw new ArgumentNullException(nameof(type));
-            Type tmp = Helpers.GetUnderlyingType(type);
-            if (tmp != null) type = tmp;
-
-            // is it a basic type?
-            ProtoTypeCode typeCode = Helpers.GetTypeCode(type);
-            switch (typeCode)
-            {
-                case ProtoTypeCode.Empty:
-                case ProtoTypeCode.Unknown:
-                    break;
-                default:
-                    return allowBasic; // well-known basic type
-            }
-            int modelKey = GetKey(ref type);
-            if (modelKey >= 0) return allowContract; // known contract type
-
-            // is it a list?
-            if (allowLists)
-            {
-                Type itemType = null;
-                if (type.IsArray)
-                {   // note we don't need to exclude byte[], as that is handled by GetTypeCode already
-                    if (type.GetArrayRank() == 1) itemType = type.GetElementType();
-                }
-                else
-                {
-                    itemType = GetListItemType(this, type);
-                }
-                if (itemType != null) return CanSerialize(itemType, allowBasic, allowContract, false);
-            }
-            return false;
-        }
-
-        /// <summary>
-        /// Suggest a .proto definition for the given type
-        /// </summary>
-        /// <param name="type">The type to generate a .proto definition for, or <c>null</c> to generate a .proto that represents the entire model</param>
-        /// <returns>The .proto definition as a string</returns>
-        public virtual string GetSchema(Type type) => GetSchema(type, ProtoSyntax.Proto2);
-
-        /// <summary>
-        /// Suggest a .proto definition for the given type
-        /// </summary>
-        /// <param name="type">The type to generate a .proto definition for, or <c>null</c> to generate a .proto that represents the entire model</param>
-        /// <returns>The .proto definition as a string</returns>
-        /// <param name="syntax">The .proto syntax to use for the operation</param>
-        public virtual string GetSchema(Type type, ProtoSyntax syntax)
-        {
-            throw new NotSupportedException();
-        }
-
-        /// <summary>
-        /// Used to provide custom services for writing and parsing type names when using dynamic types. Both parsing and formatting
-        /// are provided on a single API as it is essential that both are mapped identically at all times.
-        /// </summary>
-        public event TypeFormatEventHandler DynamicTypeFormatting;
-
-#if PLAT_BINARYFORMATTER && !(COREFX || PROFILE259)
-        /// <summary>
-        /// Creates a new IFormatter that uses protocol-buffer [de]serialization.
-        /// </summary>
-        /// <returns>A new IFormatter to be used during [de]serialization.</returns>
-        /// <param name="type">The type of object to be [de]deserialized by the formatter.</param>
-        public System.Runtime.Serialization.IFormatter CreateFormatter(Type type)
-        {
-            return new Formatter(this, type);
-        }
-
-        internal sealed class Formatter : System.Runtime.Serialization.IFormatter
-        {
-            private readonly TypeModel model;
-            private readonly Type type;
-            internal Formatter(TypeModel model, Type type)
-            {
-                this.model = model ?? throw new ArgumentNullException(nameof(model));
-                this.type = type ?? throw new ArgumentNullException(nameof(type));
-            }
-            private System.Runtime.Serialization.SerializationBinder binder;
-            public System.Runtime.Serialization.SerializationBinder Binder
-            {
-                get { return binder; }
-                set { binder = value; }
-            }
-
-            private System.Runtime.Serialization.StreamingContext context;
-            public System.Runtime.Serialization.StreamingContext Context
-            {
-                get { return context; }
-                set { context = value; }
-            }
-
-            public object Deserialize(Stream source)
-            {
-                return model.Deserialize(source, null, type, (long)-1, Context);
-            }
-
-            public void Serialize(Stream destination, object graph)
-            {
-                model.Serialize(destination, graph, Context);
-            }
-
-            private System.Runtime.Serialization.ISurrogateSelector surrogateSelector;
-            public System.Runtime.Serialization.ISurrogateSelector SurrogateSelector
-            {
-                get { return surrogateSelector; }
-                set { surrogateSelector = value; }
-            }
-        }
-#endif
-
-#if DEBUG // this is used by some unit tests only, to ensure no buffering when buffering is disabled
-        private bool forwardsOnly;
-        /// <summary>
-        /// If true, buffering of nested objects is disabled
-        /// </summary>
-        public bool ForwardsOnly
-        {
-            get { return forwardsOnly; }
-            set { forwardsOnly = value; }
-        }
-#endif
-
-        internal virtual Type GetType(string fullName, Assembly context)
-        {
-            return ResolveKnownType(fullName, this, context);
-        }
-
-        [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
-        internal static Type ResolveKnownType(string name, TypeModel model, Assembly assembly)
-        {
-            if (string.IsNullOrEmpty(name)) return null;
-            try
-            {
-                Type type = Type.GetType(name);
-
-                if (type != null) return type;
-            }
-            catch { }
-            try
-            {
-                int i = name.IndexOf(',');
-                string fullName = (i > 0 ? name.Substring(0, i) : name).Trim();
-#if !(COREFX || PROFILE259)
-                if (assembly == null) assembly = Assembly.GetCallingAssembly();
-#endif
-                Type type = assembly?.GetType(fullName);
-                if (type != null) return type;
-            }
-            catch { }
-            return null;
-        }
-    }
-}

+ 0 - 855
ThirdParty/protobuf-net/Meta/ValueMember.cs

@@ -1,855 +0,0 @@
-#if !NO_RUNTIME
-using System;
-
-using ProtoBuf.Serializers;
-using System.Globalization;
-using System.Collections.Generic;
-
-#if PROFILE259
-using System.Reflection;
-using System.Linq;
-#else
-using System.Reflection;
-#endif
-
-namespace ProtoBuf.Meta
-{
-    /// <summary>
-    /// Represents a member (property/field) that is mapped to a protobuf field
-    /// </summary>
-    public class ValueMember
-    {
-        private int _fieldNumber;
-        /// <summary>
-        /// The number that identifies this member in a protobuf stream
-        /// </summary>
-        public int FieldNumber
-        {
-            get => _fieldNumber;
-            internal set
-            {
-                if (_fieldNumber != value)
-                {
-                    MetaType.AssertValidFieldNumber(value);
-                    ThrowIfFrozen();
-                    _fieldNumber = value;
-                }
-            }
-        }
-
-        private readonly MemberInfo originalMember;
-        private MemberInfo backingMember;
-        /// <summary>
-        /// Gets the member (field/property) which this member relates to.
-        /// </summary>
-        public MemberInfo Member { get { return originalMember; } }
-        /// <summary>
-        /// Gets the backing member (field/property) which this member relates to
-        /// </summary>
-        public MemberInfo BackingMember
-        {
-            get { return backingMember; }
-            set
-            {
-                if (backingMember != value)
-                {
-                    ThrowIfFrozen();
-                    backingMember = value;
-                }
-            }
-        }
-
-        private readonly Type parentType, itemType, defaultType, memberType;
-        private object defaultValue;
-
-        /// <summary>
-        /// Within a list / array / etc, the type of object for each item in the list (especially useful with ArrayList)
-        /// </summary>
-        public Type ItemType => itemType;
-
-        /// <summary>
-        /// The underlying type of the member
-        /// </summary>
-        public Type MemberType => memberType;
-
-        /// <summary>
-        /// For abstract types (IList etc), the type of concrete object to create (if required)
-        /// </summary>
-        public Type DefaultType => defaultType;
-
-        /// <summary>
-        /// The type the defines the member
-        /// </summary>
-        public Type ParentType => parentType;
-
-        /// <summary>
-        /// The default value of the item (members with this value will not be serialized)
-        /// </summary>
-        public object DefaultValue
-        {
-            get { return defaultValue; }
-            set
-            {
-                if (defaultValue != value)
-                {
-                    ThrowIfFrozen();
-                    defaultValue = value;
-                }
-            }
-        }
-
-        private readonly RuntimeTypeModel model;
-        /// <summary>
-        /// Creates a new ValueMember instance
-        /// </summary>
-        public ValueMember(RuntimeTypeModel model, Type parentType, int fieldNumber, MemberInfo member, Type memberType, Type itemType, Type defaultType, DataFormat dataFormat, object defaultValue)
-            : this(model, fieldNumber, memberType, itemType, defaultType, dataFormat)
-        {
-            if (parentType == null) throw new ArgumentNullException("parentType");
-            if (fieldNumber < 1 && !Helpers.IsEnum(parentType)) throw new ArgumentOutOfRangeException("fieldNumber");
-
-            this.originalMember = member ?? throw new ArgumentNullException("member");
-            this.parentType = parentType;
-            if (fieldNumber < 1 && !Helpers.IsEnum(parentType)) throw new ArgumentOutOfRangeException("fieldNumber");
-            //#if WINRT
-            if (defaultValue != null && model.MapType(defaultValue.GetType()) != memberType)
-            //#else
-            //            if (defaultValue != null && !memberType.IsInstanceOfType(defaultValue))
-            //#endif
-            {
-                defaultValue = ParseDefaultValue(memberType, defaultValue);
-            }
-            this.defaultValue = defaultValue;
-
-            MetaType type = model.FindWithoutAdd(memberType);
-            if (type != null)
-            {
-                AsReference = type.AsReferenceDefault;
-            }
-            else
-            { // we need to scan the hard way; can't risk recursion by fully walking it
-                AsReference = MetaType.GetAsReferenceDefault(model, memberType);
-            }
-        }
-        /// <summary>
-        /// Creates a new ValueMember instance
-        /// </summary>
-        internal ValueMember(RuntimeTypeModel model, int fieldNumber, Type memberType, Type itemType, Type defaultType, DataFormat dataFormat)
-        {
-            _fieldNumber = fieldNumber;
-            this.memberType = memberType ?? throw new ArgumentNullException(nameof(memberType));
-            this.itemType = itemType;
-            this.defaultType = defaultType;
-
-            this.model = model ?? throw new ArgumentNullException(nameof(model));
-            this.dataFormat = dataFormat;
-        }
-        internal object GetRawEnumValue()
-        {
-#if PORTABLE || CF || COREFX || PROFILE259
-			object value = ((FieldInfo)originalMember).GetValue(null);
-            switch(Helpers.GetTypeCode(Enum.GetUnderlyingType(((FieldInfo)originalMember).FieldType)))
-            {
-                case ProtoTypeCode.SByte: return (sbyte)value;
-                case ProtoTypeCode.Byte: return (byte)value;
-                case ProtoTypeCode.Int16: return (short)value;
-                case ProtoTypeCode.UInt16: return (ushort)value;
-                case ProtoTypeCode.Int32: return (int)value;
-                case ProtoTypeCode.UInt32: return (uint)value;
-                case ProtoTypeCode.Int64: return (long)value;
-                case ProtoTypeCode.UInt64: return (ulong)value;
-                default:
-                    throw new InvalidOperationException();
-            }
-#else
-            return ((FieldInfo)originalMember).GetRawConstantValue();
-#endif
-        }
-        private static object ParseDefaultValue(Type type, object value)
-        {
-            {
-                Type tmp = Helpers.GetUnderlyingType(type);
-                if (tmp != null) type = tmp;
-            }
-            if (value is string s)
-            {
-                if (Helpers.IsEnum(type)) return Helpers.ParseEnum(type, s);
-
-                switch (Helpers.GetTypeCode(type))
-                {
-                    case ProtoTypeCode.Boolean: return bool.Parse(s);
-                    case ProtoTypeCode.Byte: return byte.Parse(s, NumberStyles.Integer, CultureInfo.InvariantCulture);
-                    case ProtoTypeCode.Char: // char.Parse missing on CF/phone7
-                        if (s.Length == 1) return s[0];
-                        throw new FormatException("Single character expected: \"" + s + "\"");
-                    case ProtoTypeCode.DateTime: return DateTime.Parse(s, CultureInfo.InvariantCulture);
-                    case ProtoTypeCode.Decimal: return decimal.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
-                    case ProtoTypeCode.Double: return double.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
-                    case ProtoTypeCode.Int16: return short.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
-                    case ProtoTypeCode.Int32: return int.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
-                    case ProtoTypeCode.Int64: return long.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
-                    case ProtoTypeCode.SByte: return sbyte.Parse(s, NumberStyles.Integer, CultureInfo.InvariantCulture);
-                    case ProtoTypeCode.Single: return float.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
-                    case ProtoTypeCode.String: return s;
-                    case ProtoTypeCode.UInt16: return ushort.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
-                    case ProtoTypeCode.UInt32: return uint.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
-                    case ProtoTypeCode.UInt64: return ulong.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
-                    case ProtoTypeCode.TimeSpan: return TimeSpan.Parse(s);
-                    case ProtoTypeCode.Uri: return s; // Uri is decorated as string
-                    case ProtoTypeCode.Guid: return new Guid(s);
-                }
-            }
-
-            if (Helpers.IsEnum(type)) return Enum.ToObject(type, value);
-            return Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
-
-        }
-
-        private IProtoSerializer serializer;
-        internal IProtoSerializer Serializer
-        {
-            get
-            {
-                return serializer ?? (serializer = BuildSerializer());
-            }
-        }
-
-        private DataFormat dataFormat;
-        /// <summary>
-        /// Specifies the rules used to process the field; this is used to determine the most appropriate
-        /// wite-type, but also to describe subtypes <i>within</i> that wire-type (such as SignedVariant)
-        /// </summary>
-        public DataFormat DataFormat
-        {
-            get { return dataFormat; }
-            set
-            {
-                if (value != dataFormat)
-                {
-                    ThrowIfFrozen();
-                    this.dataFormat = value;
-                }
-            }
-        }
-
-        /// <summary>
-        /// Indicates whether this field should follow strict encoding rules; this means (for example) that if a "fixed32"
-        /// is encountered when "variant" is defined, then it will fail (throw an exception) when parsing. Note that
-        /// when serializing the defined type is always used.
-        /// </summary>
-        public bool IsStrict
-        {
-            get { return HasFlag(OPTIONS_IsStrict); }
-            set { SetFlag(OPTIONS_IsStrict, value, true); }
-        }
-
-        /// <summary>
-        /// Indicates whether this field should use packed encoding (which can save lots of space for repeated primitive values).
-        /// This option only applies to list/array data of primitive types (int, double, etc).
-        /// </summary>
-        public bool IsPacked
-        {
-            get { return HasFlag(OPTIONS_IsPacked); }
-            set { SetFlag(OPTIONS_IsPacked, value, true); }
-        }
-
-        /// <summary>
-        /// Indicates whether this field should *repace* existing values (the default is false, meaning *append*).
-        /// This option only applies to list/array data.
-        /// </summary>
-        public bool OverwriteList
-        {
-            get { return HasFlag(OPTIONS_OverwriteList); }
-            set { SetFlag(OPTIONS_OverwriteList, value, true); }
-        }
-
-        /// <summary>
-        /// Indicates whether this field is mandatory.
-        /// </summary>
-        public bool IsRequired
-        {
-            get { return HasFlag(OPTIONS_IsRequired); }
-            set { SetFlag(OPTIONS_IsRequired, value, true); }
-        }
-
-        /// <summary>
-        /// Enables full object-tracking/full-graph support.
-        /// </summary>
-        public bool AsReference
-        {
-            get { return HasFlag(OPTIONS_AsReference); }
-            set { SetFlag(OPTIONS_AsReference, value, true); }
-        }
-
-        /// <summary>
-        /// Embeds the type information into the stream, allowing usage with types not known in advance.
-        /// </summary>
-        public bool DynamicType
-        {
-            get { return HasFlag(OPTIONS_DynamicType); }
-            set { SetFlag(OPTIONS_DynamicType, value, true); }
-        }
-
-        /// <summary>
-        /// Indicates that the member should be treated as a protobuf Map
-        /// </summary>
-        public bool IsMap
-        {
-            get { return HasFlag(OPTIONS_IsMap); }
-            set { SetFlag(OPTIONS_IsMap, value, true); }
-        }
-
-        private DataFormat mapKeyFormat, mapValueFormat;
-        /// <summary>
-        /// Specifies the data-format that should be used for the key, when IsMap is enabled
-        /// </summary>
-        public DataFormat MapKeyFormat
-        {
-            get { return mapKeyFormat; }
-            set
-            {
-                if (mapKeyFormat != value)
-                {
-                    ThrowIfFrozen();
-                    mapKeyFormat = value;
-                }
-            }
-        }
-        /// <summary>
-        /// Specifies the data-format that should be used for the value, when IsMap is enabled
-        /// </summary>
-        public DataFormat MapValueFormat
-        {
-            get { return mapValueFormat; }
-            set
-            {
-                if (mapValueFormat != value)
-                {
-                    ThrowIfFrozen();
-                    mapValueFormat = value;
-                }
-            }
-        }
-
-        private MethodInfo getSpecified, setSpecified;
-        /// <summary>
-        /// Specifies methods for working with optional data members.
-        /// </summary>
-        /// <param name="getSpecified">Provides a method (null for none) to query whether this member should
-        /// be serialized; it must be of the form "bool {Method}()". The member is only serialized if the
-        /// method returns true.</param>
-        /// <param name="setSpecified">Provides a method (null for none) to indicate that a member was
-        /// deserialized; it must be of the form "void {Method}(bool)", and will be called with "true"
-        /// when data is found.</param>
-        public void SetSpecified(MethodInfo getSpecified, MethodInfo setSpecified)
-        {
-            if (this.getSpecified != getSpecified || this.setSpecified != setSpecified)
-            {
-                if (getSpecified != null)
-                {
-                    if (getSpecified.ReturnType != model.MapType(typeof(bool))
-                        || getSpecified.IsStatic
-                        || getSpecified.GetParameters().Length != 0)
-                    {
-                        throw new ArgumentException("Invalid pattern for checking member-specified", "getSpecified");
-                    }
-                }
-                if (setSpecified != null)
-                {
-                    ParameterInfo[] args;
-                    if (setSpecified.ReturnType != model.MapType(typeof(void))
-                        || setSpecified.IsStatic
-                        || (args = setSpecified.GetParameters()).Length != 1
-                        || args[0].ParameterType != model.MapType(typeof(bool)))
-                    {
-                        throw new ArgumentException("Invalid pattern for setting member-specified", "setSpecified");
-                    }
-                }
-
-                ThrowIfFrozen();
-                this.getSpecified = getSpecified;
-                this.setSpecified = setSpecified;
-            }
-        }
-
-        private void ThrowIfFrozen()
-        {
-            if (serializer != null) throw new InvalidOperationException("The type cannot be changed once a serializer has been generated");
-        }
-
-        internal bool ResolveMapTypes(out Type dictionaryType, out Type keyType, out Type valueType)
-        {
-            dictionaryType = keyType = valueType = null;
-            try
-            {
-#if COREFX || PROFILE259
-				var info = memberType.GetTypeInfo();
-#else
-                var info = memberType;
-#endif
-                if (ImmutableCollectionDecorator.IdentifyImmutable(model, MemberType, out _, out _, out _, out _, out _, out _))
-                {
-                    return false;
-                }
-                if (info.IsInterface && info.IsGenericType && info.GetGenericTypeDefinition() == typeof(IDictionary<,>))
-                {
-#if PROFILE259
-					var typeArgs = memberType.GetGenericTypeDefinition().GenericTypeArguments;
-#else
-                    var typeArgs = memberType.GetGenericArguments();
-#endif
-                    if (IsValidMapKeyType(typeArgs[0]))
-                    {
-                        keyType = typeArgs[0];
-                        valueType = typeArgs[1];
-                        dictionaryType = memberType;
-                    }
-                    return false;
-                }
-#if PROFILE259
-				foreach (var iType in memberType.GetTypeInfo().ImplementedInterfaces)
-#else
-                foreach (var iType in memberType.GetInterfaces())
-#endif
-                {
-#if COREFX || PROFILE259
-					info = iType.GetTypeInfo();
-#else
-                    info = iType;
-#endif
-                    if (info.IsGenericType && info.GetGenericTypeDefinition() == typeof(IDictionary<,>))
-                    {
-                        if (dictionaryType != null) throw new InvalidOperationException("Multiple dictionary interfaces implemented by type: " + memberType.FullName);
-#if PROFILE259
-						var typeArgs = iType.GetGenericTypeDefinition().GenericTypeArguments;
-#else
-                        var typeArgs = iType.GetGenericArguments();
-#endif
-                        if (IsValidMapKeyType(typeArgs[0]))
-                        {
-                            keyType = typeArgs[0];
-                            valueType = typeArgs[1];
-                            dictionaryType = memberType;
-                        }
-                    }
-                }
-                if (dictionaryType == null) return false;
-
-                // (note we checked the key type already)
-                // not a map if value is repeated
-                Type itemType = null, defaultType = null;
-                model.ResolveListTypes(valueType, ref itemType, ref defaultType);
-                if (itemType != null) return false;
-
-                return dictionaryType != null;
-            }
-            catch
-            {
-                // if it isn't a good fit; don't use "map"
-                return false;
-            }
-        }
-
-        static bool IsValidMapKeyType(Type type)
-        {
-            if (type == null || Helpers.IsEnum(type)) return false;
-            switch (Helpers.GetTypeCode(type))
-            {
-                case ProtoTypeCode.Boolean:
-                case ProtoTypeCode.Byte:
-                case ProtoTypeCode.Char:
-                case ProtoTypeCode.Int16:
-                case ProtoTypeCode.Int32:
-                case ProtoTypeCode.Int64:
-                case ProtoTypeCode.String:
-
-                case ProtoTypeCode.SByte:
-                case ProtoTypeCode.UInt16:
-                case ProtoTypeCode.UInt32:
-                case ProtoTypeCode.UInt64:
-                    return true;
-            }
-            return false;
-        }
-        private IProtoSerializer BuildSerializer()
-        {
-            int opaqueToken = 0;
-            try
-            {
-                model.TakeLock(ref opaqueToken);// check nobody is still adding this type
-                var member = backingMember ?? originalMember;
-                IProtoSerializer ser;
-                if (IsMap)
-                {
-                    ResolveMapTypes(out var dictionaryType, out var keyType, out var valueType);
-
-                    if (dictionaryType == null)
-                    {
-                        throw new InvalidOperationException("Unable to resolve map type for type: " + memberType.FullName);
-                    }
-                    var concreteType = defaultType;
-                    if (concreteType == null && Helpers.IsClass(memberType))
-                    {
-                        concreteType = memberType;
-                    }
-                    var keySer = TryGetCoreSerializer(model, MapKeyFormat, keyType, out var keyWireType, false, false, false, false);
-                    if (!AsReference)
-                    {
-                        AsReference = MetaType.GetAsReferenceDefault(model, valueType);
-                    }
-                    var valueSer = TryGetCoreSerializer(model, MapValueFormat, valueType, out var valueWireType, AsReference, DynamicType, false, true);
-#if PROFILE259
-					IEnumerable<ConstructorInfo> ctors = typeof(MapDecorator<,,>).MakeGenericType(new Type[] { dictionaryType, keyType, valueType }).GetTypeInfo().DeclaredConstructors;
-	                if (ctors.Count() != 1)
-	                {
-		                throw new InvalidOperationException("Unable to resolve MapDecorator constructor");
-	                }
-	                ser = (IProtoSerializer)ctors.First().Invoke(new object[] {model, concreteType, keySer, valueSer, _fieldNumber,
-		                DataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String, keyWireType, valueWireType, OverwriteList });
-#else
-                    var ctors = typeof(MapDecorator<,,>).MakeGenericType(new Type[] { dictionaryType, keyType, valueType }).GetConstructors(
-                        BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
-                    if (ctors.Length != 1) throw new InvalidOperationException("Unable to resolve MapDecorator constructor");
-                    ser = (IProtoSerializer)ctors[0].Invoke(new object[] {model, concreteType, keySer, valueSer, _fieldNumber,
-                        DataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String, keyWireType, valueWireType, OverwriteList });
-#endif
-                }
-                else
-                {
-                    Type finalType = itemType ?? memberType;
-                    ser = TryGetCoreSerializer(model, dataFormat, finalType, out WireType wireType, AsReference, DynamicType, OverwriteList, true);
-                    if (ser == null)
-                    {
-                        throw new InvalidOperationException("No serializer defined for type: " + finalType.FullName);
-                    }
-
-                    // apply tags
-                    if (itemType != null && SupportNull)
-                    {
-                        if (IsPacked)
-                        {
-                            throw new NotSupportedException("Packed encodings cannot support null values");
-                        }
-                        ser = new TagDecorator(NullDecorator.Tag, wireType, IsStrict, ser);
-                        ser = new NullDecorator(model, ser);
-                        ser = new TagDecorator(_fieldNumber, WireType.StartGroup, false, ser);
-                    }
-                    else
-                    {
-                        ser = new TagDecorator(_fieldNumber, wireType, IsStrict, ser);
-                    }
-                    // apply lists if appropriate
-                    if (itemType != null)
-                    {
-                        Type underlyingItemType = SupportNull ? itemType : Helpers.GetUnderlyingType(itemType) ?? itemType;
-
-                        Helpers.DebugAssert(underlyingItemType == ser.ExpectedType
-                            || (ser.ExpectedType == model.MapType(typeof(object)) && !Helpers.IsValueType(underlyingItemType))
-                            , "Wrong type in the tail; expected {0}, received {1}", ser.ExpectedType, underlyingItemType);
-                        if (memberType.IsArray)
-                        {
-                            ser = new ArrayDecorator(model, ser, _fieldNumber, IsPacked, wireType, memberType, OverwriteList, SupportNull);
-                        }
-                        else
-                        {
-                            ser = ListDecorator.Create(model, memberType, defaultType, ser, _fieldNumber, IsPacked, wireType, member != null && PropertyDecorator.CanWrite(model, member), OverwriteList, SupportNull);
-                        }
-                    }
-                    else if (defaultValue != null && !IsRequired && getSpecified == null)
-                    {   // note: "ShouldSerialize*" / "*Specified" / etc ^^^^ take precedence over defaultValue,
-                        // as does "IsRequired"
-                        ser = new DefaultValueDecorator(model, defaultValue, ser);
-                    }
-                    if (memberType == model.MapType(typeof(Uri)))
-                    {
-                        ser = new UriDecorator(model, ser);
-                    }
-#if PORTABLE
-                    else if(memberType.FullName == typeof(Uri).FullName)
-                    {
-                        // In PCLs, the Uri type may not match (WinRT uses Internal/Uri, .Net uses System/Uri)
-                        ser = new ReflectedUriDecorator(memberType, model, ser);
-                    }
-#endif
-                }
-                if (member != null)
-                {
-                    if (member is PropertyInfo prop)
-                    {
-                        ser = new PropertyDecorator(model, parentType, prop, ser);
-                    }
-                    else if (member is FieldInfo fld)
-                    {
-                        ser = new FieldDecorator(parentType, fld, ser);
-                    }
-                    else
-                    {
-                        throw new InvalidOperationException();
-                    }
-                    
-                    if (getSpecified != null || setSpecified != null)
-                    {
-                        ser = new MemberSpecifiedDecorator(getSpecified, setSpecified, ser);
-                    }
-                }
-                return ser;
-            }
-            finally
-            {
-                model.ReleaseLock(opaqueToken);
-            }
-        }
-
-        private static WireType GetIntWireType(DataFormat format, int width)
-        {
-            switch (format)
-            {
-                case DataFormat.ZigZag: return WireType.SignedVariant;
-                case DataFormat.FixedSize: return width == 32 ? WireType.Fixed32 : WireType.Fixed64;
-                case DataFormat.TwosComplement:
-                case DataFormat.Default: return WireType.Variant;
-                default: throw new InvalidOperationException();
-            }
-        }
-        private static WireType GetDateTimeWireType(DataFormat format)
-        {
-            switch (format)
-            {
-
-                case DataFormat.Group: return WireType.StartGroup;
-                case DataFormat.FixedSize: return WireType.Fixed64;
-                case DataFormat.WellKnown:
-                case DataFormat.Default:
-                    return WireType.String;
-                default: throw new InvalidOperationException();
-            }
-        }
-
-        internal static IProtoSerializer TryGetCoreSerializer(RuntimeTypeModel model, DataFormat dataFormat, Type type, out WireType defaultWireType,
-            bool asReference, bool dynamicType, bool overwriteList, bool allowComplexTypes)
-        {
-            {
-                Type tmp = Helpers.GetUnderlyingType(type);
-                if (tmp != null) type = tmp;
-            }
-            if (Helpers.IsEnum(type))
-            {
-                if (allowComplexTypes && model != null)
-                {
-                    // need to do this before checking the typecode; an int enum will report Int32 etc
-                    defaultWireType = WireType.Variant;
-                    return new EnumSerializer(type, model.GetEnumMap(type));
-                }
-                else
-                { // enum is fine for adding as a meta-type
-                    defaultWireType = WireType.None;
-                    return null;
-                }
-            }
-            ProtoTypeCode code = Helpers.GetTypeCode(type);
-            switch (code)
-            {
-                case ProtoTypeCode.Int32:
-                    defaultWireType = GetIntWireType(dataFormat, 32);
-                    return new Int32Serializer(model);
-                case ProtoTypeCode.UInt32:
-                    defaultWireType = GetIntWireType(dataFormat, 32);
-                    return new UInt32Serializer(model);
-                case ProtoTypeCode.Int64:
-                    defaultWireType = GetIntWireType(dataFormat, 64);
-                    return new Int64Serializer(model);
-                case ProtoTypeCode.UInt64:
-                    defaultWireType = GetIntWireType(dataFormat, 64);
-                    return new UInt64Serializer(model);
-                case ProtoTypeCode.String:
-                    defaultWireType = WireType.String;
-                    if (asReference)
-                    {
-                        return new NetObjectSerializer(model, model.MapType(typeof(string)), 0, BclHelpers.NetObjectOptions.AsReference);
-                    }
-                    return new StringSerializer(model);
-                case ProtoTypeCode.Single:
-                    defaultWireType = WireType.Fixed32;
-                    return new SingleSerializer(model);
-                case ProtoTypeCode.Double:
-                    defaultWireType = WireType.Fixed64;
-                    return new DoubleSerializer(model);
-                case ProtoTypeCode.Boolean:
-                    defaultWireType = WireType.Variant;
-                    return new BooleanSerializer(model);
-                case ProtoTypeCode.DateTime:
-                    defaultWireType = GetDateTimeWireType(dataFormat);
-                    return new DateTimeSerializer(dataFormat, model);
-                case ProtoTypeCode.Decimal:
-                    defaultWireType = WireType.String;
-                    return new DecimalSerializer(model);
-                case ProtoTypeCode.Byte:
-                    defaultWireType = GetIntWireType(dataFormat, 32);
-                    return new ByteSerializer(model);
-                case ProtoTypeCode.SByte:
-                    defaultWireType = GetIntWireType(dataFormat, 32);
-                    return new SByteSerializer(model);
-                case ProtoTypeCode.Char:
-                    defaultWireType = WireType.Variant;
-                    return new CharSerializer(model);
-                case ProtoTypeCode.Int16:
-                    defaultWireType = GetIntWireType(dataFormat, 32);
-                    return new Int16Serializer(model);
-                case ProtoTypeCode.UInt16:
-                    defaultWireType = GetIntWireType(dataFormat, 32);
-                    return new UInt16Serializer(model);
-                case ProtoTypeCode.TimeSpan:
-                    defaultWireType = GetDateTimeWireType(dataFormat);
-                    return new TimeSpanSerializer(dataFormat, model);
-                case ProtoTypeCode.Guid:
-                    defaultWireType = dataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String;
-                    return new GuidSerializer(model);
-                case ProtoTypeCode.Uri:
-                    defaultWireType = WireType.String;
-                    return new StringSerializer(model);
-                case ProtoTypeCode.ByteArray:
-                    defaultWireType = WireType.String;
-                    return new BlobSerializer(model, overwriteList);
-                case ProtoTypeCode.Type:
-                    defaultWireType = WireType.String;
-                    return new SystemTypeSerializer(model);
-            }
-            IProtoSerializer parseable = model.AllowParseableTypes ? ParseableSerializer.TryCreate(type, model) : null;
-            if (parseable != null)
-            {
-                defaultWireType = WireType.String;
-                return parseable;
-            }
-            if (allowComplexTypes && model != null)
-            {
-                int key = model.GetKey(type, false, true);
-                MetaType meta = null;
-                if (key >= 0)
-                {
-                    meta = model[type];
-                    if (dataFormat == DataFormat.Default && meta.IsGroup)
-                    {
-                        dataFormat = DataFormat.Group;
-                    }
-                }
-
-                if (asReference || dynamicType)
-                {
-                    BclHelpers.NetObjectOptions options = BclHelpers.NetObjectOptions.None;
-                    if (asReference) options |= BclHelpers.NetObjectOptions.AsReference;
-                    if (dynamicType) options |= BclHelpers.NetObjectOptions.DynamicType;
-                    if (meta != null)
-                    { // exists
-                        if (asReference && Helpers.IsValueType(type))
-                        {
-                            string message = "AsReference cannot be used with value-types";
-
-                            if (type.Name == "KeyValuePair`2")
-                            {
-                                message += "; please see https://stackoverflow.com/q/14436606/23354";
-                            }
-                            else
-                            {
-                                message += ": " + type.FullName;
-                            }
-                            throw new InvalidOperationException(message);
-                        }
-
-                        if (asReference && meta.IsAutoTuple) options |= BclHelpers.NetObjectOptions.LateSet;
-                        if (meta.UseConstructor) options |= BclHelpers.NetObjectOptions.UseConstructor;
-                    }
-                    defaultWireType = dataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String;
-                    return new NetObjectSerializer(model, type, key, options);
-                }
-                if (key >= 0)
-                {
-                    defaultWireType = dataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String;
-                    return new SubItemSerializer(type, key, meta, true);
-                }
-            }
-            defaultWireType = WireType.None;
-            return null;
-        }
-
-
-        private string name;
-        internal void SetName(string name)
-        {
-            if (name != this.name)
-            {
-                ThrowIfFrozen();
-                this.name = name;
-            }
-        }
-        /// <summary>
-        /// Gets the logical name for this member in the schema (this is not critical for binary serialization, but may be used
-        /// when inferring a schema).
-        /// </summary>
-        public string Name
-        {
-            get { return string.IsNullOrEmpty(name) ? originalMember.Name : name; }
-            set { SetName(value); }
-        }
-
-        private const byte
-           OPTIONS_IsStrict = 1,
-           OPTIONS_IsPacked = 2,
-           OPTIONS_IsRequired = 4,
-           OPTIONS_OverwriteList = 8,
-           OPTIONS_SupportNull = 16,
-           OPTIONS_AsReference = 32,
-           OPTIONS_IsMap = 64,
-           OPTIONS_DynamicType = 128;
-
-        private byte flags;
-        private bool HasFlag(byte flag) { return (flags & flag) == flag; }
-        private void SetFlag(byte flag, bool value, bool throwIfFrozen)
-        {
-            if (throwIfFrozen && HasFlag(flag) != value)
-            {
-                ThrowIfFrozen();
-            }
-            if (value)
-                flags |= flag;
-            else
-                flags = (byte)(flags & ~flag);
-        }
-
-        /// <summary>
-        /// Should lists have extended support for null values? Note this makes the serialization less efficient.
-        /// </summary>
-        public bool SupportNull
-        {
-            get { return HasFlag(OPTIONS_SupportNull); }
-            set { SetFlag(OPTIONS_SupportNull, value, true); }
-        }
-
-        internal string GetSchemaTypeName(bool applyNetObjectProxy, ref RuntimeTypeModel.CommonImports imports)
-        {
-            Type effectiveType = ItemType;
-            if (effectiveType == null) effectiveType = MemberType;
-            return model.GetSchemaTypeName(effectiveType, DataFormat, applyNetObjectProxy && AsReference, applyNetObjectProxy && DynamicType, ref imports);
-        }
-
-
-        internal sealed class Comparer : System.Collections.IComparer, IComparer<ValueMember>
-        {
-            public static readonly Comparer Default = new Comparer();
-
-            public int Compare(object x, object y)
-            {
-                return Compare(x as ValueMember, y as ValueMember);
-            }
-
-            public int Compare(ValueMember x, ValueMember y)
-            {
-                if (ReferenceEquals(x, y)) return 0;
-                if (x == null) return -1;
-                if (y == null) return 1;
-
-                return x.FieldNumber.CompareTo(y.FieldNumber);
-            }
-        }
-    }
-}
-#endif

+ 0 - 190
ThirdParty/protobuf-net/NetObjectCache.cs

@@ -1,190 +0,0 @@
-using System;
-using System.Collections.Generic;
-using ProtoBuf.Meta;
-
-namespace ProtoBuf
-{
-    internal sealed class NetObjectCache
-    {
-        internal const int Root = 0;
-        private MutableList underlyingList;
-
-        private MutableList List => underlyingList ?? (underlyingList = new MutableList());
-
-        internal object GetKeyedObject(int key)
-        {
-            if (key-- == Root)
-            {
-                if (rootObject == null) throw new ProtoException("No root object assigned");
-                return rootObject;
-            }
-            BasicList list = List;
-
-            if (key < 0 || key >= list.Count)
-            {
-                Helpers.DebugWriteLine("Missing key: " + key);
-                throw new ProtoException("Internal error; a missing key occurred");
-            }
-
-            object tmp = list[key];
-            if (tmp == null)
-            {
-                throw new ProtoException("A deferred key does not have a value yet");
-            }
-            return tmp;
-        }
-
-        internal void SetKeyedObject(int key, object value)
-        {
-            if (key-- == Root)
-            {
-                if (value == null) throw new ArgumentNullException(nameof(value));
-                if (rootObject != null && ((object)rootObject != (object)value)) throw new ProtoException("The root object cannot be reassigned");
-                rootObject = value;
-            }
-            else
-            {
-                MutableList list = List;
-                if (key < list.Count)
-                {
-                    object oldVal = list[key];
-                    if (oldVal == null)
-                    {
-                        list[key] = value;
-                    }
-                    else if (!ReferenceEquals(oldVal, value))
-                    {
-                        throw new ProtoException("Reference-tracked objects cannot change reference");
-                    } // otherwise was the same; nothing to do
-                }
-                else if (key != list.Add(value))
-                {
-                    throw new ProtoException("Internal error; a key mismatch occurred");
-                }
-            }
-        }
-
-        private object rootObject;
-        internal int AddObjectKey(object value, out bool existing)
-        {
-            if (value == null) throw new ArgumentNullException(nameof(value));
-
-            if ((object)value == (object)rootObject) // (object) here is no-op, but should be
-            {                                        // preserved even if this was typed - needs ref-check
-                existing = true;
-                return Root;
-            }
-
-            string s = value as string;
-            BasicList list = List;
-            int index;
-
-            if (s == null)
-            {
-#if CF || PORTABLE // CF has very limited proper object ref-tracking; so instead, we'll search it the hard way
-                index = list.IndexOfReference(value);
-#else
-                if (objectKeys == null)
-                {
-                    objectKeys = new Dictionary<object, int>(ReferenceComparer.Default);
-                    index = -1;
-                }
-                else
-                {
-                    if (!objectKeys.TryGetValue(value, out index)) index = -1;
-                }
-#endif
-            }
-            else
-            {
-                if (stringKeys == null)
-                {
-                    stringKeys = new Dictionary<string, int>();
-                    index = -1;
-                }
-                else
-                {
-                    if (!stringKeys.TryGetValue(s, out index)) index = -1;
-                }
-            }
-
-            if (!(existing = index >= 0))
-            {
-                index = list.Add(value);
-
-                if (s == null)
-                {
-#if !CF && !PORTABLE // CF can't handle the object keys very well
-                    objectKeys.Add(value, index);
-#endif
-                }
-                else
-                {
-                    stringKeys.Add(s, index);
-                }
-            }
-            return index + 1;
-        }
-
-        private int trapStartIndex; // defaults to 0 - optimization for RegisterTrappedObject
-                                    // to make it faster at seeking to find deferred-objects
-
-        internal void RegisterTrappedObject(object value)
-        {
-            if (rootObject == null)
-            {
-                rootObject = value;
-            }
-            else
-            {
-                if (underlyingList != null)
-                {
-                    for (int i = trapStartIndex; i < underlyingList.Count; i++)
-                    {
-                        trapStartIndex = i + 1; // things never *become* null; whether or
-                                                // not the next item is null, it will never
-                                                // need to be checked again
-
-                        if (underlyingList[i] == null)
-                        {
-                            underlyingList[i] = value;
-                            break;
-                        }
-                    }
-                }
-            }
-        }
-
-        private Dictionary<string, int> stringKeys;
-
-#if !CF && !PORTABLE // CF lacks the ability to get a robust reference-based hash-code, so we'll do it the harder way instead
-        private System.Collections.Generic.Dictionary<object, int> objectKeys;
-        private sealed class ReferenceComparer : IEqualityComparer<object>
-        {
-            public readonly static ReferenceComparer Default = new ReferenceComparer();
-            private ReferenceComparer() { }
-
-            bool IEqualityComparer<object>.Equals(object x, object y)
-            {
-                return x == y; // ref equality
-            }
-
-            int IEqualityComparer<object>.GetHashCode(object obj)
-            {
-                return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj);
-            }
-        }
-#endif
-
-        internal void Clear()
-        {
-            trapStartIndex = 0;
-            rootObject = null;
-            if (underlyingList != null) underlyingList.Clear();
-            if (stringKeys != null) stringKeys.Clear();
-#if !CF && !PORTABLE
-            if (objectKeys != null) objectKeys.Clear();
-#endif
-        }
-    }
-}

+ 0 - 26
ThirdParty/protobuf-net/PrefixStyle.cs

@@ -1,26 +0,0 @@
-
-namespace ProtoBuf
-{
-    /// <summary>
-    /// Specifies the type of prefix that should be applied to messages.
-    /// </summary>
-    public enum PrefixStyle
-    {
-        /// <summary>
-        /// No length prefix is applied to the data; the data is terminated only be the end of the stream.
-        /// </summary>
-        None = 0,
-        /// <summary>
-        /// A base-128 ("varint", the default prefix format in protobuf) length prefix is applied to the data (efficient for short messages).
-        /// </summary>
-        Base128 = 1,
-        /// <summary>
-        /// A fixed-length (little-endian) length prefix is applied to the data (useful for compatibility).
-        /// </summary>
-        Fixed32 = 2,
-        /// <summary>
-        /// A fixed-length (big-endian) length prefix is applied to the data (useful for compatibility).
-        /// </summary>
-        Fixed32BigEndian = 3
-    }
-}

+ 0 - 175
ThirdParty/protobuf-net/ProtoContractAttribute.cs

@@ -1,175 +0,0 @@
-using System;
-
-namespace ProtoBuf
-{
-    /// <summary>
-    /// Indicates that a type is defined for protocol-buffer serialization.
-    /// </summary>
-    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface,
-        AllowMultiple = false, Inherited = false)]
-    public sealed class ProtoContractAttribute : Attribute
-    {
-        /// <summary>
-        /// Gets or sets the defined name of the type.
-        /// </summary>
-        public string Name { get; set; }
-
-        /// <summary>
-        /// Gets or sets the fist offset to use with implicit field tags;
-        /// only uesd if ImplicitFields is set.
-        /// </summary>
-        public int ImplicitFirstTag
-        {
-            get { return implicitFirstTag; }
-            set
-            {
-                if (value < 1) throw new ArgumentOutOfRangeException("ImplicitFirstTag");
-                implicitFirstTag = value;
-            }
-        }
-        private int implicitFirstTag;
-
-        /// <summary>
-        /// If specified, alternative contract markers (such as markers for XmlSerailizer or DataContractSerializer) are ignored.
-        /// </summary>
-        public bool UseProtoMembersOnly
-        {
-            get { return HasFlag(OPTIONS_UseProtoMembersOnly); }
-            set { SetFlag(OPTIONS_UseProtoMembersOnly, value); }
-        }
-
-        /// <summary>
-        /// If specified, do NOT treat this type as a list, even if it looks like one.
-        /// </summary>
-        public bool IgnoreListHandling
-        {
-            get { return HasFlag(OPTIONS_IgnoreListHandling); }
-            set { SetFlag(OPTIONS_IgnoreListHandling, value); }
-        }
-
-        /// <summary>
-        /// Gets or sets the mechanism used to automatically infer field tags
-        /// for members. This option should be used in advanced scenarios only.
-        /// Please review the important notes against the ImplicitFields enumeration.
-        /// </summary>
-        public ImplicitFields ImplicitFields { get; set; }
-
-        /// <summary>
-        /// Enables/disables automatic tag generation based on the existing name / order
-        /// of the defined members. This option is not used for members marked
-        /// with ProtoMemberAttribute, as intended to provide compatibility with
-        /// WCF serialization. WARNING: when adding new fields you must take
-        /// care to increase the Order for new elements, otherwise data corruption
-        /// may occur.
-        /// </summary>
-        /// <remarks>If not explicitly specified, the default is assumed from Serializer.GlobalOptions.InferTagFromName.</remarks>
-        public bool InferTagFromName
-        {
-            get { return HasFlag(OPTIONS_InferTagFromName); }
-            set
-            {
-                SetFlag(OPTIONS_InferTagFromName, value);
-                SetFlag(OPTIONS_InferTagFromNameHasValue, true);
-            }
-        }
-
-        /// <summary>
-        /// Has a InferTagFromName value been explicitly set? if not, the default from the type-model is assumed.
-        /// </summary>
-        internal bool InferTagFromNameHasValue
-        { // note that this property is accessed via reflection and should not be removed
-            get { return HasFlag(OPTIONS_InferTagFromNameHasValue); }
-        }
-
-        /// <summary>
-        /// Specifies an offset to apply to [DataMember(Order=...)] markers;
-        /// this is useful when working with mex-generated classes that have
-        /// a different origin (usually 1 vs 0) than the original data-contract.
-        /// 
-        /// This value is added to the Order of each member.
-        /// </summary>
-        public int DataMemberOffset { get; set; }
-
-        /// <summary>
-        /// If true, the constructor for the type is bypassed during deserialization, meaning any field initializers
-        /// or other initialization code is skipped.
-        /// </summary>
-        public bool SkipConstructor
-        {
-            get { return HasFlag(OPTIONS_SkipConstructor); }
-            set { SetFlag(OPTIONS_SkipConstructor, value); }
-        }
-
-        /// <summary>
-        /// Should this type be treated as a reference by default? Please also see the implications of this,
-        /// as recorded on ProtoMemberAttribute.AsReference
-        /// </summary>
-        public bool AsReferenceDefault
-        {
-            get { return HasFlag(OPTIONS_AsReferenceDefault); }
-            set
-            {
-                SetFlag(OPTIONS_AsReferenceDefault, value);
-            }
-        }
-
-        /// <summary>
-        /// Indicates whether this type should always be treated as a "group" (rather than a string-prefixed sub-message)
-        /// </summary>
-        public bool IsGroup
-        {
-            get { return HasFlag(OPTIONS_IsGroup); }
-            set
-            {
-                SetFlag(OPTIONS_IsGroup, value);
-            }
-        }
-
-        private bool HasFlag(ushort flag) { return (flags & flag) == flag; }
-        private void SetFlag(ushort flag, bool value)
-        {
-            if (value) flags |= flag;
-            else flags = (ushort)(flags & ~flag);
-        }
-
-        private ushort flags;
-
-        private const ushort
-            OPTIONS_InferTagFromName = 1,
-            OPTIONS_InferTagFromNameHasValue = 2,
-            OPTIONS_UseProtoMembersOnly = 4,
-            OPTIONS_SkipConstructor = 8,
-            OPTIONS_IgnoreListHandling = 16,
-            OPTIONS_AsReferenceDefault = 32,
-            OPTIONS_EnumPassthru = 64,
-            OPTIONS_EnumPassthruHasValue = 128,
-            OPTIONS_IsGroup = 256;
-
-        /// <summary>
-        /// Applies only to enums (not to DTO classes themselves); gets or sets a value indicating that an enum should be treated directly as an int/short/etc, rather
-        /// than enforcing .proto enum rules. This is useful *in particul* for [Flags] enums.
-        /// </summary>
-        public bool EnumPassthru
-        {
-            get { return HasFlag(OPTIONS_EnumPassthru); }
-            set
-            {
-                SetFlag(OPTIONS_EnumPassthru, value);
-                SetFlag(OPTIONS_EnumPassthruHasValue, true);
-            }
-        }
-
-        /// <summary>
-        /// Allows to define a surrogate type used for serialization/deserialization purpose.
-        /// </summary>
-        public Type Surrogate { get; set; }
-
-        /// <summary>
-        /// Has a EnumPassthru value been explicitly set?
-        /// </summary>
-        internal bool EnumPassthruHasValue
-        { // note that this property is accessed via reflection and should not be removed
-            get { return HasFlag(OPTIONS_EnumPassthruHasValue); }
-        }
-    }
-}

+ 0 - 13
ThirdParty/protobuf-net/ProtoConverterAttribute.cs

@@ -1,13 +0,0 @@
-using System;
-
-namespace ProtoBuf
-{
-    /// <summary>
-    /// Indicates that a static member should be considered the same as though
-    /// were an implicit / explicit conversion operator; in particular, this
-    /// is useful for conversions that operator syntax does not allow, such as
-    /// to/from interface types.
-    /// </summary>
-    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
-    public class ProtoConverterAttribute : Attribute { }
-}

+ 0 - 36
ThirdParty/protobuf-net/ProtoEnumAttribute.cs

@@ -1,36 +0,0 @@
-using System;
-
-namespace ProtoBuf
-{
-    /// <summary>
-    /// Used to define protocol-buffer specific behavior for
-    /// enumerated values.
-    /// </summary>
-    [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
-    public sealed class ProtoEnumAttribute : Attribute
-    {
-        /// <summary>
-        /// Gets or sets the specific value to use for this enum during serialization.
-        /// </summary>
-        public int Value
-        {
-            get { return enumValue; }
-            set { this.enumValue = value; hasValue = true; }
-        }
-
-        /// <summary>
-        /// Indicates whether this instance has a customised value mapping
-        /// </summary>
-        /// <returns>true if a specific value is set</returns>
-        public bool HasValue() => hasValue;
-
-        private bool hasValue;
-        private int enumValue;
-
-        /// <summary>
-        /// Gets or sets the defined name of the enum, as used in .proto
-        /// (this name is not used during serialization).
-        /// </summary>
-        public string Name { get; set; }
-    }
-}

+ 0 - 30
ThirdParty/protobuf-net/ProtoException.cs

@@ -1,30 +0,0 @@
-using System;
-
-#if PLAT_BINARYFORMATTER && !(COREFX || PROFILE259)
-using System.Runtime.Serialization;
-#endif
-namespace ProtoBuf
-{
-    /// <summary>
-    /// Indicates an error during serialization/deserialization of a proto stream.
-    /// </summary>
-#if PLAT_BINARYFORMATTER && !(COREFX || PROFILE259)
-    [Serializable]
-#endif
-    public class ProtoException : Exception
-    {
-        /// <summary>Creates a new ProtoException instance.</summary>
-        public ProtoException() { }
-
-        /// <summary>Creates a new ProtoException instance.</summary>
-        public ProtoException(string message) : base(message) { }
-
-        /// <summary>Creates a new ProtoException instance.</summary>
-        public ProtoException(string message, Exception innerException) : base(message, innerException) { }
-
-#if PLAT_BINARYFORMATTER && !(COREFX || PROFILE259)
-        /// <summary>Creates a new ProtoException instance.</summary>
-        protected ProtoException(SerializationInfo info, StreamingContext context) : base(info, context) { }
-#endif
-    }
-}

+ 0 - 40
ThirdParty/protobuf-net/ProtoIgnoreAttribute.cs

@@ -1,40 +0,0 @@
-using System;
-
-namespace ProtoBuf
-{
-    /// <summary>
-    /// Indicates that a member should be excluded from serialization; this
-    /// is only normally used when using implict fields.
-    /// </summary>
-    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field,
-        AllowMultiple = false, Inherited = true)]
-    public class ProtoIgnoreAttribute : Attribute { }
-
-    /// <summary>
-    /// Indicates that a member should be excluded from serialization; this
-    /// is only normally used when using implict fields. This allows
-    /// ProtoIgnoreAttribute usage
-    /// even for partial classes where the individual members are not
-    /// under direct control.
-    /// </summary>
-    [AttributeUsage(AttributeTargets.Class,
-            AllowMultiple = true, Inherited = false)]
-    public sealed class ProtoPartialIgnoreAttribute : ProtoIgnoreAttribute
-    {
-        /// <summary>
-        /// Creates a new ProtoPartialIgnoreAttribute instance.
-        /// </summary>
-        /// <param name="memberName">Specifies the member to be ignored.</param>
-        public ProtoPartialIgnoreAttribute(string memberName)
-            : base()
-        {
-            if (string.IsNullOrEmpty(memberName)) throw new ArgumentNullException(nameof(memberName));
-
-            MemberName = memberName;
-        }
-        /// <summary>
-        /// The name of the member to be ignored.
-        /// </summary>
-        public string MemberName { get; }
-    }
-}

+ 0 - 60
ThirdParty/protobuf-net/ProtoIncludeAttribute.cs

@@ -1,60 +0,0 @@
-using System;
-using System.ComponentModel;
-
-using ProtoBuf.Meta;
-
-namespace ProtoBuf
-{
-    /// <summary>
-    /// Indicates the known-types to support for an individual
-    /// message. This serializes each level in the hierarchy as
-    /// a nested message to retain wire-compatibility with
-    /// other protocol-buffer implementations.
-    /// </summary>
-    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)]
-    public sealed class ProtoIncludeAttribute : Attribute
-    {
-        ///<summary>
-        /// Creates a new instance of the ProtoIncludeAttribute.
-        /// </summary>
-        /// <param name="tag">The unique index (within the type) that will identify this data.</param>
-        /// <param name="knownType">The additional type to serialize/deserialize.</param>
-        public ProtoIncludeAttribute(int tag, Type knownType)
-            : this(tag, knownType == null ? "" : knownType.AssemblyQualifiedName) { }
-
-        /// <summary>
-        /// Creates a new instance of the ProtoIncludeAttribute.
-        /// </summary>
-        /// <param name="tag">The unique index (within the type) that will identify this data.</param>
-        /// <param name="knownTypeName">The additional type to serialize/deserialize.</param>
-        public ProtoIncludeAttribute(int tag, string knownTypeName)
-        {
-            if (tag <= 0) throw new ArgumentOutOfRangeException(nameof(tag), "Tags must be positive integers");
-            if (string.IsNullOrEmpty(knownTypeName)) throw new ArgumentNullException(nameof(knownTypeName), "Known type cannot be blank");
-            Tag = tag;
-            KnownTypeName = knownTypeName;
-        }
-
-        /// <summary>
-        /// Gets the unique index (within the type) that will identify this data.
-        /// </summary>
-        public int Tag { get; }
-
-        /// <summary>
-        /// Gets the additional type to serialize/deserialize.
-        /// </summary>
-        public string KnownTypeName { get; }
-
-        /// <summary>
-        /// Gets the additional type to serialize/deserialize.
-        /// </summary>
-        public Type KnownType => TypeModel.ResolveKnownType(KnownTypeName, null, null);
-
-        /// <summary>
-        /// Specifies whether the inherited sype's sub-message should be
-        /// written with a length-prefix (default), or with group markers.
-        /// </summary>
-        [DefaultValue(DataFormat.Default)]
-        public DataFormat DataFormat { get; set; } = DataFormat.Default;
-    }
-}

+ 0 - 29
ThirdParty/protobuf-net/ProtoMapAttribute.cs

@@ -1,29 +0,0 @@
-using System;
-
-namespace ProtoBuf
-{
-    /// <summary>
-    /// Controls the formatting of elements in a dictionary, and indicates that
-    /// "map" rules should be used: duplicates *replace* earlier values, rather
-    /// than throwing an exception
-    /// </summary>
-    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
-    public class ProtoMapAttribute : Attribute
-    {
-        /// <summary>
-        /// Describes the data-format used to store the key
-        /// </summary>
-        public DataFormat KeyFormat { get; set; }
-        /// <summary>
-        /// Describes the data-format used to store the value
-        /// </summary>
-        public DataFormat ValueFormat { get; set; }
-
-        /// <summary>
-        /// Disables "map" handling; dictionaries will use ".Add(key,value)" instead of  "[key] = value",
-        /// which means duplicate keys will cause an exception (instead of retaining the final value); if
-        /// a proto schema is emitted, it will be produced using "repeated" instead of "map"
-        /// </summary>
-        public bool DisableMap { get; set; }
-    }
-}

+ 0 - 228
ThirdParty/protobuf-net/ProtoMemberAttribute.cs

@@ -1,228 +0,0 @@
-using System;
-using System.Reflection;
-
-namespace ProtoBuf
-{
-    /// <summary>
-    /// Declares a member to be used in protocol-buffer serialization, using
-    /// the given Tag. A DataFormat may be used to optimise the serialization
-    /// format (for instance, using zigzag encoding for negative numbers, or 
-    /// fixed-length encoding for large values.
-    /// </summary>
-    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field,
-        AllowMultiple = false, Inherited = true)]
-    public class ProtoMemberAttribute : Attribute
-        , IComparable
-        , IComparable<ProtoMemberAttribute>
-
-    {
-        /// <summary>
-        /// Compare with another ProtoMemberAttribute for sorting purposes
-        /// </summary>
-        public int CompareTo(object other) => CompareTo(other as ProtoMemberAttribute);
-        /// <summary>
-        /// Compare with another ProtoMemberAttribute for sorting purposes
-        /// </summary>
-        public int CompareTo(ProtoMemberAttribute other)
-        {
-            if (other == null) return -1;
-            if ((object)this == (object)other) return 0;
-            int result = this.tag.CompareTo(other.tag);
-            if (result == 0) result = string.CompareOrdinal(this.name, other.name);
-            return result;
-        }
-
-        /// <summary>
-        /// Creates a new ProtoMemberAttribute instance.
-        /// </summary>
-        /// <param name="tag">Specifies the unique tag used to identify this member within the type.</param>
-        public ProtoMemberAttribute(int tag) : this(tag, false)
-        { }
-
-        internal ProtoMemberAttribute(int tag, bool forced)
-        {
-            if (tag <= 0 && !forced) throw new ArgumentOutOfRangeException(nameof(tag));
-            this.tag = tag;
-        }
-
-#if !NO_RUNTIME
-        internal MemberInfo Member, BackingMember;
-        internal bool TagIsPinned;
-#endif
-        /// <summary>
-        /// Gets or sets the original name defined in the .proto; not used
-        /// during serialization.
-        /// </summary>
-        public string Name { get { return name; } set { name = value; } }
-        private string name;
-
-        /// <summary>
-        /// Gets or sets the data-format to be used when encoding this value.
-        /// </summary>
-        public DataFormat DataFormat { get { return dataFormat; } set { dataFormat = value; } }
-        private DataFormat dataFormat;
-
-        /// <summary>
-        /// Gets the unique tag used to identify this member within the type.
-        /// </summary>
-        public int Tag { get { return tag; } }
-        private int tag;
-        internal void Rebase(int tag) { this.tag = tag; }
-
-        /// <summary>
-        /// Gets or sets a value indicating whether this member is mandatory.
-        /// </summary>
-        public bool IsRequired
-        {
-            get { return (options & MemberSerializationOptions.Required) == MemberSerializationOptions.Required; }
-            set
-            {
-                if (value) options |= MemberSerializationOptions.Required;
-                else options &= ~MemberSerializationOptions.Required;
-            }
-        }
-
-        /// <summary>
-        /// Gets a value indicating whether this member is packed.
-        /// This option only applies to list/array data of primitive types (int, double, etc).
-        /// </summary>
-        public bool IsPacked
-        {
-            get { return (options & MemberSerializationOptions.Packed) == MemberSerializationOptions.Packed; }
-            set
-            {
-                if (value) options |= MemberSerializationOptions.Packed;
-                else options &= ~MemberSerializationOptions.Packed;
-            }
-        }
-
-        /// <summary>
-        /// Indicates whether this field should *repace* existing values (the default is false, meaning *append*).
-        /// This option only applies to list/array data.
-        /// </summary>
-        public bool OverwriteList
-        {
-            get { return (options & MemberSerializationOptions.OverwriteList) == MemberSerializationOptions.OverwriteList; }
-            set
-            {
-                if (value) options |= MemberSerializationOptions.OverwriteList;
-                else options &= ~MemberSerializationOptions.OverwriteList;
-            }
-        }
-
-        /// <summary>
-        /// Enables full object-tracking/full-graph support.
-        /// </summary>
-        public bool AsReference
-        {
-            get { return (options & MemberSerializationOptions.AsReference) == MemberSerializationOptions.AsReference; }
-            set
-            {
-                if (value) options |= MemberSerializationOptions.AsReference;
-                else options &= ~MemberSerializationOptions.AsReference;
-
-                options |= MemberSerializationOptions.AsReferenceHasValue;
-            }
-        }
-
-        internal bool AsReferenceHasValue
-        {
-            get { return (options & MemberSerializationOptions.AsReferenceHasValue) == MemberSerializationOptions.AsReferenceHasValue; }
-            set
-            {
-                if (value) options |= MemberSerializationOptions.AsReferenceHasValue;
-                else options &= ~MemberSerializationOptions.AsReferenceHasValue;
-            }
-        }
-
-        /// <summary>
-        /// Embeds the type information into the stream, allowing usage with types not known in advance.
-        /// </summary>
-        public bool DynamicType
-        {
-            get { return (options & MemberSerializationOptions.DynamicType) == MemberSerializationOptions.DynamicType; }
-            set
-            {
-                if (value) options |= MemberSerializationOptions.DynamicType;
-                else options &= ~MemberSerializationOptions.DynamicType;
-            }
-        }
-
-        /// <summary>
-        /// Gets or sets a value indicating whether this member is packed (lists/arrays).
-        /// </summary>
-        public MemberSerializationOptions Options { get { return options; } set { options = value; } }
-        private MemberSerializationOptions options;
-
-
-    }
-
-    /// <summary>
-    /// Additional (optional) settings that control serialization of members
-    /// </summary>
-    [Flags]
-    public enum MemberSerializationOptions
-    {
-        /// <summary>
-        /// Default; no additional options
-        /// </summary>
-        None = 0,
-        /// <summary>
-        /// Indicates that repeated elements should use packed (length-prefixed) encoding
-        /// </summary>
-        Packed = 1,
-        /// <summary>
-        /// Indicates that the given item is required
-        /// </summary>
-        Required = 2,
-        /// <summary>
-        /// Enables full object-tracking/full-graph support
-        /// </summary>
-        AsReference = 4,
-        /// <summary>
-        /// Embeds the type information into the stream, allowing usage with types not known in advance
-        /// </summary>
-        DynamicType = 8,
-        /// <summary>
-        /// Indicates whether this field should *repace* existing values (the default is false, meaning *append*).
-        /// This option only applies to list/array data.
-        /// </summary>
-        OverwriteList = 16,
-        /// <summary>
-        /// Determines whether the types AsReferenceDefault value is used, or whether this member's AsReference should be used
-        /// </summary>
-        AsReferenceHasValue = 32
-    }
-
-    /// <summary>
-    /// Declares a member to be used in protocol-buffer serialization, using
-    /// the given Tag and MemberName. This allows ProtoMemberAttribute usage
-    /// even for partial classes where the individual members are not
-    /// under direct control.
-    /// A DataFormat may be used to optimise the serialization
-    /// format (for instance, using zigzag encoding for negative numbers, or 
-    /// fixed-length encoding for large values.
-    /// </summary>
-    [AttributeUsage(AttributeTargets.Class,
-            AllowMultiple = true, Inherited = false)]
-    public sealed class ProtoPartialMemberAttribute : ProtoMemberAttribute
-    {
-        /// <summary>
-        /// Creates a new ProtoMemberAttribute instance.
-        /// </summary>
-        /// <param name="tag">Specifies the unique tag used to identify this member within the type.</param>
-        /// <param name="memberName">Specifies the member to be serialized.</param>
-        public ProtoPartialMemberAttribute(int tag, string memberName)
-            : base(tag)
-        {
-#if !NO_RUNTIME
-            if (string.IsNullOrEmpty(memberName)) throw new ArgumentNullException(nameof(memberName));
-#endif
-            this.MemberName = memberName;
-        }
-        /// <summary>
-        /// The name of the member to be serialized.
-        /// </summary>
-        public string MemberName { get; private set; }
-    }
-}

+ 0 - 1436
ThirdParty/protobuf-net/ProtoReader.cs

@@ -1,1436 +0,0 @@
-
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Text;
-using ProtoBuf.Meta;
-
-namespace ProtoBuf
-{
-    /// <summary>
-    /// A stateful reader, used to read a protobuf stream. Typical usage would be (sequentially) to call
-    /// ReadFieldHeader and (after matching the field) an appropriate Read* method.
-    /// </summary>
-    public sealed class ProtoReader : IDisposable
-    {
-        Stream source;
-        byte[] ioBuffer;
-        TypeModel model;
-        int fieldNumber, depth, ioIndex, available;
-        long position64, blockEnd64, dataRemaining64;
-        WireType wireType;
-        bool isFixedLength, internStrings;
-        private NetObjectCache netCache;
-
-        // this is how many outstanding objects do not currently have
-        // values for the purposes of reference tracking; we'll default
-        // to just trapping the root object
-        // note: objects are trapped (the ref and key mapped) via NoteObject
-        uint trapCount; // uint is so we can use beq/bne more efficiently than bgt
-
-        /// <summary>
-        /// Gets the number of the field being processed.
-        /// </summary>
-        public int FieldNumber => fieldNumber;
-
-        /// <summary>
-        /// Indicates the underlying proto serialization format on the wire.
-        /// </summary>
-        public WireType WireType => wireType;
-
-        /// <summary>
-        /// Creates a new reader against a stream
-        /// </summary>
-        /// <param name="source">The source stream</param>
-        /// <param name="model">The model to use for serialization; this can be null, but this will impair the ability to deserialize sub-objects</param>
-        /// <param name="context">Additional context about this serialization operation</param>
-        [Obsolete("Please use ProtoReader.Create; this API may be removed in a future version", error: false)]
-        public ProtoReader(Stream source, TypeModel model, SerializationContext context)
-        {
-
-            Init(this, source, model, context, TO_EOF);
-        }
-
-        internal const long TO_EOF = -1;
-
-        /// <summary>
-        /// Gets / sets a flag indicating whether strings should be checked for repetition; if
-        /// true, any repeated UTF-8 byte sequence will result in the same String instance, rather
-        /// than a second instance of the same string. Enabled by default. Note that this uses
-        /// a <i>custom</i> interner - the system-wide string interner is not used.
-        /// </summary>
-        public bool InternStrings { get { return internStrings; } set { internStrings = value; } }
-
-        /// <summary>
-        /// Creates a new reader against a stream
-        /// </summary>
-        /// <param name="source">The source stream</param>
-        /// <param name="model">The model to use for serialization; this can be null, but this will impair the ability to deserialize sub-objects</param>
-        /// <param name="context">Additional context about this serialization operation</param>
-        /// <param name="length">The number of bytes to read, or -1 to read until the end of the stream</param>
-        [Obsolete("Please use ProtoReader.Create; this API may be removed in a future version", error: false)]
-        public ProtoReader(Stream source, TypeModel model, SerializationContext context, int length)
-        {
-            Init(this, source, model, context, length);
-        }
-
-        /// <summary>
-        /// Creates a new reader against a stream
-        /// </summary>
-        /// <param name="source">The source stream</param>
-        /// <param name="model">The model to use for serialization; this can be null, but this will impair the ability to deserialize sub-objects</param>
-        /// <param name="context">Additional context about this serialization operation</param>
-        /// <param name="length">The number of bytes to read, or -1 to read until the end of the stream</param>
-        [Obsolete("Please use ProtoReader.Create; this API may be removed in a future version", error: false)]
-        public ProtoReader(Stream source, TypeModel model, SerializationContext context, long length)
-        {
-            Init(this, source, model, context, length);
-        }
-
-        private static void Init(ProtoReader reader, Stream source, TypeModel model, SerializationContext context, long length)
-        {
-            if (source == null) throw new ArgumentNullException(nameof(source));
-            if (!source.CanRead) throw new ArgumentException("Cannot read from stream", nameof(source));
-            reader.source = source;
-            reader.ioBuffer = BufferPool.GetBuffer();
-            reader.model = model;
-            bool isFixedLength = length >= 0;
-            reader.isFixedLength = isFixedLength;
-            reader.dataRemaining64 = isFixedLength ? length : 0;
-
-            if (context == null) { context = SerializationContext.Default; }
-            else { context.Freeze(); }
-            reader.context = context;
-            reader.position64 = 0;
-            reader.available = reader.depth = reader.fieldNumber = reader.ioIndex = 0;
-            reader.blockEnd64 = long.MaxValue;
-            reader.internStrings = RuntimeTypeModel.Default.InternStrings;
-            reader.wireType = WireType.None;
-            reader.trapCount = 1;
-            if (reader.netCache == null) reader.netCache = new NetObjectCache();
-        }
-
-        private SerializationContext context;
-
-        /// <summary>
-        /// Addition information about this deserialization operation.
-        /// </summary>
-        public SerializationContext Context => context;
-
-        /// <summary>
-        /// Releases resources used by the reader, but importantly <b>does not</b> Dispose the 
-        /// underlying stream; in many typical use-cases the stream is used for different
-        /// processes, so it is assumed that the consumer will Dispose their stream separately.
-        /// </summary>
-        public void Dispose()
-        {
-            // importantly, this does **not** own the stream, and does not dispose it
-            source = null;
-            model = null;
-            BufferPool.ReleaseBufferToPool(ref ioBuffer);
-            if (stringInterner != null)
-            {
-                stringInterner.Clear();
-                stringInterner = null;
-            }
-            if (netCache != null) netCache.Clear();
-        }
-        internal int TryReadUInt32VariantWithoutMoving(bool trimNegative, out uint value)
-        {
-            if (available < 10) Ensure(10, false);
-            if (available == 0)
-            {
-                value = 0;
-                return 0;
-            }
-            int readPos = ioIndex;
-            value = ioBuffer[readPos++];
-            if ((value & 0x80) == 0) return 1;
-            value &= 0x7F;
-            if (available == 1) throw EoF(this);
-
-            uint chunk = ioBuffer[readPos++];
-            value |= (chunk & 0x7F) << 7;
-            if ((chunk & 0x80) == 0) return 2;
-            if (available == 2) throw EoF(this);
-
-            chunk = ioBuffer[readPos++];
-            value |= (chunk & 0x7F) << 14;
-            if ((chunk & 0x80) == 0) return 3;
-            if (available == 3) throw EoF(this);
-
-            chunk = ioBuffer[readPos++];
-            value |= (chunk & 0x7F) << 21;
-            if ((chunk & 0x80) == 0) return 4;
-            if (available == 4) throw EoF(this);
-
-            chunk = ioBuffer[readPos];
-            value |= chunk << 28; // can only use 4 bits from this chunk
-            if ((chunk & 0xF0) == 0) return 5;
-
-            if (trimNegative // allow for -ve values
-                && (chunk & 0xF0) == 0xF0
-                && available >= 10
-                    && ioBuffer[++readPos] == 0xFF
-                    && ioBuffer[++readPos] == 0xFF
-                    && ioBuffer[++readPos] == 0xFF
-                    && ioBuffer[++readPos] == 0xFF
-                    && ioBuffer[++readPos] == 0x01)
-            {
-                return 10;
-            }
-            throw AddErrorData(new OverflowException(), this);
-        }
-
-        private uint ReadUInt32Variant(bool trimNegative)
-        {
-            int read = TryReadUInt32VariantWithoutMoving(trimNegative, out uint value);
-            if (read > 0)
-            {
-                ioIndex += read;
-                available -= read;
-                position64 += read;
-                return value;
-            }
-            throw EoF(this);
-        }
-
-        private bool TryReadUInt32Variant(out uint value)
-        {
-            int read = TryReadUInt32VariantWithoutMoving(false, out value);
-            if (read > 0)
-            {
-                ioIndex += read;
-                available -= read;
-                position64 += read;
-                return true;
-            }
-            return false;
-        }
-
-        /// <summary>
-        /// Reads an unsigned 32-bit integer from the stream; supported wire-types: Variant, Fixed32, Fixed64
-        /// </summary>
-        public uint ReadUInt32()
-        {
-            switch (wireType)
-            {
-                case WireType.Variant:
-                    return ReadUInt32Variant(false);
-                case WireType.Fixed32:
-                    if (available < 4) Ensure(4, true);
-                    position64 += 4;
-                    available -= 4;
-                    return ((uint)ioBuffer[ioIndex++])
-                        | (((uint)ioBuffer[ioIndex++]) << 8)
-                        | (((uint)ioBuffer[ioIndex++]) << 16)
-                        | (((uint)ioBuffer[ioIndex++]) << 24);
-                case WireType.Fixed64:
-                    ulong val = ReadUInt64();
-                    checked { return (uint)val; }
-                default:
-                    throw CreateWireTypeException();
-            }
-        }
-
-        /// <summary>
-        /// Returns the position of the current reader (note that this is not necessarily the same as the position
-        /// in the underlying stream, if multiple readers are used on the same stream)
-        /// </summary>
-        public int Position { get { return checked((int)position64); } }
-
-        /// <summary>
-        /// Returns the position of the current reader (note that this is not necessarily the same as the position
-        /// in the underlying stream, if multiple readers are used on the same stream)
-        /// </summary>
-        public long LongPosition { get { return position64; } }
-        internal void Ensure(int count, bool strict)
-        {
-            Helpers.DebugAssert(available <= count, "Asking for data without checking first");
-            if (count > ioBuffer.Length)
-            {
-                BufferPool.ResizeAndFlushLeft(ref ioBuffer, count, ioIndex, available);
-                ioIndex = 0;
-            }
-            else if (ioIndex + count >= ioBuffer.Length)
-            {
-                // need to shift the buffer data to the left to make space
-                Buffer.BlockCopy(ioBuffer, ioIndex, ioBuffer, 0, available);
-                ioIndex = 0;
-            }
-            count -= available;
-            int writePos = ioIndex + available, bytesRead;
-            int canRead = ioBuffer.Length - writePos;
-            if (isFixedLength)
-            {   // throttle it if needed
-                if (dataRemaining64 < canRead) canRead = (int)dataRemaining64;
-            }
-            while (count > 0 && canRead > 0 && (bytesRead = source.Read(ioBuffer, writePos, canRead)) > 0)
-            {
-                available += bytesRead;
-                count -= bytesRead;
-                canRead -= bytesRead;
-                writePos += bytesRead;
-                if (isFixedLength) { dataRemaining64 -= bytesRead; }
-            }
-            if (strict && count > 0)
-            {
-                throw EoF(this);
-            }
-
-        }
-        /// <summary>
-        /// Reads a signed 16-bit integer from the stream: Variant, Fixed32, Fixed64, SignedVariant
-        /// </summary>
-        public short ReadInt16()
-        {
-            checked { return (short)ReadInt32(); }
-        }
-        /// <summary>
-        /// Reads an unsigned 16-bit integer from the stream; supported wire-types: Variant, Fixed32, Fixed64
-        /// </summary>
-        public ushort ReadUInt16()
-        {
-            checked { return (ushort)ReadUInt32(); }
-        }
-
-        /// <summary>
-        /// Reads an unsigned 8-bit integer from the stream; supported wire-types: Variant, Fixed32, Fixed64
-        /// </summary>
-        public byte ReadByte()
-        {
-            checked { return (byte)ReadUInt32(); }
-        }
-
-        /// <summary>
-        /// Reads a signed 8-bit integer from the stream; supported wire-types: Variant, Fixed32, Fixed64, SignedVariant
-        /// </summary>
-        public sbyte ReadSByte()
-        {
-            checked { return (sbyte)ReadInt32(); }
-        }
-
-        /// <summary>
-        /// Reads a signed 32-bit integer from the stream; supported wire-types: Variant, Fixed32, Fixed64, SignedVariant
-        /// </summary>
-        public int ReadInt32()
-        {
-            switch (wireType)
-            {
-                case WireType.Variant:
-                    return (int)ReadUInt32Variant(true);
-                case WireType.Fixed32:
-                    if (available < 4) Ensure(4, true);
-                    position64 += 4;
-                    available -= 4;
-                    return ((int)ioBuffer[ioIndex++])
-                        | (((int)ioBuffer[ioIndex++]) << 8)
-                        | (((int)ioBuffer[ioIndex++]) << 16)
-                        | (((int)ioBuffer[ioIndex++]) << 24);
-                case WireType.Fixed64:
-                    long l = ReadInt64();
-                    checked { return (int)l; }
-                case WireType.SignedVariant:
-                    return Zag(ReadUInt32Variant(true));
-                default:
-                    throw CreateWireTypeException();
-            }
-        }
-        private const long Int64Msb = ((long)1) << 63;
-        private const int Int32Msb = ((int)1) << 31;
-        private static int Zag(uint ziggedValue)
-        {
-            int value = (int)ziggedValue;
-            return (-(value & 0x01)) ^ ((value >> 1) & ~ProtoReader.Int32Msb);
-        }
-
-        private static long Zag(ulong ziggedValue)
-        {
-            long value = (long)ziggedValue;
-            return (-(value & 0x01L)) ^ ((value >> 1) & ~ProtoReader.Int64Msb);
-        }
-        /// <summary>
-        /// Reads a signed 64-bit integer from the stream; supported wire-types: Variant, Fixed32, Fixed64, SignedVariant
-        /// </summary>
-        public long ReadInt64()
-        {
-            switch (wireType)
-            {
-                case WireType.Variant:
-                    return (long)ReadUInt64Variant();
-                case WireType.Fixed32:
-                    return ReadInt32();
-                case WireType.Fixed64:
-                    if (available < 8) Ensure(8, true);
-                    position64 += 8;
-                    available -= 8;
-
-#if NETCOREAPP2_1
-                    var result = System.Buffers.Binary.BinaryPrimitives.ReadInt64LittleEndian(ioBuffer.AsSpan(ioIndex, 8));
-
-                    ioIndex+= 8;
-
-                    return result;
-#else
-                    return ((long)ioBuffer[ioIndex++])
-                        | (((long)ioBuffer[ioIndex++]) << 8)
-                        | (((long)ioBuffer[ioIndex++]) << 16)
-                        | (((long)ioBuffer[ioIndex++]) << 24)
-                        | (((long)ioBuffer[ioIndex++]) << 32)
-                        | (((long)ioBuffer[ioIndex++]) << 40)
-                        | (((long)ioBuffer[ioIndex++]) << 48)
-                        | (((long)ioBuffer[ioIndex++]) << 56);
-#endif
-                case WireType.SignedVariant:
-                    return Zag(ReadUInt64Variant());
-                default:
-                    throw CreateWireTypeException();
-            }
-        }
-
-        private int TryReadUInt64VariantWithoutMoving(out ulong value)
-        {
-            if (available < 10) Ensure(10, false);
-            if (available == 0)
-            {
-                value = 0;
-                return 0;
-            }
-            int readPos = ioIndex;
-            value = ioBuffer[readPos++];
-            if ((value & 0x80) == 0) return 1;
-            value &= 0x7F;
-            if (available == 1) throw EoF(this);
-
-            ulong chunk = ioBuffer[readPos++];
-            value |= (chunk & 0x7F) << 7;
-            if ((chunk & 0x80) == 0) return 2;
-            if (available == 2) throw EoF(this);
-
-            chunk = ioBuffer[readPos++];
-            value |= (chunk & 0x7F) << 14;
-            if ((chunk & 0x80) == 0) return 3;
-            if (available == 3) throw EoF(this);
-
-            chunk = ioBuffer[readPos++];
-            value |= (chunk & 0x7F) << 21;
-            if ((chunk & 0x80) == 0) return 4;
-            if (available == 4) throw EoF(this);
-
-            chunk = ioBuffer[readPos++];
-            value |= (chunk & 0x7F) << 28;
-            if ((chunk & 0x80) == 0) return 5;
-            if (available == 5) throw EoF(this);
-
-            chunk = ioBuffer[readPos++];
-            value |= (chunk & 0x7F) << 35;
-            if ((chunk & 0x80) == 0) return 6;
-            if (available == 6) throw EoF(this);
-
-            chunk = ioBuffer[readPos++];
-            value |= (chunk & 0x7F) << 42;
-            if ((chunk & 0x80) == 0) return 7;
-            if (available == 7) throw EoF(this);
-
-
-            chunk = ioBuffer[readPos++];
-            value |= (chunk & 0x7F) << 49;
-            if ((chunk & 0x80) == 0) return 8;
-            if (available == 8) throw EoF(this);
-
-            chunk = ioBuffer[readPos++];
-            value |= (chunk & 0x7F) << 56;
-            if ((chunk & 0x80) == 0) return 9;
-            if (available == 9) throw EoF(this);
-
-            chunk = ioBuffer[readPos];
-            value |= chunk << 63; // can only use 1 bit from this chunk
-
-            if ((chunk & ~(ulong)0x01) != 0) throw AddErrorData(new OverflowException(), this);
-            return 10;
-        }
-
-        private ulong ReadUInt64Variant()
-        {
-            int read = TryReadUInt64VariantWithoutMoving(out ulong value);
-            if (read > 0)
-            {
-                ioIndex += read;
-                available -= read;
-                position64 += read;
-                return value;
-            }
-            throw EoF(this);
-        }
-
-        private Dictionary<string, string> stringInterner;
-        private string Intern(string value)
-        {
-            if (value == null) return null;
-            if (value.Length == 0) return "";
-            if (stringInterner == null)
-            {
-                stringInterner = new Dictionary<string, string>
-                {
-                    { value, value }
-                };
-            }
-            else if (stringInterner.TryGetValue(value, out string found))
-            {
-                value = found;
-            }
-            else
-            {
-                stringInterner.Add(value, value);
-            }
-            return value;
-        }
-
-#if COREFX
-        static readonly Encoding encoding = Encoding.UTF8;
-#else
-        static readonly UTF8Encoding encoding = new UTF8Encoding();
-#endif
-        /// <summary>
-        /// Reads a string from the stream (using UTF8); supported wire-types: String
-        /// </summary>
-        public string ReadString()
-        {
-            if (wireType == WireType.String)
-            {
-                int bytes = (int)ReadUInt32Variant(false);
-                if (bytes == 0) return "";
-                if (available < bytes) Ensure(bytes, true);
-
-                string s = encoding.GetString(ioBuffer, ioIndex, bytes);
-
-                if (internStrings) { s = Intern(s); }
-                available -= bytes;
-                position64 += bytes;
-                ioIndex += bytes;
-                return s;
-            }
-            throw CreateWireTypeException();
-        }
-        /// <summary>
-        /// Throws an exception indication that the given value cannot be mapped to an enum.
-        /// </summary>
-        public void ThrowEnumException(Type type, int value)
-        {
-            string desc = type == null ? "<null>" : type.FullName;
-            throw AddErrorData(new ProtoException("No " + desc + " enum is mapped to the wire-value " + value.ToString()), this);
-        }
-
-        private Exception CreateWireTypeException()
-        {
-            return CreateException("Invalid wire-type; this usually means you have over-written a file without truncating or setting the length; see https://stackoverflow.com/q/2152978/23354");
-        }
-
-        private Exception CreateException(string message)
-        {
-            return AddErrorData(new ProtoException(message), this);
-        }
-        /// <summary>
-        /// Reads a double-precision number from the stream; supported wire-types: Fixed32, Fixed64
-        /// </summary>
-        public
-#if !FEAT_SAFE
- unsafe
-#endif
- double ReadDouble()
-        {
-            switch (wireType)
-            {
-                case WireType.Fixed32:
-                    return ReadSingle();
-                case WireType.Fixed64:
-                    long value = ReadInt64();
-#if FEAT_SAFE
-                    return BitConverter.ToDouble(BitConverter.GetBytes(value), 0);
-#else
-                    return *(double*)&value;
-#endif
-                default:
-                    throw CreateWireTypeException();
-            }
-        }
-
-        /// <summary>
-        /// Reads (merges) a sub-message from the stream, internally calling StartSubItem and EndSubItem, and (in between)
-        /// parsing the message in accordance with the model associated with the reader
-        /// </summary>
-        public static object ReadObject(object value, int key, ProtoReader reader)
-        {
-            return ReadTypedObject(value, key, reader, null);
-        }
-
-        internal static object ReadTypedObject(object value, int key, ProtoReader reader, Type type)
-        {
-            if (reader.model == null)
-            {
-                throw AddErrorData(new InvalidOperationException("Cannot deserialize sub-objects unless a model is provided"), reader);
-            }
-            SubItemToken token = ProtoReader.StartSubItem(reader);
-            if (key >= 0)
-            {
-                value = reader.model.Deserialize(key, value, reader);
-            }
-            else if (type != null && reader.model.TryDeserializeAuxiliaryType(reader, DataFormat.Default, Serializer.ListItemTag, type, ref value, true, false, true, false, null))
-            {
-                // ok
-            }
-            else
-            {
-                TypeModel.ThrowUnexpectedType(type);
-            }
-            ProtoReader.EndSubItem(token, reader);
-            return value;
-        }
-
-        /// <summary>
-        /// Makes the end of consuming a nested message in the stream; the stream must be either at the correct EndGroup
-        /// marker, or all fields of the sub-message must have been consumed (in either case, this means ReadFieldHeader
-        /// should return zero)
-        /// </summary>
-        public static void EndSubItem(SubItemToken token, ProtoReader reader)
-        {
-            if (reader == null) throw new ArgumentNullException("reader");
-            long value64 = token.value64;
-            switch (reader.wireType)
-            {
-                case WireType.EndGroup:
-                    if (value64 >= 0) throw AddErrorData(new ArgumentException("token"), reader);
-                    if (-(int)value64 != reader.fieldNumber) throw reader.CreateException("Wrong group was ended"); // wrong group ended!
-                    reader.wireType = WireType.None; // this releases ReadFieldHeader
-                    reader.depth--;
-                    break;
-                // case WireType.None: // TODO reinstate once reads reset the wire-type
-                default:
-                    if (value64 < reader.position64) throw reader.CreateException($"Sub-message not read entirely; expected {value64}, was {reader.position64}");
-                    if (reader.blockEnd64 != reader.position64 && reader.blockEnd64 != long.MaxValue)
-                    {
-                        throw reader.CreateException("Sub-message not read correctly");
-                    }
-                    reader.blockEnd64 = value64;
-                    reader.depth--;
-                    break;
-                    /*default:
-                        throw reader.BorkedIt(); */
-            }
-        }
-
-        /// <summary>
-        /// Begins consuming a nested message in the stream; supported wire-types: StartGroup, String
-        /// </summary>
-        /// <remarks>The token returned must be help and used when callining EndSubItem</remarks>
-        public static SubItemToken StartSubItem(ProtoReader reader)
-        {
-            if (reader == null) throw new ArgumentNullException("reader");
-            switch (reader.wireType)
-            {
-                case WireType.StartGroup:
-                    reader.wireType = WireType.None; // to prevent glitches from double-calling
-                    reader.depth++;
-                    return new SubItemToken((long)(-reader.fieldNumber));
-                case WireType.String:
-                    long len = (long)reader.ReadUInt64Variant();
-                    if (len < 0) throw AddErrorData(new InvalidOperationException(), reader);
-                    long lastEnd = reader.blockEnd64;
-                    reader.blockEnd64 = reader.position64 + len;
-                    reader.depth++;
-                    return new SubItemToken(lastEnd);
-                default:
-                    throw reader.CreateWireTypeException(); // throws
-            }
-        }
-
-        /// <summary>
-        /// Reads a field header from the stream, setting the wire-type and retuning the field number. If no
-        /// more fields are available, then 0 is returned. This methods respects sub-messages.
-        /// </summary>
-        public int ReadFieldHeader()
-        {
-            // at the end of a group the caller must call EndSubItem to release the
-            // reader (which moves the status to Error, since ReadFieldHeader must
-            // then be called)
-            if (blockEnd64 <= position64 || wireType == WireType.EndGroup) { return 0; }
-
-            if (TryReadUInt32Variant(out uint tag) && tag != 0)
-            {
-                wireType = (WireType)(tag & 7);
-                fieldNumber = (int)(tag >> 3);
-                if (fieldNumber < 1) throw new ProtoException("Invalid field in source data: " + fieldNumber.ToString());
-            }
-            else
-            {
-                wireType = WireType.None;
-                fieldNumber = 0;
-            }
-            if (wireType == ProtoBuf.WireType.EndGroup)
-            {
-                if (depth > 0) return 0; // spoof an end, but note we still set the field-number
-                throw new ProtoException("Unexpected end-group in source data; this usually means the source data is corrupt");
-            }
-            return fieldNumber;
-        }
-        /// <summary>
-        /// Looks ahead to see whether the next field in the stream is what we expect
-        /// (typically; what we've just finished reading - for example ot read successive list items)
-        /// </summary>
-        public bool TryReadFieldHeader(int field)
-        {
-            // check for virtual end of stream
-            if (blockEnd64 <= position64 || wireType == WireType.EndGroup) { return false; }
-
-            int read = TryReadUInt32VariantWithoutMoving(false, out uint tag);
-            WireType tmpWireType; // need to catch this to exclude (early) any "end group" tokens
-            if (read > 0 && ((int)tag >> 3) == field
-                && (tmpWireType = (WireType)(tag & 7)) != WireType.EndGroup)
-            {
-                wireType = tmpWireType;
-                fieldNumber = field;
-                position64 += read;
-                ioIndex += read;
-                available -= read;
-                return true;
-            }
-            return false;
-        }
-
-        /// <summary>
-        /// Get the TypeModel associated with this reader
-        /// </summary>
-        public TypeModel Model { get { return model; } }
-
-        /// <summary>
-        /// Compares the streams current wire-type to the hinted wire-type, updating the reader if necessary; for example,
-        /// a Variant may be updated to SignedVariant. If the hinted wire-type is unrelated then no change is made.
-        /// </summary>
-        public void Hint(WireType wireType)
-        {
-            if (this.wireType == wireType) { }  // fine; everything as we expect
-            else if (((int)wireType & 7) == (int)this.wireType)
-            {   // the underling type is a match; we're customising it with an extension
-                this.wireType = wireType;
-            }
-            // note no error here; we're OK about using alternative data
-        }
-
-        /// <summary>
-        /// Verifies that the stream's current wire-type is as expected, or a specialized sub-type (for example,
-        /// SignedVariant) - in which case the current wire-type is updated. Otherwise an exception is thrown.
-        /// </summary>
-        public void Assert(WireType wireType)
-        {
-            if (this.wireType == wireType) { }  // fine; everything as we expect
-            else if (((int)wireType & 7) == (int)this.wireType)
-            {   // the underling type is a match; we're customising it with an extension
-                this.wireType = wireType;
-            }
-            else
-            {   // nope; that is *not* what we were expecting!
-                throw CreateWireTypeException();
-            }
-        }
-
-        /// <summary>
-        /// Discards the data for the current field.
-        /// </summary>
-        public void SkipField()
-        {
-            switch (wireType)
-            {
-                case WireType.Fixed32:
-                    if (available < 4) Ensure(4, true);
-                    available -= 4;
-                    ioIndex += 4;
-                    position64 += 4;
-                    return;
-                case WireType.Fixed64:
-                    if (available < 8) Ensure(8, true);
-                    available -= 8;
-                    ioIndex += 8;
-                    position64 += 8;
-                    return;
-                case WireType.String:
-                    long len = (long)ReadUInt64Variant();
-                    if (len <= available)
-                    { // just jump it!
-                        available -= (int)len;
-                        ioIndex += (int)len;
-                        position64 += len;
-                        return;
-                    }
-                    // everything remaining in the buffer is garbage
-                    position64 += len; // assumes success, but if it fails we're screwed anyway
-                    len -= available; // discount anything we've got to-hand
-                    ioIndex = available = 0; // note that we have no data in the buffer
-                    if (isFixedLength)
-                    {
-                        if (len > dataRemaining64) throw EoF(this);
-                        // else assume we're going to be OK
-                        dataRemaining64 -= len;
-                    }
-                    ProtoReader.Seek(source, len, ioBuffer);
-                    return;
-                case WireType.Variant:
-                case WireType.SignedVariant:
-                    ReadUInt64Variant(); // and drop it
-                    return;
-                case WireType.StartGroup:
-                    int originalFieldNumber = this.fieldNumber;
-                    depth++; // need to satisfy the sanity-checks in ReadFieldHeader
-                    while (ReadFieldHeader() > 0) { SkipField(); }
-                    depth--;
-                    if (wireType == WireType.EndGroup && fieldNumber == originalFieldNumber)
-                    { // we expect to exit in a similar state to how we entered
-                        wireType = ProtoBuf.WireType.None;
-                        return;
-                    }
-                    throw CreateWireTypeException();
-                case WireType.None: // treat as explicit errorr
-                case WireType.EndGroup: // treat as explicit error
-                default: // treat as implicit error
-                    throw CreateWireTypeException();
-            }
-        }
-
-        /// <summary>
-        /// Reads an unsigned 64-bit integer from the stream; supported wire-types: Variant, Fixed32, Fixed64
-        /// </summary>
-        public ulong ReadUInt64()
-        {
-            switch (wireType)
-            {
-                case WireType.Variant:
-                    return ReadUInt64Variant();
-                case WireType.Fixed32:
-                    return ReadUInt32();
-                case WireType.Fixed64:
-                    if (available < 8) Ensure(8, true);
-                    position64 += 8;
-                    available -= 8;
-
-                    return ((ulong)ioBuffer[ioIndex++])
-                        | (((ulong)ioBuffer[ioIndex++]) << 8)
-                        | (((ulong)ioBuffer[ioIndex++]) << 16)
-                        | (((ulong)ioBuffer[ioIndex++]) << 24)
-                        | (((ulong)ioBuffer[ioIndex++]) << 32)
-                        | (((ulong)ioBuffer[ioIndex++]) << 40)
-                        | (((ulong)ioBuffer[ioIndex++]) << 48)
-                        | (((ulong)ioBuffer[ioIndex++]) << 56);
-                default:
-                    throw CreateWireTypeException();
-            }
-        }
-        /// <summary>
-        /// Reads a single-precision number from the stream; supported wire-types: Fixed32, Fixed64
-        /// </summary>
-        public
-#if !FEAT_SAFE
- unsafe
-#endif
- float ReadSingle()
-        {
-            switch (wireType)
-            {
-                case WireType.Fixed32:
-                    {
-                        int value = ReadInt32();
-#if FEAT_SAFE
-                        return BitConverter.ToSingle(BitConverter.GetBytes(value), 0);
-#else
-                        return *(float*)&value;
-#endif
-                    }
-                case WireType.Fixed64:
-                    {
-                        double value = ReadDouble();
-                        float f = (float)value;
-                        if (float.IsInfinity(f) && !double.IsInfinity(value))
-                        {
-                            throw AddErrorData(new OverflowException(), this);
-                        }
-                        return f;
-                    }
-                default:
-                    throw CreateWireTypeException();
-            }
-        }
-
-        /// <summary>
-        /// Reads a boolean value from the stream; supported wire-types: Variant, Fixed32, Fixed64
-        /// </summary>
-        /// <returns></returns>
-        public bool ReadBoolean()
-        {
-            switch (ReadUInt32())
-            {
-                case 0: return false;
-                case 1: return true;
-                default: throw CreateException("Unexpected boolean value");
-            }
-        }
-
-        private static readonly byte[] EmptyBlob = new byte[0];
-        /// <summary>
-        /// Reads a byte-sequence from the stream, appending them to an existing byte-sequence (which can be null); supported wire-types: String
-        /// </summary>
-        public static byte[] AppendBytes(byte[] value, ProtoReader reader)
-        {
-            if (reader == null) throw new ArgumentNullException(nameof(reader));
-            switch (reader.wireType)
-            {
-                case WireType.String:
-                    int len = (int)reader.ReadUInt32Variant(false);
-                    reader.wireType = WireType.None;
-                    if (len == 0) return value ?? EmptyBlob;
-                    int offset;
-                    if (value == null || value.Length == 0)
-                    {
-                        offset = 0;
-                        value = new byte[len];
-                    }
-                    else
-                    {
-                        offset = value.Length;
-                        byte[] tmp = new byte[value.Length + len];
-                        Buffer.BlockCopy(value, 0, tmp, 0, value.Length);
-                        value = tmp;
-                    }
-                    // value is now sized with the final length, and (if necessary)
-                    // contains the old data up to "offset"
-                    reader.position64 += len; // assume success
-                    while (len > reader.available)
-                    {
-                        if (reader.available > 0)
-                        {
-                            // copy what we *do* have
-                            Buffer.BlockCopy(reader.ioBuffer, reader.ioIndex, value, offset, reader.available);
-                            len -= reader.available;
-                            offset += reader.available;
-                            reader.ioIndex = reader.available = 0; // we've drained the buffer
-                        }
-                        //  now refill the buffer (without overflowing it)
-                        int count = len > reader.ioBuffer.Length ? reader.ioBuffer.Length : len;
-                        if (count > 0) reader.Ensure(count, true);
-                    }
-                    // at this point, we know that len <= available
-                    if (len > 0)
-                    {   // still need data, but we have enough buffered
-                        Buffer.BlockCopy(reader.ioBuffer, reader.ioIndex, value, offset, len);
-                        reader.ioIndex += len;
-                        reader.available -= len;
-                    }
-                    return value;
-                case WireType.Variant:
-                    return new byte[0];
-                default:
-                    throw reader.CreateWireTypeException();
-            }
-        }
-
-        //static byte[] ReadBytes(Stream stream, int length)
-        //{
-        //    if (stream == null) throw new ArgumentNullException("stream");
-        //    if (length < 0) throw new ArgumentOutOfRangeException("length");
-        //    byte[] buffer = new byte[length];
-        //    int offset = 0, read;
-        //    while (length > 0 && (read = stream.Read(buffer, offset, length)) > 0)
-        //    {
-        //        length -= read;
-        //    }
-        //    if (length > 0) throw EoF(null);
-        //    return buffer;
-        //}
-        private static int ReadByteOrThrow(Stream source)
-        {
-            int val = source.ReadByte();
-            if (val < 0) throw EoF(null);
-            return val;
-        }
-
-        /// <summary>
-        /// Reads the length-prefix of a message from a stream without buffering additional data, allowing a fixed-length
-        /// reader to be created.
-        /// </summary>
-        public static int ReadLengthPrefix(Stream source, bool expectHeader, PrefixStyle style, out int fieldNumber)
-            => ReadLengthPrefix(source, expectHeader, style, out fieldNumber, out int bytesRead);
-
-        /// <summary>
-        /// Reads a little-endian encoded integer. An exception is thrown if the data is not all available.
-        /// </summary>
-        public static int DirectReadLittleEndianInt32(Stream source)
-        {
-            return ReadByteOrThrow(source)
-                | (ReadByteOrThrow(source) << 8)
-                | (ReadByteOrThrow(source) << 16)
-                | (ReadByteOrThrow(source) << 24);
-        }
-
-        /// <summary>
-        /// Reads a big-endian encoded integer. An exception is thrown if the data is not all available.
-        /// </summary>
-        public static int DirectReadBigEndianInt32(Stream source)
-        {
-            return (ReadByteOrThrow(source) << 24)
-                 | (ReadByteOrThrow(source) << 16)
-                 | (ReadByteOrThrow(source) << 8)
-                 | ReadByteOrThrow(source);
-        }
-
-        /// <summary>
-        /// Reads a varint encoded integer. An exception is thrown if the data is not all available.
-        /// </summary>
-        public static int DirectReadVarintInt32(Stream source)
-        {
-            int bytes = TryReadUInt64Variant(source, out ulong val);
-            if (bytes <= 0) throw EoF(null);
-            return checked((int)val);
-        }
-
-        /// <summary>
-        /// Reads a string (of a given lenth, in bytes) directly from the source into a pre-existing buffer. An exception is thrown if the data is not all available.
-        /// </summary>
-        public static void DirectReadBytes(Stream source, byte[] buffer, int offset, int count)
-        {
-            int read;
-            if (source == null) throw new ArgumentNullException("source");
-            while (count > 0 && (read = source.Read(buffer, offset, count)) > 0)
-            {
-                count -= read;
-                offset += read;
-            }
-            if (count > 0) throw EoF(null);
-        }
-
-        /// <summary>
-        /// Reads a given number of bytes directly from the source. An exception is thrown if the data is not all available.
-        /// </summary>
-        public static byte[] DirectReadBytes(Stream source, int count)
-        {
-            byte[] buffer = new byte[count];
-            DirectReadBytes(source, buffer, 0, count);
-            return buffer;
-        }
-
-        /// <summary>
-        /// Reads a string (of a given lenth, in bytes) directly from the source. An exception is thrown if the data is not all available.
-        /// </summary>
-        public static string DirectReadString(Stream source, int length)
-        {
-            byte[] buffer = new byte[length];
-            DirectReadBytes(source, buffer, 0, length);
-            return Encoding.UTF8.GetString(buffer, 0, length);
-        }
-
-        /// <summary>
-        /// Reads the length-prefix of a message from a stream without buffering additional data, allowing a fixed-length
-        /// reader to be created.
-        /// </summary>
-        public static int ReadLengthPrefix(Stream source, bool expectHeader, PrefixStyle style, out int fieldNumber, out int bytesRead)
-        {
-            if (style == PrefixStyle.None)
-            {
-                bytesRead = fieldNumber = 0;
-                return int.MaxValue; // avoid the long.maxvalue causing overflow
-            }
-            long len64 = ReadLongLengthPrefix(source, expectHeader, style, out fieldNumber, out bytesRead);
-            return checked((int)len64);
-        }
-
-        /// <summary>
-        /// Reads the length-prefix of a message from a stream without buffering additional data, allowing a fixed-length
-        /// reader to be created.
-        /// </summary>
-        public static long ReadLongLengthPrefix(Stream source, bool expectHeader, PrefixStyle style, out int fieldNumber, out int bytesRead)
-        {
-            fieldNumber = 0;
-            switch (style)
-            {
-                case PrefixStyle.None:
-                    bytesRead = 0;
-                    return long.MaxValue;
-                case PrefixStyle.Base128:
-                    ulong val;
-                    int tmpBytesRead;
-                    bytesRead = 0;
-                    if (expectHeader)
-                    {
-                        tmpBytesRead = ProtoReader.TryReadUInt64Variant(source, out val);
-                        bytesRead += tmpBytesRead;
-                        if (tmpBytesRead > 0)
-                        {
-                            if ((val & 7) != (uint)WireType.String)
-                            { // got a header, but it isn't a string
-                                throw new InvalidOperationException();
-                            }
-                            fieldNumber = (int)(val >> 3);
-                            tmpBytesRead = ProtoReader.TryReadUInt64Variant(source, out val);
-                            bytesRead += tmpBytesRead;
-                            if (bytesRead == 0)
-                            { // got a header, but no length
-                                throw EoF(null);
-                            }
-                            return (long)val;
-                        }
-                        else
-                        { // no header
-                            bytesRead = 0;
-                            return -1;
-                        }
-                    }
-                    // check for a length
-                    tmpBytesRead = ProtoReader.TryReadUInt64Variant(source, out val);
-                    bytesRead += tmpBytesRead;
-                    return bytesRead < 0 ? -1 : (long)val;
-
-                case PrefixStyle.Fixed32:
-                    {
-                        int b = source.ReadByte();
-                        if (b < 0)
-                        {
-                            bytesRead = 0;
-                            return -1;
-                        }
-                        bytesRead = 4;
-                        return b
-                             | (ReadByteOrThrow(source) << 8)
-                             | (ReadByteOrThrow(source) << 16)
-                             | (ReadByteOrThrow(source) << 24);
-                    }
-                case PrefixStyle.Fixed32BigEndian:
-                    {
-                        int b = source.ReadByte();
-                        if (b < 0)
-                        {
-                            bytesRead = 0;
-                            return -1;
-                        }
-                        bytesRead = 4;
-                        return (b << 24)
-                            | (ReadByteOrThrow(source) << 16)
-                            | (ReadByteOrThrow(source) << 8)
-                            | ReadByteOrThrow(source);
-                    }
-                default:
-                    throw new ArgumentOutOfRangeException("style");
-            }
-        }
-
-        /// <returns>The number of bytes consumed; 0 if no data available</returns>
-        private static int TryReadUInt64Variant(Stream source, out ulong value)
-        {
-            value = 0;
-            int b = source.ReadByte();
-            if (b < 0) { return 0; }
-            value = (uint)b;
-            if ((value & 0x80) == 0) { return 1; }
-            value &= 0x7F;
-            int bytesRead = 1, shift = 7;
-            while (bytesRead < 9)
-            {
-                b = source.ReadByte();
-                if (b < 0) throw EoF(null);
-                value |= ((ulong)b & 0x7F) << shift;
-                shift += 7;
-                bytesRead++;
-
-                if ((b & 0x80) == 0) return bytesRead;
-            }
-            b = source.ReadByte();
-            if (b < 0) throw EoF(null);
-            if ((b & 1) == 0) // only use 1 bit from the last byte
-            {
-                value |= ((ulong)b & 0x7F) << shift;
-                return ++bytesRead;
-            }
-            throw new OverflowException();
-        }
-
-        internal static void Seek(Stream source, long count, byte[] buffer)
-        {
-            if (source.CanSeek)
-            {
-                source.Seek(count, SeekOrigin.Current);
-                count = 0;
-            }
-            else if (buffer != null)
-            {
-                int bytesRead;
-                while (count > buffer.Length && (bytesRead = source.Read(buffer, 0, buffer.Length)) > 0)
-                {
-                    count -= bytesRead;
-                }
-                while (count > 0 && (bytesRead = source.Read(buffer, 0, (int)count)) > 0)
-                {
-                    count -= bytesRead;
-                }
-            }
-            else // borrow a buffer
-            {
-                buffer = BufferPool.GetBuffer();
-                try
-                {
-                    int bytesRead;
-                    while (count > buffer.Length && (bytesRead = source.Read(buffer, 0, buffer.Length)) > 0)
-                    {
-                        count -= bytesRead;
-                    }
-                    while (count > 0 && (bytesRead = source.Read(buffer, 0, (int)count)) > 0)
-                    {
-                        count -= bytesRead;
-                    }
-                }
-                finally
-                {
-                    BufferPool.ReleaseBufferToPool(ref buffer);
-                }
-            }
-            if (count > 0) throw EoF(null);
-        }
-        internal static Exception AddErrorData(Exception exception, ProtoReader source)
-        {
-#if !CF && !PORTABLE
-            if (exception != null && source != null && !exception.Data.Contains("protoSource"))
-            {
-                exception.Data.Add("protoSource", string.Format("tag={0}; wire-type={1}; offset={2}; depth={3}",
-                    source.fieldNumber, source.wireType, source.position64, source.depth));
-            }
-#endif
-            return exception;
-        }
-
-        private static Exception EoF(ProtoReader source)
-        {
-            return AddErrorData(new EndOfStreamException(), source);
-        }
-
-        /// <summary>
-        /// Copies the current field into the instance as extension data
-        /// </summary>
-        public void AppendExtensionData(IExtensible instance)
-        {
-            if (instance == null) throw new ArgumentNullException(nameof(instance));
-            IExtension extn = instance.GetExtensionObject(true);
-            bool commit = false;
-            // unusually we *don't* want "using" here; the "finally" does that, with
-            // the extension object being responsible for disposal etc
-            Stream dest = extn.BeginAppend();
-            try
-            {
-                //TODO: replace this with stream-based, buffered raw copying
-                using (ProtoWriter writer = ProtoWriter.Create(dest, model, null))
-                {
-                    AppendExtensionField(writer);
-                    writer.Close();
-                }
-                commit = true;
-            }
-            finally { extn.EndAppend(dest, commit); }
-        }
-
-        private void AppendExtensionField(ProtoWriter writer)
-        {
-            //TODO: replace this with stream-based, buffered raw copying
-            ProtoWriter.WriteFieldHeader(fieldNumber, wireType, writer);
-            switch (wireType)
-            {
-                case WireType.Fixed32:
-                    ProtoWriter.WriteInt32(ReadInt32(), writer);
-                    return;
-                case WireType.Variant:
-                case WireType.SignedVariant:
-                case WireType.Fixed64:
-                    ProtoWriter.WriteInt64(ReadInt64(), writer);
-                    return;
-                case WireType.String:
-                    ProtoWriter.WriteBytes(AppendBytes(null, this), writer);
-                    return;
-                case WireType.StartGroup:
-                    SubItemToken readerToken = StartSubItem(this),
-                        writerToken = ProtoWriter.StartSubItem(null, writer);
-                    while (ReadFieldHeader() > 0) { AppendExtensionField(writer); }
-                    EndSubItem(readerToken, this);
-                    ProtoWriter.EndSubItem(writerToken, writer);
-                    return;
-                case WireType.None: // treat as explicit errorr
-                case WireType.EndGroup: // treat as explicit error
-                default: // treat as implicit error
-                    throw CreateWireTypeException();
-            }
-        }
-
-        /// <summary>
-        /// Indicates whether the reader still has data remaining in the current sub-item,
-        /// additionally setting the wire-type for the next field if there is more data.
-        /// This is used when decoding packed data.
-        /// </summary>
-        public static bool HasSubValue(ProtoBuf.WireType wireType, ProtoReader source)
-        {
-            if (source == null) throw new ArgumentNullException("source");
-            // check for virtual end of stream
-            if (source.blockEnd64 <= source.position64 || wireType == WireType.EndGroup) { return false; }
-            source.wireType = wireType;
-            return true;
-        }
-
-        internal int GetTypeKey(ref Type type)
-        {
-            return model.GetKey(ref type);
-        }
-
-        internal NetObjectCache NetCache => netCache;
-
-        internal Type DeserializeType(string value)
-        {
-            return TypeModel.DeserializeType(model, value);
-        }
-
-        internal void SetRootObject(object value)
-        {
-            netCache.SetKeyedObject(NetObjectCache.Root, value);
-            trapCount--;
-        }
-
-        /// <summary>
-        /// Utility method, not intended for public use; this helps maintain the root object is complex scenarios
-        /// </summary>
-        public static void NoteObject(object value, ProtoReader reader)
-        {
-            if (reader == null) throw new ArgumentNullException("reader");
-            if (reader.trapCount != 0)
-            {
-                reader.netCache.RegisterTrappedObject(value);
-                reader.trapCount--;
-            }
-        }
-
-        /// <summary>
-        /// Reads a Type from the stream, using the model's DynamicTypeFormatting if appropriate; supported wire-types: String
-        /// </summary>
-        public Type ReadType()
-        {
-            return TypeModel.DeserializeType(model, ReadString());
-        }
-
-        internal void TrapNextObject(int newObjectKey)
-        {
-            trapCount++;
-            netCache.SetKeyedObject(newObjectKey, null); // use null as a temp
-        }
-
-        internal void CheckFullyConsumed()
-        {
-            if (isFixedLength)
-            {
-                if (dataRemaining64 != 0) throw new ProtoException("Incorrect number of bytes consumed");
-            }
-            else
-            {
-                if (available != 0) throw new ProtoException("Unconsumed data left in the buffer; this suggests corrupt input");
-            }
-        }
-
-        /// <summary>
-        /// Merge two objects using the details from the current reader; this is used to change the type
-        /// of objects when an inheritance relationship is discovered later than usual during deserilazation.
-        /// </summary>
-        public static object Merge(ProtoReader parent, object from, object to)
-        {
-            if (parent == null) throw new ArgumentNullException("parent");
-            TypeModel model = parent.Model;
-            SerializationContext ctx = parent.Context;
-            if (model == null) throw new InvalidOperationException("Types cannot be merged unless a type-model has been specified");
-            using (var ms = new MemoryStream())
-            {
-                model.Serialize(ms, from, ctx);
-                ms.Position = 0;
-                return model.Deserialize(ms, to, null);
-            }
-        }
-
-        #region RECYCLER
-
-        internal static ProtoReader Create(Stream source, TypeModel model, SerializationContext context, int len)
-            => Create(source, model, context, (long)len);
-        /// <summary>
-        /// Creates a new reader against a stream
-        /// </summary>
-        /// <param name="source">The source stream</param>
-        /// <param name="model">The model to use for serialization; this can be null, but this will impair the ability to deserialize sub-objects</param>
-        /// <param name="context">Additional context about this serialization operation</param>
-        /// <param name="length">The number of bytes to read, or -1 to read until the end of the stream</param>
-        public static ProtoReader Create(Stream source, TypeModel model, SerializationContext context = null, long length = TO_EOF)
-        {
-            ProtoReader reader = GetRecycled();
-            if (reader == null)
-            {
-#pragma warning disable CS0618
-                return new ProtoReader(source, model, context, length);
-#pragma warning restore CS0618
-            }
-            Init(reader, source, model, context, length);
-            return reader;
-        }
-
-#if !PLAT_NO_THREADSTATIC
-        [ThreadStatic]
-        private static ProtoReader lastReader;
-
-        private static ProtoReader GetRecycled()
-        {
-            ProtoReader tmp = lastReader;
-            lastReader = null;
-            return tmp;
-        }
-        internal static void Recycle(ProtoReader reader)
-        {
-            if (reader != null)
-            {
-                reader.Dispose();
-                lastReader = reader;
-            }
-        }
-#elif !PLAT_NO_INTERLOCKED
-        private static object lastReader;
-        private static ProtoReader GetRecycled()
-        {
-            return (ProtoReader)System.Threading.Interlocked.Exchange(ref lastReader, null);
-        }
-        internal static void Recycle(ProtoReader reader)
-        {
-            if(reader != null)
-            {
-                reader.Dispose();
-                System.Threading.Interlocked.Exchange(ref lastReader, reader);
-            }
-        }
-#else
-        private static readonly object recycleLock = new object();
-        private static ProtoReader lastReader;
-        private static ProtoReader GetRecycled()
-        {
-            lock(recycleLock)
-            {
-                ProtoReader tmp = lastReader;
-                lastReader = null;
-                return tmp;
-            }            
-        }
-        internal static void Recycle(ProtoReader reader)
-        {
-            if(reader != null)
-            {
-                reader.Dispose();
-                lock(recycleLock)
-                {
-                    lastReader = reader;
-                }
-            }
-        }
-#endif
-
-        #endregion
-    }
-}

+ 0 - 1003
ThirdParty/protobuf-net/ProtoWriter.cs

@@ -1,1003 +0,0 @@
-using System;
-using System.IO;
-using System.Text;
-using ProtoBuf.Meta;
-
-namespace ProtoBuf
-{
-    /// <summary>
-    /// Represents an output stream for writing protobuf data.
-    /// 
-    /// Why is the API backwards (static methods with writer arguments)?
-    /// See: http://marcgravell.blogspot.com/2010/03/last-will-be-first-and-first-will-be.html
-    /// </summary>
-    public sealed class ProtoWriter : IDisposable
-    {
-        private Stream dest;
-        TypeModel model;
-        /// <summary>
-        /// Write an encapsulated sub-object, using the supplied unique key (reprasenting a type).
-        /// </summary>
-        /// <param name="value">The object to write.</param>
-        /// <param name="key">The key that uniquely identifies the type within the model.</param>
-        /// <param name="writer">The destination.</param>
-        public static void WriteObject(object value, int key, ProtoWriter writer)
-        {
-            if (writer == null) throw new ArgumentNullException("writer");
-            if (writer.model == null)
-            {
-                throw new InvalidOperationException("Cannot serialize sub-objects unless a model is provided");
-            }
-
-            SubItemToken token = StartSubItem(value, writer);
-            if (key >= 0)
-            {
-                writer.model.Serialize(key, value, writer);
-            }
-            else if (writer.model != null && writer.model.TrySerializeAuxiliaryType(writer, value.GetType(), DataFormat.Default, Serializer.ListItemTag, value, false, null))
-            {
-                // all ok
-            }
-            else
-            {
-                TypeModel.ThrowUnexpectedType(value.GetType());
-            }
-
-            EndSubItem(token, writer);
-        }
-        /// <summary>
-        /// Write an encapsulated sub-object, using the supplied unique key (reprasenting a type) - but the
-        /// caller is asserting that this relationship is non-recursive; no recursion check will be
-        /// performed.
-        /// </summary>
-        /// <param name="value">The object to write.</param>
-        /// <param name="key">The key that uniquely identifies the type within the model.</param>
-        /// <param name="writer">The destination.</param>
-        public static void WriteRecursionSafeObject(object value, int key, ProtoWriter writer)
-        {
-            if (writer == null) throw new ArgumentNullException(nameof(writer));
-            if (writer.model == null)
-            {
-                throw new InvalidOperationException("Cannot serialize sub-objects unless a model is provided");
-            }
-            SubItemToken token = StartSubItem(null, writer);
-            writer.model.Serialize(key, value, writer);
-            EndSubItem(token, writer);
-        }
-
-        internal static void WriteObject(object value, int key, ProtoWriter writer, PrefixStyle style, int fieldNumber)
-        {
-            if (writer.model == null)
-            {
-                throw new InvalidOperationException("Cannot serialize sub-objects unless a model is provided");
-            }
-            if (writer.wireType != WireType.None) throw ProtoWriter.CreateException(writer);
-
-            switch (style)
-            {
-                case PrefixStyle.Base128:
-                    writer.wireType = WireType.String;
-                    writer.fieldNumber = fieldNumber;
-                    if (fieldNumber > 0) WriteHeaderCore(fieldNumber, WireType.String, writer);
-                    break;
-                case PrefixStyle.Fixed32:
-                case PrefixStyle.Fixed32BigEndian:
-                    writer.fieldNumber = 0;
-                    writer.wireType = WireType.Fixed32;
-                    break;
-                default:
-                    throw new ArgumentOutOfRangeException("style");
-            }
-            SubItemToken token = StartSubItem(value, writer, true);
-            if (key < 0)
-            {
-                if (!writer.model.TrySerializeAuxiliaryType(writer, value.GetType(), DataFormat.Default, Serializer.ListItemTag, value, false, null))
-                {
-                    TypeModel.ThrowUnexpectedType(value.GetType());
-                }
-            }
-            else
-            {
-                writer.model.Serialize(key, value, writer);
-            }
-            EndSubItem(token, writer, style);
-        }
-
-        internal int GetTypeKey(ref Type type)
-        {
-            return model.GetKey(ref type);
-        }
-
-        private readonly NetObjectCache netCache = new NetObjectCache();
-        internal NetObjectCache NetCache => netCache;
-
-        private int fieldNumber, flushLock;
-        WireType wireType;
-        internal WireType WireType { get { return wireType; } }
-        /// <summary>
-        /// Writes a field-header, indicating the format of the next data we plan to write.
-        /// </summary>
-        public static void WriteFieldHeader(int fieldNumber, WireType wireType, ProtoWriter writer)
-        {
-            if (writer == null) throw new ArgumentNullException("writer");
-            if (writer.wireType != WireType.None) throw new InvalidOperationException("Cannot write a " + wireType.ToString()
-                + " header until the " + writer.wireType.ToString() + " data has been written");
-            if (fieldNumber < 0) throw new ArgumentOutOfRangeException("fieldNumber");
-#if DEBUG
-            switch (wireType)
-            {   // validate requested header-type
-                case WireType.Fixed32:
-                case WireType.Fixed64:
-                case WireType.String:
-                case WireType.StartGroup:
-                case WireType.SignedVariant:
-                case WireType.Variant:
-                    break; // fine
-                case WireType.None:
-                case WireType.EndGroup:
-                default:
-                    throw new ArgumentException("Invalid wire-type: " + wireType.ToString(), "wireType");
-            }
-#endif
-            if (writer.packedFieldNumber == 0)
-            {
-                writer.fieldNumber = fieldNumber;
-                writer.wireType = wireType;
-                WriteHeaderCore(fieldNumber, wireType, writer);
-            }
-            else if (writer.packedFieldNumber == fieldNumber)
-            { // we'll set things up, but note we *don't* actually write the header here
-                switch (wireType)
-                {
-                    case WireType.Fixed32:
-                    case WireType.Fixed64:
-                    case WireType.Variant:
-                    case WireType.SignedVariant:
-                        break; // fine
-                    default:
-                        throw new InvalidOperationException("Wire-type cannot be encoded as packed: " + wireType.ToString());
-                }
-                writer.fieldNumber = fieldNumber;
-                writer.wireType = wireType;
-            }
-            else
-            {
-                throw new InvalidOperationException("Field mismatch during packed encoding; expected " + writer.packedFieldNumber.ToString() + " but received " + fieldNumber.ToString());
-            }
-        }
-        internal static void WriteHeaderCore(int fieldNumber, WireType wireType, ProtoWriter writer)
-        {
-            uint header = (((uint)fieldNumber) << 3)
-                | (((uint)wireType) & 7);
-            WriteUInt32Variant(header, writer);
-        }
-
-        /// <summary>
-        /// Writes a byte-array to the stream; supported wire-types: String
-        /// </summary>
-        public static void WriteBytes(byte[] data, ProtoWriter writer)
-        {
-            if (data == null) throw new ArgumentNullException(nameof(data));
-            ProtoWriter.WriteBytes(data, 0, data.Length, writer);
-        }
-        /// <summary>
-        /// Writes a byte-array to the stream; supported wire-types: String
-        /// </summary>
-        public static void WriteBytes(byte[] data, int offset, int length, ProtoWriter writer)
-        {
-            if (data == null) throw new ArgumentNullException(nameof(data));
-            if (writer == null) throw new ArgumentNullException(nameof(writer));
-            switch (writer.wireType)
-            {
-                case WireType.Fixed32:
-                    if (length != 4) throw new ArgumentException(nameof(length));
-                    goto CopyFixedLength;  // ugly but effective
-                case WireType.Fixed64:
-                    if (length != 8) throw new ArgumentException(nameof(length));
-                    goto CopyFixedLength;  // ugly but effective
-                case WireType.String:
-                    WriteUInt32Variant((uint)length, writer);
-                    writer.wireType = WireType.None;
-                    if (length == 0) return;
-                    if (writer.flushLock != 0 || length <= writer.ioBuffer.Length) // write to the buffer
-                    {
-                        goto CopyFixedLength; // ugly but effective
-                    }
-                    // writing data that is bigger than the buffer (and the buffer
-                    // isn't currently locked due to a sub-object needing the size backfilled)
-                    Flush(writer); // commit any existing data from the buffer
-                    // now just write directly to the underlying stream
-                    writer.dest.Write(data, offset, length);
-                    writer.position64 += length; // since we've flushed offset etc is 0, and remains
-                                                 // zero since we're writing directly to the stream
-                    return;
-            }
-            throw CreateException(writer);
-            CopyFixedLength: // no point duplicating this lots of times, and don't really want another stackframe
-            DemandSpace(length, writer);
-            Buffer.BlockCopy(data, offset, writer.ioBuffer, writer.ioIndex, length);
-            IncrementedAndReset(length, writer);
-        }
-        private static void CopyRawFromStream(Stream source, ProtoWriter writer)
-        {
-            byte[] buffer = writer.ioBuffer;
-            int space = buffer.Length - writer.ioIndex, bytesRead = 1; // 1 here to spoof case where already full
-
-            // try filling the buffer first   
-            while (space > 0 && (bytesRead = source.Read(buffer, writer.ioIndex, space)) > 0)
-            {
-                writer.ioIndex += bytesRead;
-                writer.position64 += bytesRead;
-                space -= bytesRead;
-            }
-            if (bytesRead <= 0) return; // all done using just the buffer; stream exhausted
-
-            // at this point the stream still has data, but buffer is full; 
-            if (writer.flushLock == 0)
-            {
-                // flush the buffer and write to the underlying stream instead
-                Flush(writer);
-                while ((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0)
-                {
-                    writer.dest.Write(buffer, 0, bytesRead);
-                    writer.position64 += bytesRead;
-                }
-            }
-            else
-            {
-                do
-                {
-                    // need more space; resize (double) as necessary,
-                    // requesting a reasonable minimum chunk each time
-                    // (128 is the minimum; there may actually be much
-                    // more space than this in the buffer)
-                    DemandSpace(128, writer);
-                    if ((bytesRead = source.Read(writer.ioBuffer, writer.ioIndex,
-                        writer.ioBuffer.Length - writer.ioIndex)) <= 0) break;
-                    writer.position64 += bytesRead;
-                    writer.ioIndex += bytesRead;
-                } while (true);
-            }
-
-        }
-        private static void IncrementedAndReset(int length, ProtoWriter writer)
-        {
-            Helpers.DebugAssert(length >= 0);
-            writer.ioIndex += length;
-            writer.position64 += length;
-            writer.wireType = WireType.None;
-        }
-        int depth = 0;
-        const int RecursionCheckDepth = 25;
-        /// <summary>
-        /// Indicates the start of a nested record.
-        /// </summary>
-        /// <param name="instance">The instance to write.</param>
-        /// <param name="writer">The destination.</param>
-        /// <returns>A token representing the state of the stream; this token is given to EndSubItem.</returns>
-        public static SubItemToken StartSubItem(object instance, ProtoWriter writer)
-        {
-            return StartSubItem(instance, writer, false);
-        }
-
-        MutableList recursionStack;
-        private void CheckRecursionStackAndPush(object instance)
-        {
-            int hitLevel;
-            if (recursionStack == null) { recursionStack = new MutableList(); }
-            else if (instance != null && (hitLevel = recursionStack.IndexOfReference(instance)) >= 0)
-            {
-#if DEBUG
-                Helpers.DebugWriteLine("Stack:");
-                foreach (object obj in recursionStack)
-                {
-                    Helpers.DebugWriteLine(obj == null ? "<null>" : obj.ToString());
-                }
-                Helpers.DebugWriteLine(instance == null ? "<null>" : instance.ToString());
-#endif
-                throw new ProtoException("Possible recursion detected (offset: " + (recursionStack.Count - hitLevel).ToString() + " level(s)): " + instance.ToString());
-            }
-            recursionStack.Add(instance);
-        }
-        private void PopRecursionStack() { recursionStack.RemoveLast(); }
-
-        private static SubItemToken StartSubItem(object instance, ProtoWriter writer, bool allowFixed)
-        {
-            if (writer == null) throw new ArgumentNullException("writer");
-            if (++writer.depth > RecursionCheckDepth)
-            {
-                writer.CheckRecursionStackAndPush(instance);
-            }
-            if (writer.packedFieldNumber != 0) throw new InvalidOperationException("Cannot begin a sub-item while performing packed encoding");
-            switch (writer.wireType)
-            {
-                case WireType.StartGroup:
-                    writer.wireType = WireType.None;
-                    return new SubItemToken((long)(-writer.fieldNumber));
-                case WireType.String:
-#if DEBUG
-                    if (writer.model != null && writer.model.ForwardsOnly)
-                    {
-                        throw new ProtoException("Should not be buffering data: " + instance ?? "(null)");
-                    }
-#endif
-                    writer.wireType = WireType.None;
-                    DemandSpace(32, writer); // make some space in anticipation...
-                    writer.flushLock++;
-                    writer.position64++;
-                    return new SubItemToken((long)(writer.ioIndex++)); // leave 1 space (optimistic) for length
-                case WireType.Fixed32:
-                    {
-                        if (!allowFixed) throw CreateException(writer);
-                        DemandSpace(32, writer); // make some space in anticipation...
-                        writer.flushLock++;
-                        SubItemToken token = new SubItemToken((long)writer.ioIndex);
-                        ProtoWriter.IncrementedAndReset(4, writer); // leave 4 space (rigid) for length
-                        return token;
-                    }
-                default:
-                    throw CreateException(writer);
-            }
-        }
-
-        /// <summary>
-        /// Indicates the end of a nested record.
-        /// </summary>
-        /// <param name="token">The token obtained from StartubItem.</param>
-        /// <param name="writer">The destination.</param>
-        public static void EndSubItem(SubItemToken token, ProtoWriter writer)
-        {
-            EndSubItem(token, writer, PrefixStyle.Base128);
-        }
-        private static void EndSubItem(SubItemToken token, ProtoWriter writer, PrefixStyle style)
-        {
-            if (writer == null) throw new ArgumentNullException("writer");
-            if (writer.wireType != WireType.None) { throw CreateException(writer); }
-            int value = (int)token.value64;
-            if (writer.depth <= 0) throw CreateException(writer);
-            if (writer.depth-- > RecursionCheckDepth)
-            {
-                writer.PopRecursionStack();
-            }
-            writer.packedFieldNumber = 0; // ending the sub-item always wipes packed encoding
-            if (value < 0)
-            {   // group - very simple append
-                WriteHeaderCore(-value, WireType.EndGroup, writer);
-                writer.wireType = WireType.None;
-                return;
-            }
-
-            // so we're backfilling the length into an existing sequence
-            int len;
-            switch (style)
-            {
-                case PrefixStyle.Fixed32:
-                    len = (int)((writer.ioIndex - value) - 4);
-                    ProtoWriter.WriteInt32ToBuffer(len, writer.ioBuffer, value);
-                    break;
-                case PrefixStyle.Fixed32BigEndian:
-                    len = (int)((writer.ioIndex - value) - 4);
-                    byte[] buffer = writer.ioBuffer;
-                    ProtoWriter.WriteInt32ToBuffer(len, buffer, value);
-                    // and swap the byte order
-                    byte b = buffer[value];
-                    buffer[value] = buffer[value + 3];
-                    buffer[value + 3] = b;
-                    b = buffer[value + 1];
-                    buffer[value + 1] = buffer[value + 2];
-                    buffer[value + 2] = b;
-                    break;
-                case PrefixStyle.Base128:
-                    // string - complicated because we only reserved one byte;
-                    // if the prefix turns out to need more than this then
-                    // we need to shuffle the existing data
-                    len = (int)((writer.ioIndex - value) - 1);
-                    int offset = 0;
-                    uint tmp = (uint)len;
-                    while ((tmp >>= 7) != 0) offset++;
-                    if (offset == 0)
-                    {
-                        writer.ioBuffer[value] = (byte)(len & 0x7F);
-                    }
-                    else
-                    {
-                        DemandSpace(offset, writer);
-                        byte[] blob = writer.ioBuffer;
-                        Buffer.BlockCopy(blob, value + 1, blob, value + 1 + offset, len);
-                        tmp = (uint)len;
-                        do
-                        {
-                            blob[value++] = (byte)((tmp & 0x7F) | 0x80);
-                        } while ((tmp >>= 7) != 0);
-                        blob[value - 1] = (byte)(blob[value - 1] & ~0x80);
-                        writer.position64 += offset;
-                        writer.ioIndex += offset;
-                    }
-                    break;
-                default:
-                    throw new ArgumentOutOfRangeException("style");
-            }
-            // and this object is no longer a blockage - also flush if sensible
-            const int ADVISORY_FLUSH_SIZE = 1024;
-            if (--writer.flushLock == 0 && writer.ioIndex >= ADVISORY_FLUSH_SIZE)
-            {
-                ProtoWriter.Flush(writer);
-            }
-
-        }
-
-        /// <summary>
-        /// Creates a new writer against a stream
-        /// </summary>
-        /// <param name="dest">The destination stream</param>
-        /// <param name="model">The model to use for serialization; this can be null, but this will impair the ability to serialize sub-objects</param>
-        /// <param name="context">Additional context about this serialization operation</param>
-        public static ProtoWriter Create(Stream dest, TypeModel model, SerializationContext context = null)
-#pragma warning disable CS0618
-            => new ProtoWriter(dest, model, context);
-#pragma warning restore CS0618
-
-        /// <summary>
-        /// Creates a new writer against a stream
-        /// </summary>
-        /// <param name="dest">The destination stream</param>
-        /// <param name="model">The model to use for serialization; this can be null, but this will impair the ability to serialize sub-objects</param>
-        /// <param name="context">Additional context about this serialization operation</param>
-        [Obsolete("Please use ProtoWriter.Create; this API may be removed in a future version", error: false)]
-        public ProtoWriter(Stream dest, TypeModel model, SerializationContext context)
-        {
-            if (dest == null) throw new ArgumentNullException("dest");
-            if (!dest.CanWrite) throw new ArgumentException("Cannot write to stream", "dest");
-            //if (model == null) throw new ArgumentNullException("model");
-            this.dest = dest;
-            this.ioBuffer = BufferPool.GetBuffer();
-            this.model = model;
-            this.wireType = WireType.None;
-            if (context == null) { context = SerializationContext.Default; }
-            else { context.Freeze(); }
-            this.context = context;
-
-        }
-
-        private readonly SerializationContext context;
-        /// <summary>
-        /// Addition information about this serialization operation.
-        /// </summary>
-        public SerializationContext Context => context;
-
-        void IDisposable.Dispose()
-        {
-            Dispose();
-        }
-
-        private void Dispose()
-        {   // importantly, this does **not** own the stream, and does not dispose it
-            if (dest != null)
-            {
-                Flush(this);
-                dest = null;
-            }
-            model = null;
-            BufferPool.ReleaseBufferToPool(ref ioBuffer);
-        }
-
-        private byte[] ioBuffer;
-        private int ioIndex;
-        // note that this is used by some of the unit tests and should not be removed
-        internal static long GetLongPosition(ProtoWriter writer) { return writer.position64; }
-        internal static int GetPosition(ProtoWriter writer) { return checked((int)writer.position64); }
-        private long position64;
-        private static void DemandSpace(int required, ProtoWriter writer)
-        {
-            // check for enough space
-            if ((writer.ioBuffer.Length - writer.ioIndex) < required)
-            {
-                TryFlushOrResize(required, writer);
-            }
-        }
-
-        private static void TryFlushOrResize(int required, ProtoWriter writer)
-        {
-            if (writer.flushLock == 0)
-            {
-                Flush(writer); // try emptying the buffer
-                if ((writer.ioBuffer.Length - writer.ioIndex) >= required) return;
-            }
-
-            // either can't empty the buffer, or that didn't help; need more space
-            BufferPool.ResizeAndFlushLeft(ref writer.ioBuffer, required + writer.ioIndex, 0, writer.ioIndex);
-        }
-
-        /// <summary>
-        /// Flushes data to the underlying stream, and releases any resources. The underlying stream is *not* disposed
-        /// by this operation.
-        /// </summary>
-        public void Close()
-        {
-            if (depth != 0 || flushLock != 0) throw new InvalidOperationException("Unable to close stream in an incomplete state");
-            Dispose();
-        }
-
-        internal void CheckDepthFlushlock()
-        {
-            if (depth != 0 || flushLock != 0) throw new InvalidOperationException("The writer is in an incomplete state");
-        }
-
-        /// <summary>
-        /// Get the TypeModel associated with this writer
-        /// </summary>
-        public TypeModel Model => model;
-
-        /// <summary>
-        /// Writes any buffered data (if possible) to the underlying stream.
-        /// </summary>
-        /// <param name="writer">The writer to flush</param>
-        /// <remarks>It is not always possible to fully flush, since some sequences
-        /// may require values to be back-filled into the byte-stream.</remarks>
-        internal static void Flush(ProtoWriter writer)
-        {
-            if (writer.flushLock == 0 && writer.ioIndex != 0)
-            {
-                writer.dest.Write(writer.ioBuffer, 0, writer.ioIndex);
-                writer.ioIndex = 0;
-            }
-        }
-
-        /// <summary>
-        /// Writes an unsigned 32-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64
-        /// </summary>
-        private static void WriteUInt32Variant(uint value, ProtoWriter writer)
-        {
-            DemandSpace(5, writer);
-            int count = 0;
-            do
-            {
-                writer.ioBuffer[writer.ioIndex++] = (byte)((value & 0x7F) | 0x80);
-                count++;
-            } while ((value >>= 7) != 0);
-            writer.ioBuffer[writer.ioIndex - 1] &= 0x7F;
-            writer.position64 += count;
-        }
-
-#if COREFX
-        static readonly Encoding encoding = Encoding.UTF8;
-#else
-        static readonly UTF8Encoding encoding = new UTF8Encoding();
-#endif
-
-        internal static uint Zig(int value)
-        {
-            return (uint)((value << 1) ^ (value >> 31));
-        }
-
-        internal static ulong Zig(long value)
-        {
-            return (ulong)((value << 1) ^ (value >> 63));
-        }
-
-        private static void WriteUInt64Variant(ulong value, ProtoWriter writer)
-        {
-            DemandSpace(10, writer);
-            int count = 0;
-            do
-            {
-                writer.ioBuffer[writer.ioIndex++] = (byte)((value & 0x7F) | 0x80);
-                count++;
-            } while ((value >>= 7) != 0);
-            writer.ioBuffer[writer.ioIndex - 1] &= 0x7F;
-            writer.position64 += count;
-        }
-
-        /// <summary>
-        /// Writes a string to the stream; supported wire-types: String
-        /// </summary>
-        public static void WriteString(string value, ProtoWriter writer)
-        {
-            if (writer == null) throw new ArgumentNullException("writer");
-            if (writer.wireType != WireType.String) throw CreateException(writer);
-            if (value == null) throw new ArgumentNullException("value"); // written header; now what?
-            int len = value.Length;
-            if (len == 0)
-            {
-                WriteUInt32Variant(0, writer);
-                writer.wireType = WireType.None;
-                return; // just a header
-            }
-            int predicted = encoding.GetByteCount(value);
-            WriteUInt32Variant((uint)predicted, writer);
-            DemandSpace(predicted, writer);
-            int actual = encoding.GetBytes(value, 0, value.Length, writer.ioBuffer, writer.ioIndex);
-            Helpers.DebugAssert(predicted == actual);
-            IncrementedAndReset(actual, writer);
-        }
-
-        /// <summary>
-        /// Writes an unsigned 64-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64
-        /// </summary>
-        public static void WriteUInt64(ulong value, ProtoWriter writer)
-        {
-            if (writer == null) throw new ArgumentNullException(nameof(writer));
-            switch (writer.wireType)
-            {
-                case WireType.Fixed64:
-                    ProtoWriter.WriteInt64((long)value, writer);
-                    return;
-                case WireType.Variant:
-                    WriteUInt64Variant(value, writer);
-                    writer.wireType = WireType.None;
-                    return;
-                case WireType.Fixed32:
-                    checked { ProtoWriter.WriteUInt32((uint)value, writer); }
-                    return;
-                default:
-                    throw CreateException(writer);
-            }
-        }
-
-        /// <summary>
-        /// Writes a signed 64-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64, SignedVariant
-        /// </summary>
-        public static void WriteInt64(long value, ProtoWriter writer)
-        {
-            byte[] buffer;
-            int index;
-            if (writer == null) throw new ArgumentNullException(nameof(writer));
-            switch (writer.wireType)
-            {
-                case WireType.Fixed64:
-                    DemandSpace(8, writer);
-                    buffer = writer.ioBuffer;
-                    index = writer.ioIndex;
-
-#if NETCOREAPP2_1
-                    System.Buffers.Binary.BinaryPrimitives.WriteInt64LittleEndian(buffer.AsSpan(index, 8), value);
-#else
-                    buffer[index] = (byte)value;
-                    buffer[index + 1] = (byte)(value >> 8);
-                    buffer[index + 2] = (byte)(value >> 16);
-                    buffer[index + 3] = (byte)(value >> 24);
-                    buffer[index + 4] = (byte)(value >> 32);
-                    buffer[index + 5] = (byte)(value >> 40);
-                    buffer[index + 6] = (byte)(value >> 48);
-                    buffer[index + 7] = (byte)(value >> 56);
-#endif
-                    IncrementedAndReset(8, writer);
-                    return;
-                case WireType.SignedVariant:
-                    WriteUInt64Variant(Zig(value), writer);
-                    writer.wireType = WireType.None;
-                    return;
-                case WireType.Variant:
-                    if (value >= 0)
-                    {
-                        WriteUInt64Variant((ulong)value, writer);
-                        writer.wireType = WireType.None;
-                    }
-                    else
-                    {
-                        DemandSpace(10, writer);
-                        buffer = writer.ioBuffer;
-                        index = writer.ioIndex;
-                        buffer[index] = (byte)(value | 0x80);
-                        buffer[index + 1] = (byte)((int)(value >> 7) | 0x80);
-                        buffer[index + 2] = (byte)((int)(value >> 14) | 0x80);
-                        buffer[index + 3] = (byte)((int)(value >> 21) | 0x80);
-                        buffer[index + 4] = (byte)((int)(value >> 28) | 0x80);
-                        buffer[index + 5] = (byte)((int)(value >> 35) | 0x80);
-                        buffer[index + 6] = (byte)((int)(value >> 42) | 0x80);
-                        buffer[index + 7] = (byte)((int)(value >> 49) | 0x80);
-                        buffer[index + 8] = (byte)((int)(value >> 56) | 0x80);
-                        buffer[index + 9] = 0x01; // sign bit
-                        IncrementedAndReset(10, writer);
-                    }
-                    return;
-                case WireType.Fixed32:
-                    checked { WriteInt32((int)value, writer); }
-                    return;
-                default:
-                    throw CreateException(writer);
-            }
-        }
-
-        /// <summary>
-        /// Writes an unsigned 16-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64
-        /// </summary>
-        public static void WriteUInt32(uint value, ProtoWriter writer)
-        {
-            if (writer == null) throw new ArgumentNullException("writer");
-            switch (writer.wireType)
-            {
-                case WireType.Fixed32:
-                    ProtoWriter.WriteInt32((int)value, writer);
-                    return;
-                case WireType.Fixed64:
-                    ProtoWriter.WriteInt64((int)value, writer);
-                    return;
-                case WireType.Variant:
-                    WriteUInt32Variant(value, writer);
-                    writer.wireType = WireType.None;
-                    return;
-                default:
-                    throw CreateException(writer);
-            }
-        }
-
-        /// <summary>
-        /// Writes a signed 16-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64, SignedVariant
-        /// </summary>
-        public static void WriteInt16(short value, ProtoWriter writer)
-        {
-            ProtoWriter.WriteInt32(value, writer);
-        }
-
-        /// <summary>
-        /// Writes an unsigned 16-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64
-        /// </summary>
-        public static void WriteUInt16(ushort value, ProtoWriter writer)
-        {
-            ProtoWriter.WriteUInt32(value, writer);
-        }
-
-        /// <summary>
-        /// Writes an unsigned 8-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64
-        /// </summary>
-        public static void WriteByte(byte value, ProtoWriter writer)
-        {
-            ProtoWriter.WriteUInt32(value, writer);
-        }
-        /// <summary>
-        /// Writes a signed 8-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64, SignedVariant
-        /// </summary>
-        public static void WriteSByte(sbyte value, ProtoWriter writer)
-        {
-            ProtoWriter.WriteInt32(value, writer);
-        }
-
-        private static void WriteInt32ToBuffer(int value, byte[] buffer, int index)
-        {
-#if NETCOREAPP2_1
-            System.Buffers.Binary.BinaryPrimitives.WriteInt32LittleEndian(buffer.AsSpan(index, 4), value);
-#else
-            buffer[index] = (byte)value;
-            buffer[index + 1] = (byte)(value >> 8);
-            buffer[index + 2] = (byte)(value >> 16);
-            buffer[index + 3] = (byte)(value >> 24);
-#endif
-        }
-
-        /// <summary>
-        /// Writes a signed 32-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64, SignedVariant
-        /// </summary>
-        public static void WriteInt32(int value, ProtoWriter writer)
-        {
-            byte[] buffer;
-            int index;
-            if (writer == null) throw new ArgumentNullException(nameof(writer));
-            switch (writer.wireType)
-            {
-                case WireType.Fixed32:
-                    DemandSpace(4, writer);
-                    WriteInt32ToBuffer(value, writer.ioBuffer, writer.ioIndex);
-                    IncrementedAndReset(4, writer);
-                    return;
-                case WireType.Fixed64:
-                    DemandSpace(8, writer);
-                    buffer = writer.ioBuffer;
-                    index = writer.ioIndex;
-                    buffer[index] = (byte)value;
-                    buffer[index + 1] = (byte)(value >> 8);
-                    buffer[index + 2] = (byte)(value >> 16);
-                    buffer[index + 3] = (byte)(value >> 24);
-                    buffer[index + 4] = buffer[index + 5] =
-                        buffer[index + 6] = buffer[index + 7] = 0;
-                    IncrementedAndReset(8, writer);
-                    return;
-                case WireType.SignedVariant:
-                    WriteUInt32Variant(Zig(value), writer);
-                    writer.wireType = WireType.None;
-                    return;
-                case WireType.Variant:
-                    if (value >= 0)
-                    {
-                        WriteUInt32Variant((uint)value, writer);
-                        writer.wireType = WireType.None;
-                    }
-                    else
-                    {
-                        DemandSpace(10, writer);
-                        buffer = writer.ioBuffer;
-                        index = writer.ioIndex;
-                        buffer[index] = (byte)(value | 0x80);
-                        buffer[index + 1] = (byte)((value >> 7) | 0x80);
-                        buffer[index + 2] = (byte)((value >> 14) | 0x80);
-                        buffer[index + 3] = (byte)((value >> 21) | 0x80);
-                        buffer[index + 4] = (byte)((value >> 28) | 0x80);
-                        buffer[index + 5] = buffer[index + 6] =
-                            buffer[index + 7] = buffer[index + 8] = (byte)0xFF;
-                        buffer[index + 9] = (byte)0x01;
-                        IncrementedAndReset(10, writer);
-                    }
-                    return;
-                default:
-                    throw CreateException(writer);
-            }
-        }
-
-        /// <summary>
-        /// Writes a double-precision number to the stream; supported wire-types: Fixed32, Fixed64
-        /// </summary>
-        public
-#if !FEAT_SAFE
-            unsafe
-#endif
-
-                static void WriteDouble(double value, ProtoWriter writer)
-        {
-            if (writer == null) throw new ArgumentNullException("writer");
-            switch (writer.wireType)
-            {
-                case WireType.Fixed32:
-                    float f = (float)value;
-                    if (float.IsInfinity(f) && !double.IsInfinity(value))
-                    {
-                        throw new OverflowException();
-                    }
-                    ProtoWriter.WriteSingle(f, writer);
-                    return;
-                case WireType.Fixed64:
-#if FEAT_SAFE
-                    ProtoWriter.WriteInt64(BitConverter.ToInt64(BitConverter.GetBytes(value), 0), writer);
-#else
-                    ProtoWriter.WriteInt64(*(long*)&value, writer);
-#endif
-                    return;
-                default:
-                    throw CreateException(writer);
-            }
-        }
-        /// <summary>
-        /// Writes a single-precision number to the stream; supported wire-types: Fixed32, Fixed64
-        /// </summary>
-        public
-#if !FEAT_SAFE
-            unsafe
-#endif
-            static void WriteSingle(float value, ProtoWriter writer)
-        {
-            if (writer == null) throw new ArgumentNullException("writer");
-            switch (writer.wireType)
-            {
-                case WireType.Fixed32:
-#if FEAT_SAFE
-                    ProtoWriter.WriteInt32(BitConverter.ToInt32(BitConverter.GetBytes(value), 0), writer);
-#else
-                    ProtoWriter.WriteInt32(*(int*)&value, writer);
-#endif
-                    return;
-                case WireType.Fixed64:
-                    ProtoWriter.WriteDouble((double)value, writer);
-                    return;
-                default:
-                    throw CreateException(writer);
-            }
-        }
-
-        /// <summary>
-        /// Throws an exception indicating that the given enum cannot be mapped to a serialized value.
-        /// </summary>
-        public static void ThrowEnumException(ProtoWriter writer, object enumValue)
-        {
-            if (writer == null) throw new ArgumentNullException("writer");
-            string rhs = enumValue == null ? "<null>" : (enumValue.GetType().FullName + "." + enumValue.ToString());
-            throw new ProtoException("No wire-value is mapped to the enum " + rhs + " at position " + writer.position64.ToString());
-        }
-
-        // general purpose serialization exception message
-        internal static Exception CreateException(ProtoWriter writer)
-        {
-            if (writer == null) throw new ArgumentNullException("writer");
-            return new ProtoException("Invalid serialization operation with wire-type " + writer.wireType.ToString() + " at position " + writer.position64.ToString());
-        }
-
-        /// <summary>
-        /// Writes a boolean to the stream; supported wire-types: Variant, Fixed32, Fixed64
-        /// </summary>
-        public static void WriteBoolean(bool value, ProtoWriter writer)
-        {
-            ProtoWriter.WriteUInt32(value ? (uint)1 : (uint)0, writer);
-        }
-
-        /// <summary>
-        /// Copies any extension data stored for the instance to the underlying stream
-        /// </summary>
-        public static void AppendExtensionData(IExtensible instance, ProtoWriter writer)
-        {
-            if (instance == null) throw new ArgumentNullException(nameof(instance));
-            if (writer == null) throw new ArgumentNullException(nameof(writer));
-            // we expect the writer to be raw here; the extension data will have the
-            // header detail, so we'll copy it implicitly
-            if (writer.wireType != WireType.None) throw CreateException(writer);
-
-            IExtension extn = instance.GetExtensionObject(false);
-            if (extn != null)
-            {
-                // unusually we *don't* want "using" here; the "finally" does that, with
-                // the extension object being responsible for disposal etc
-                Stream source = extn.BeginQuery();
-                try
-                {
-                    CopyRawFromStream(source, writer);
-                }
-                finally { extn.EndQuery(source); }
-            }
-        }
-
-        private int packedFieldNumber;
-        /// <summary>
-        /// Used for packed encoding; indicates that the next field should be skipped rather than
-        /// a field header written. Note that the field number must match, else an exception is thrown
-        /// when the attempt is made to write the (incorrect) field. The wire-type is taken from the
-        /// subsequent call to WriteFieldHeader. Only primitive types can be packed.
-        /// </summary>
-        public static void SetPackedField(int fieldNumber, ProtoWriter writer)
-        {
-            if (fieldNumber <= 0) throw new ArgumentOutOfRangeException(nameof(fieldNumber));
-            if (writer == null) throw new ArgumentNullException(nameof(writer));
-            writer.packedFieldNumber = fieldNumber;
-        }
-
-        /// <summary>
-        /// Used for packed encoding; explicitly reset the packed field marker; this is not required
-        /// if using StartSubItem/EndSubItem
-        /// </summary>
-        public static void ClearPackedField(int fieldNumber, ProtoWriter writer)
-        {
-            if (fieldNumber != writer.packedFieldNumber)
-                throw new InvalidOperationException("Field mismatch during packed encoding; expected " + writer.packedFieldNumber.ToString() + " but received " + fieldNumber.ToString());
-            writer.packedFieldNumber = 0;
-        }
-
-        /// <summary>
-        /// Used for packed encoding; writes the length prefix using fixed sizes rather than using
-        /// buffering. Only valid for fixed-32 and fixed-64 encoding.
-        /// </summary>
-        public static void WritePackedPrefix(int elementCount, WireType wireType, ProtoWriter writer)
-        {
-            if (writer.WireType != WireType.String) throw new InvalidOperationException("Invalid wire-type: " + writer.WireType);
-            if (elementCount < 0) throw new ArgumentOutOfRangeException(nameof(elementCount));
-            ulong bytes;
-            switch (wireType)
-            {
-                // use long in case very large arrays are enabled
-                case WireType.Fixed32: bytes = ((ulong)elementCount) << 2; break; // x4
-                case WireType.Fixed64: bytes = ((ulong)elementCount) << 3; break; // x8
-                default:
-                    throw new ArgumentOutOfRangeException(nameof(wireType), "Invalid wire-type: " + wireType);
-            }
-            WriteUInt64Variant(bytes, writer);
-            writer.wireType = WireType.None;
-        }
-
-        internal string SerializeType(Type type)
-        {
-            return TypeModel.SerializeType(model, type);
-        }
-
-        /// <summary>
-        /// Specifies a known root object to use during reference-tracked serialization
-        /// </summary>
-        public void SetRootObject(object value)
-        {
-            NetCache.SetKeyedObject(NetObjectCache.Root, value);
-        }
-
-        /// <summary>
-        /// Writes a Type to the stream, using the model's DynamicTypeFormatting if appropriate; supported wire-types: String
-        /// </summary>
-        public static void WriteType(Type value, ProtoWriter writer)
-        {
-            if (writer == null) throw new ArgumentNullException(nameof(writer));
-            WriteString(writer.SerializeType(value), writer);
-        }
-    }
-}

+ 0 - 76
ThirdParty/protobuf-net/SerializationContext.cs

@@ -1,76 +0,0 @@
-using System;
-
-namespace ProtoBuf
-{
-    /// <summary>
-    /// Additional information about a serialization operation
-    /// </summary>
-    public sealed class SerializationContext
-    {
-        private bool frozen;
-        internal void Freeze() { frozen = true; }
-        private void ThrowIfFrozen() { if (frozen) throw new InvalidOperationException("The serialization-context cannot be changed once it is in use"); }
-        private object context;
-        /// <summary>
-        /// Gets or sets a user-defined object containing additional information about this serialization/deserialization operation.
-        /// </summary>
-        public object Context
-        {
-            get { return context; }
-            set { if (context != value) { ThrowIfFrozen(); context = value; } }
-        }
-
-        private static readonly SerializationContext @default;
-
-        static SerializationContext()
-        {
-            @default = new SerializationContext();
-            @default.Freeze();
-        }
-        /// <summary>
-        /// A default SerializationContext, with minimal information.
-        /// </summary>
-        internal static SerializationContext Default => @default;
-#if PLAT_BINARYFORMATTER
-
-#if !(COREFX || PROFILE259)
-        private System.Runtime.Serialization.StreamingContextStates state = System.Runtime.Serialization.StreamingContextStates.Persistence;
-        /// <summary>
-        /// Gets or sets the source or destination of the transmitted data.
-        /// </summary>
-        public System.Runtime.Serialization.StreamingContextStates State
-        {
-            get { return state; }
-            set { if (state != value) { ThrowIfFrozen(); state = value; } }
-        }
-#endif
-		/// <summary>
-		/// Convert a SerializationContext to a StreamingContext
-		/// </summary>
-		public static implicit operator System.Runtime.Serialization.StreamingContext(SerializationContext ctx)
-        {
-#if COREFX
-			return new System.Runtime.Serialization.StreamingContext();
-#else
-            if (ctx == null) return new System.Runtime.Serialization.StreamingContext(System.Runtime.Serialization.StreamingContextStates.Persistence);
-            return new System.Runtime.Serialization.StreamingContext(ctx.state, ctx.context);
-#endif
-        }
-        /// <summary>
-        /// Convert a StreamingContext to a SerializationContext
-        /// </summary>
-        public static implicit operator SerializationContext (System.Runtime.Serialization.StreamingContext ctx)
-        {
-            SerializationContext result = new SerializationContext();
-
-#if !(COREFX || PROFILE259)
-            result.Context = ctx.Context;
-            result.State = ctx.State;
-#endif
-
-			return result;
-        }
-#endif
-    }
-
-}

+ 0 - 514
ThirdParty/protobuf-net/Serializer.cs

@@ -1,514 +0,0 @@
-using ProtoBuf.Meta;
-using System;
-using System.IO;
-using System.Collections.Generic;
-using System.Reflection;
-
-namespace ProtoBuf
-{
-    /// <summary>
-    /// Provides protocol-buffer serialization capability for concrete, attributed types. This
-    /// is a *default* model, but custom serializer models are also supported.
-    /// </summary>
-    /// <remarks>
-    /// Protocol-buffer serialization is a compact binary format, designed to take
-    /// advantage of sparse data and knowledge of specific data types; it is also
-    /// extensible, allowing a type to be deserialized / merged even if some data is
-    /// not recognised.
-    /// </remarks>
-    public static class Serializer
-    {
-#if !NO_RUNTIME
-        /// <summary>
-        /// Suggest a .proto definition for the given type
-        /// </summary>
-        /// <typeparam name="T">The type to generate a .proto definition for</typeparam>
-        /// <returns>The .proto definition as a string</returns>
-        public static string GetProto<T>() => GetProto<T>(ProtoSyntax.Proto2);
-
-        /// <summary>
-        /// Suggest a .proto definition for the given type
-        /// </summary>
-        /// <typeparam name="T">The type to generate a .proto definition for</typeparam>
-        /// <returns>The .proto definition as a string</returns>
-        public static string GetProto<T>(ProtoSyntax syntax)
-        {
-            return RuntimeTypeModel.Default.GetSchema(RuntimeTypeModel.Default.MapType(typeof(T)), syntax);
-        }
-        /// <summary>
-        /// Create a deep clone of the supplied instance; any sub-items are also cloned.
-        /// </summary>
-        public static T DeepClone<T>(T instance)
-        {
-            return instance == null ? instance : (T)RuntimeTypeModel.Default.DeepClone(instance);
-        }
-
-        /// <summary>
-        /// Applies a protocol-buffer stream to an existing instance.
-        /// </summary>
-        /// <typeparam name="T">The type being merged.</typeparam>
-        /// <param name="instance">The existing instance to be modified (can be null).</param>
-        /// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
-        /// <returns>The updated instance; this may be different to the instance argument if
-        /// either the original instance was null, or the stream defines a known sub-type of the
-        /// original instance.</returns>
-        public static T Merge<T>(Stream source, T instance)
-        {
-            return (T)RuntimeTypeModel.Default.Deserialize(source, instance, typeof(T));
-        }
-
-        /// <summary>
-        /// Creates a new instance from a protocol-buffer stream
-        /// </summary>
-        /// <typeparam name="T">The type to be created.</typeparam>
-        /// <param name="source">The binary stream to apply to the new instance (cannot be null).</param>
-        /// <returns>A new, initialized instance.</returns>
-        public static T Deserialize<T>(Stream source)
-        {
-            return (T)RuntimeTypeModel.Default.Deserialize(source, null, typeof(T));
-        }
-
-        /// <summary>
-		/// Creates a new instance from a protocol-buffer stream
-		/// </summary>
-		/// <param name="type">The type to be created.</param>
-		/// <param name="source">The binary stream to apply to the new instance (cannot be null).</param>
-		/// <returns>A new, initialized instance.</returns>
-		public static object Deserialize(Type type, Stream source)
-        {
-            return RuntimeTypeModel.Default.Deserialize(source, null, type);
-        }
-
-        /// <summary>
-        /// Writes a protocol-buffer representation of the given instance to the supplied stream.
-        /// </summary>
-        /// <param name="instance">The existing instance to be serialized (cannot be null).</param>
-        /// <param name="destination">The destination stream to write to.</param>
-        public static void Serialize<T>(Stream destination, T instance)
-        {
-            if (instance != null)
-            {
-                RuntimeTypeModel.Default.Serialize(destination, instance);
-            }
-        }
-
-        /// <summary>
-        /// Serializes a given instance and deserializes it as a different type;
-        /// this can be used to translate between wire-compatible objects (where
-        /// two .NET types represent the same data), or to promote/demote a type
-        /// through an inheritance hierarchy.
-        /// </summary>
-        /// <remarks>No assumption of compatibility is made between the types.</remarks>
-        /// <typeparam name="TFrom">The type of the object being copied.</typeparam>
-        /// <typeparam name="TTo">The type of the new object to be created.</typeparam>
-        /// <param name="instance">The existing instance to use as a template.</param>
-        /// <returns>A new instane of type TNewType, with the data from TOldType.</returns>
-        public static TTo ChangeType<TFrom, TTo>(TFrom instance)
-        {
-            using (var ms = new MemoryStream())
-            {
-                Serialize<TFrom>(ms, instance);
-                ms.Position = 0;
-                return Deserialize<TTo>(ms);
-            }
-        }
-#if PLAT_BINARYFORMATTER && !(COREFX || PROFILE259)
-        /// <summary>
-        /// Writes a protocol-buffer representation of the given instance to the supplied SerializationInfo.
-        /// </summary>
-        /// <typeparam name="T">The type being serialized.</typeparam>
-        /// <param name="instance">The existing instance to be serialized (cannot be null).</param>
-        /// <param name="info">The destination SerializationInfo to write to.</param>
-        public static void Serialize<T>(System.Runtime.Serialization.SerializationInfo info, T instance) where T : class, System.Runtime.Serialization.ISerializable
-        {
-            Serialize<T>(info, new System.Runtime.Serialization.StreamingContext(System.Runtime.Serialization.StreamingContextStates.Persistence), instance);
-        }
-        /// <summary>
-        /// Writes a protocol-buffer representation of the given instance to the supplied SerializationInfo.
-        /// </summary>
-        /// <typeparam name="T">The type being serialized.</typeparam>
-        /// <param name="instance">The existing instance to be serialized (cannot be null).</param>
-        /// <param name="info">The destination SerializationInfo to write to.</param>
-        /// <param name="context">Additional information about this serialization operation.</param>
-        public static void Serialize<T>(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context, T instance) where T : class, System.Runtime.Serialization.ISerializable
-        {
-            // note: also tried byte[]... it doesn't perform hugely well with either (compared to regular serialization)
-            if (info == null) throw new ArgumentNullException("info");
-            if (instance == null) throw new ArgumentNullException("instance");
-            if (instance.GetType() != typeof(T)) throw new ArgumentException("Incorrect type", "instance");
-            using (MemoryStream ms = new MemoryStream())
-            {
-                RuntimeTypeModel.Default.Serialize(ms, instance, context);
-                info.AddValue(ProtoBinaryField, ms.ToArray());
-            }
-        }
-#endif
-#if PLAT_XMLSERIALIZER
-        /// <summary>
-        /// Writes a protocol-buffer representation of the given instance to the supplied XmlWriter.
-        /// </summary>
-        /// <typeparam name="T">The type being serialized.</typeparam>
-        /// <param name="instance">The existing instance to be serialized (cannot be null).</param>
-        /// <param name="writer">The destination XmlWriter to write to.</param>
-        public static void Serialize<T>(System.Xml.XmlWriter writer, T instance) where T : System.Xml.Serialization.IXmlSerializable
-        {
-            if (writer == null) throw new ArgumentNullException("writer");
-            if (instance == null) throw new ArgumentNullException("instance");
-
-            using (MemoryStream ms = new MemoryStream())
-            {
-                Serializer.Serialize(ms, instance);
-                writer.WriteBase64(Helpers.GetBuffer(ms), 0, (int)ms.Length);
-            }
-        }
-        /// <summary>
-        /// Applies a protocol-buffer from an XmlReader to an existing instance.
-        /// </summary>
-        /// <typeparam name="T">The type being merged.</typeparam>
-        /// <param name="instance">The existing instance to be modified (cannot be null).</param>
-        /// <param name="reader">The XmlReader containing the data to apply to the instance (cannot be null).</param>
-        public static void Merge<T>(System.Xml.XmlReader reader, T instance) where T : System.Xml.Serialization.IXmlSerializable
-        {
-            if (reader == null) throw new ArgumentNullException("reader");
-            if (instance == null) throw new ArgumentNullException("instance");
-
-            const int LEN = 4096;
-            byte[] buffer = new byte[LEN];
-            int read;
-            using (MemoryStream ms = new MemoryStream())
-            {
-                int depth = reader.Depth;
-                while(reader.Read() && reader.Depth > depth)
-                {
-                    if (reader.NodeType == System.Xml.XmlNodeType.Text)
-                    {
-                        while ((read = reader.ReadContentAsBase64(buffer, 0, LEN)) > 0)
-                        {
-                            ms.Write(buffer, 0, read);
-                        }
-                        if (reader.Depth <= depth) break;
-                    }
-                }
-                ms.Position = 0;
-                Serializer.Merge(ms, instance);
-            }
-        }
-#endif
-
-        private const string ProtoBinaryField = "proto";
-#if PLAT_BINARYFORMATTER && !(COREFX || PROFILE259)
-        /// <summary>
-        /// Applies a protocol-buffer from a SerializationInfo to an existing instance.
-        /// </summary>
-        /// <typeparam name="T">The type being merged.</typeparam>
-        /// <param name="instance">The existing instance to be modified (cannot be null).</param>
-        /// <param name="info">The SerializationInfo containing the data to apply to the instance (cannot be null).</param>
-        public static void Merge<T>(System.Runtime.Serialization.SerializationInfo info, T instance) where T : class, System.Runtime.Serialization.ISerializable
-        {
-            Merge<T>(info, new System.Runtime.Serialization.StreamingContext(System.Runtime.Serialization.StreamingContextStates.Persistence), instance);
-        }
-        /// <summary>
-        /// Applies a protocol-buffer from a SerializationInfo to an existing instance.
-        /// </summary>
-        /// <typeparam name="T">The type being merged.</typeparam>
-        /// <param name="instance">The existing instance to be modified (cannot be null).</param>
-        /// <param name="info">The SerializationInfo containing the data to apply to the instance (cannot be null).</param>
-        /// <param name="context">Additional information about this serialization operation.</param>
-        public static void Merge<T>(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context, T instance) where T : class, System.Runtime.Serialization.ISerializable
-        {
-            // note: also tried byte[]... it doesn't perform hugely well with either (compared to regular serialization)
-            if (info == null) throw new ArgumentNullException("info");
-            if (instance == null) throw new ArgumentNullException("instance");
-            if (instance.GetType() != typeof(T)) throw new ArgumentException("Incorrect type", "instance");
-
-            byte[] buffer = (byte[])info.GetValue(ProtoBinaryField, typeof(byte[]));
-            using (MemoryStream ms = new MemoryStream(buffer))
-            {
-                T result = (T)RuntimeTypeModel.Default.Deserialize(ms, instance, typeof(T), context);
-                if (!ReferenceEquals(result, instance))
-                {
-                    throw new ProtoException("Deserialization changed the instance; cannot succeed.");
-                }
-            }
-        }
-#endif
-
-        /// <summary>
-        /// Precompiles the serializer for a given type.
-        /// </summary>
-        public static void PrepareSerializer<T>()
-        {
-            NonGeneric.PrepareSerializer(typeof(T));
-        }
-
-#if PLAT_BINARYFORMATTER && !(COREFX || PROFILE259)
-        /// <summary>
-        /// Creates a new IFormatter that uses protocol-buffer [de]serialization.
-        /// </summary>
-        /// <typeparam name="T">The type of object to be [de]deserialized by the formatter.</typeparam>
-        /// <returns>A new IFormatter to be used during [de]serialization.</returns>
-        public static System.Runtime.Serialization.IFormatter CreateFormatter<T>()
-        {
-            return RuntimeTypeModel.Default.CreateFormatter(typeof(T));
-        }
-#endif
-        /// <summary>
-        /// Reads a sequence of consecutive length-prefixed items from a stream, using
-        /// either base-128 or fixed-length prefixes. Base-128 prefixes with a tag
-        /// are directly comparable to serializing multiple items in succession
-        /// (use the <see cref="ListItemTag"/> tag to emulate the implicit behavior
-        /// when serializing a list/array). When a tag is
-        /// specified, any records with different tags are silently omitted. The
-        /// tag is ignored. The tag is ignored for fixed-length prefixes.
-        /// </summary>
-        /// <typeparam name="T">The type of object to deserialize.</typeparam>
-        /// <param name="source">The binary stream containing the serialized records.</param>
-        /// <param name="style">The prefix style used in the data.</param>
-        /// <param name="fieldNumber">The tag of records to return (if non-positive, then no tag is
-        /// expected and all records are returned).</param>
-        /// <returns>The sequence of deserialized objects.</returns>
-        public static IEnumerable<T> DeserializeItems<T>(Stream source, PrefixStyle style, int fieldNumber)
-        {
-            return RuntimeTypeModel.Default.DeserializeItems<T>(source, style, fieldNumber);
-        }
-
-        /// <summary>
-        /// Creates a new instance from a protocol-buffer stream that has a length-prefix
-        /// on data (to assist with network IO).
-        /// </summary>
-        /// <typeparam name="T">The type to be created.</typeparam>
-        /// <param name="source">The binary stream to apply to the new instance (cannot be null).</param>
-        /// <param name="style">How to encode the length prefix.</param>
-        /// <returns>A new, initialized instance.</returns>
-        public static T DeserializeWithLengthPrefix<T>(Stream source, PrefixStyle style)
-        {
-            return DeserializeWithLengthPrefix<T>(source, style, 0);
-        }
-
-        /// <summary>
-        /// Creates a new instance from a protocol-buffer stream that has a length-prefix
-        /// on data (to assist with network IO).
-        /// </summary>
-        /// <typeparam name="T">The type to be created.</typeparam>
-        /// <param name="source">The binary stream to apply to the new instance (cannot be null).</param>
-        /// <param name="style">How to encode the length prefix.</param>
-        /// <param name="fieldNumber">The expected tag of the item (only used with base-128 prefix style).</param>
-        /// <returns>A new, initialized instance.</returns>
-        public static T DeserializeWithLengthPrefix<T>(Stream source, PrefixStyle style, int fieldNumber)
-        {
-            RuntimeTypeModel model = RuntimeTypeModel.Default;
-            return (T)model.DeserializeWithLengthPrefix(source, null, model.MapType(typeof(T)), style, fieldNumber);
-        }
-
-        /// <summary>
-        /// Applies a protocol-buffer stream to an existing instance, using length-prefixed
-        /// data - useful with network IO.
-        /// </summary>
-        /// <typeparam name="T">The type being merged.</typeparam>
-        /// <param name="instance">The existing instance to be modified (can be null).</param>
-        /// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
-        /// <param name="style">How to encode the length prefix.</param>
-        /// <returns>The updated instance; this may be different to the instance argument if
-        /// either the original instance was null, or the stream defines a known sub-type of the
-        /// original instance.</returns>
-        public static T MergeWithLengthPrefix<T>(Stream source, T instance, PrefixStyle style)
-        {
-            RuntimeTypeModel model = RuntimeTypeModel.Default;
-            return (T)model.DeserializeWithLengthPrefix(source, instance, model.MapType(typeof(T)), style, 0);
-        }
-
-        /// <summary>
-        /// Writes a protocol-buffer representation of the given instance to the supplied stream,
-        /// with a length-prefix. This is useful for socket programming,
-        /// as DeserializeWithLengthPrefix/MergeWithLengthPrefix can be used to read the single object back
-        /// from an ongoing stream.
-        /// </summary>
-        /// <typeparam name="T">The type being serialized.</typeparam>
-        /// <param name="instance">The existing instance to be serialized (cannot be null).</param>
-        /// <param name="style">How to encode the length prefix.</param>
-        /// <param name="destination">The destination stream to write to.</param>
-        public static void SerializeWithLengthPrefix<T>(Stream destination, T instance, PrefixStyle style)
-        {
-            SerializeWithLengthPrefix<T>(destination, instance, style, 0);
-        }
-
-        /// <summary>
-        /// Writes a protocol-buffer representation of the given instance to the supplied stream,
-        /// with a length-prefix. This is useful for socket programming,
-        /// as DeserializeWithLengthPrefix/MergeWithLengthPrefix can be used to read the single object back
-        /// from an ongoing stream.
-        /// </summary>
-        /// <typeparam name="T">The type being serialized.</typeparam>
-        /// <param name="instance">The existing instance to be serialized (cannot be null).</param>
-        /// <param name="style">How to encode the length prefix.</param>
-        /// <param name="destination">The destination stream to write to.</param>
-        /// <param name="fieldNumber">The tag used as a prefix to each record (only used with base-128 style prefixes).</param>
-        public static void SerializeWithLengthPrefix<T>(Stream destination, T instance, PrefixStyle style, int fieldNumber)
-        {
-            RuntimeTypeModel model = RuntimeTypeModel.Default;
-            model.SerializeWithLengthPrefix(destination, instance, model.MapType(typeof(T)), style, fieldNumber);
-        }
-
-        /// <summary>Indicates the number of bytes expected for the next message.</summary>
-        /// <param name="source">The stream containing the data to investigate for a length.</param>
-        /// <param name="style">The algorithm used to encode the length.</param>
-        /// <param name="length">The length of the message, if it could be identified.</param>
-        /// <returns>True if a length could be obtained, false otherwise.</returns>
-        public static bool TryReadLengthPrefix(Stream source, PrefixStyle style, out int length)
-        {
-            length = ProtoReader.ReadLengthPrefix(source, false, style, out int fieldNumber, out int bytesRead);
-            return bytesRead > 0;
-        }
-
-        /// <summary>Indicates the number of bytes expected for the next message.</summary>
-        /// <param name="buffer">The buffer containing the data to investigate for a length.</param>
-        /// <param name="index">The offset of the first byte to read from the buffer.</param>
-        /// <param name="count">The number of bytes to read from the buffer.</param>
-        /// <param name="style">The algorithm used to encode the length.</param>
-        /// <param name="length">The length of the message, if it could be identified.</param>
-        /// <returns>True if a length could be obtained, false otherwise.</returns>
-        public static bool TryReadLengthPrefix(byte[] buffer, int index, int count, PrefixStyle style, out int length)
-        {
-            using (Stream source = new MemoryStream(buffer, index, count))
-            {
-                return TryReadLengthPrefix(source, style, out length);
-            }
-        }
-#endif
-        /// <summary>
-        /// The field number that is used as a default when serializing/deserializing a list of objects.
-        /// The data is treated as repeated message with field number 1.
-        /// </summary>
-        public const int ListItemTag = 1;
-
-
-#if !NO_RUNTIME
-        /// <summary>
-        /// Provides non-generic access to the default serializer.
-        /// </summary>
-        public static class NonGeneric
-        {
-            /// <summary>
-            /// Create a deep clone of the supplied instance; any sub-items are also cloned.
-            /// </summary>
-            public static object DeepClone(object instance)
-            {
-                return instance == null ? null : RuntimeTypeModel.Default.DeepClone(instance);
-            }
-
-            /// <summary>
-            /// Writes a protocol-buffer representation of the given instance to the supplied stream.
-            /// </summary>
-            /// <param name="instance">The existing instance to be serialized (cannot be null).</param>
-            /// <param name="dest">The destination stream to write to.</param>
-            public static void Serialize(Stream dest, object instance)
-            {
-                if (instance != null)
-                {
-                    RuntimeTypeModel.Default.Serialize(dest, instance);
-                }
-            }
-
-            /// <summary>
-            /// Creates a new instance from a protocol-buffer stream
-            /// </summary>
-            /// <param name="type">The type to be created.</param>
-            /// <param name="source">The binary stream to apply to the new instance (cannot be null).</param>
-            /// <returns>A new, initialized instance.</returns>
-            public static object Deserialize(Type type, Stream source)
-            {
-                return RuntimeTypeModel.Default.Deserialize(source, null, type);
-            }
-
-            /// <summary>Applies a protocol-buffer stream to an existing instance.</summary>
-            /// <param name="instance">The existing instance to be modified (cannot be null).</param>
-            /// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
-            /// <returns>The updated instance</returns>
-            public static object Merge(Stream source, object instance)
-            {
-                if (instance == null) throw new ArgumentNullException(nameof(instance));
-                return RuntimeTypeModel.Default.Deserialize(source, instance, instance.GetType(), null);
-            }
-
-            /// <summary>
-            /// Writes a protocol-buffer representation of the given instance to the supplied stream,
-            /// with a length-prefix. This is useful for socket programming,
-            /// as DeserializeWithLengthPrefix/MergeWithLengthPrefix can be used to read the single object back
-            /// from an ongoing stream.
-            /// </summary>
-            /// <param name="instance">The existing instance to be serialized (cannot be null).</param>
-            /// <param name="style">How to encode the length prefix.</param>
-            /// <param name="destination">The destination stream to write to.</param>
-            /// <param name="fieldNumber">The tag used as a prefix to each record (only used with base-128 style prefixes).</param>
-            public static void SerializeWithLengthPrefix(Stream destination, object instance, PrefixStyle style, int fieldNumber)
-            {
-                if (instance == null) throw new ArgumentNullException(nameof(instance));
-                RuntimeTypeModel model = RuntimeTypeModel.Default;
-                model.SerializeWithLengthPrefix(destination, instance, model.MapType(instance.GetType()), style, fieldNumber);
-            }
-            /// <summary>
-            /// Applies a protocol-buffer stream to an existing instance (or null), using length-prefixed
-            /// data - useful with network IO.
-            /// </summary>
-            /// <param name="value">The existing instance to be modified (can be null).</param>
-            /// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
-            /// <param name="style">How to encode the length prefix.</param>
-            /// <param name="resolver">Used to resolve types on a per-field basis.</param>
-            /// <returns>The updated instance; this may be different to the instance argument if
-            /// either the original instance was null, or the stream defines a known sub-type of the
-            /// original instance.</returns>
-            public static bool TryDeserializeWithLengthPrefix(Stream source, PrefixStyle style, TypeResolver resolver, out object value)
-            {
-                value = RuntimeTypeModel.Default.DeserializeWithLengthPrefix(source, null, null, style, 0, resolver);
-                return value != null;
-            }
-
-            /// <summary>
-            /// Indicates whether the supplied type is explicitly modelled by the model
-            /// </summary>
-            public static bool CanSerialize(Type type) => RuntimeTypeModel.Default.IsDefined(type);
-
-            /// <summary>
-            /// Precompiles the serializer for a given type.
-            /// </summary>
-            public static void PrepareSerializer(Type t)
-            {
-#if FEAT_COMPILER
-                RuntimeTypeModel model = RuntimeTypeModel.Default;
-                model[model.MapType(t)].CompileInPlace();
-#endif
-            }
-        }
-
-        /// <summary>
-        /// Global switches that change the behavior of protobuf-net
-        /// </summary>
-        public static class GlobalOptions
-        {
-            /// <summary>
-            /// <see cref="RuntimeTypeModel.InferTagFromNameDefault"/>
-            /// </summary>
-            [Obsolete("Please use RuntimeTypeModel.Default.InferTagFromNameDefault instead (or on a per-model basis)", false)]
-            public static bool InferTagFromName
-            {
-                get { return RuntimeTypeModel.Default.InferTagFromNameDefault; }
-                set { RuntimeTypeModel.Default.InferTagFromNameDefault = value; }
-            }
-        }
-#endif
-        /// <summary>
-        /// Maps a field-number to a type
-        /// </summary>
-        public delegate Type TypeResolver(int fieldNumber);
-
-        /// <summary>
-        /// Releases any internal buffers that have been reserved for efficiency; this does not affect any serialization
-        /// operations; simply: it can be used (optionally) to release the buffers for garbage collection (at the expense
-        /// of having to re-allocate a new buffer for the next operation, rather than re-use prior buffers).
-        /// </summary>
-        public static void FlushPool()
-        {
-            BufferPool.Flush();
-        }
-    }
-}

+ 0 - 310
ThirdParty/protobuf-net/Serializers/ArrayDecorator.cs

@@ -1,310 +0,0 @@
-#if !NO_RUNTIME
-using System;
-using System.Collections;
-using System.Reflection;
-using ProtoBuf.Meta;
-
-namespace ProtoBuf.Serializers
-{
-    sealed class ArrayDecorator : ProtoDecoratorBase
-    {
-        private readonly int fieldNumber;
-        private const byte
-                   OPTIONS_WritePacked = 1,
-                   OPTIONS_OverwriteList = 2,
-                   OPTIONS_SupportNull = 4;
-        private readonly byte options;
-        private readonly WireType packedWireType;
-        public ArrayDecorator(TypeModel model, IProtoSerializer tail, int fieldNumber, bool writePacked, WireType packedWireType, Type arrayType, bool overwriteList, bool supportNull)
-            : base(tail)
-        {
-            Helpers.DebugAssert(arrayType != null, "arrayType should be non-null");
-            Helpers.DebugAssert(arrayType.IsArray && arrayType.GetArrayRank() == 1, "should be single-dimension array; " + arrayType.FullName);
-            this.itemType = arrayType.GetElementType();
-            Type underlyingItemType = supportNull ? itemType : (Helpers.GetUnderlyingType(itemType) ?? itemType);
-
-            Helpers.DebugAssert(underlyingItemType == Tail.ExpectedType
-                || (Tail.ExpectedType == model.MapType(typeof(object)) && !Helpers.IsValueType(underlyingItemType)), "invalid tail");
-            Helpers.DebugAssert(Tail.ExpectedType != model.MapType(typeof(byte)), "Should have used BlobSerializer");
-            if ((writePacked || packedWireType != WireType.None) && fieldNumber <= 0) throw new ArgumentOutOfRangeException("fieldNumber");
-            if (!ListDecorator.CanPack(packedWireType))
-            {
-                if (writePacked) throw new InvalidOperationException("Only simple data-types can use packed encoding");
-                packedWireType = WireType.None;
-            }
-            this.fieldNumber = fieldNumber;
-            this.packedWireType = packedWireType;
-            if (writePacked) options |= OPTIONS_WritePacked;
-            if (overwriteList) options |= OPTIONS_OverwriteList;
-            if (supportNull) options |= OPTIONS_SupportNull;
-            this.arrayType = arrayType;
-        }
-        readonly Type arrayType, itemType; // this is, for example, typeof(int[])
-        public override Type ExpectedType { get { return arrayType; } }
-        public override bool RequiresOldValue { get { return AppendToCollection; } }
-        public override bool ReturnsValue { get { return true; } }
-        private bool CanUsePackedPrefix() => CanUsePackedPrefix(packedWireType, itemType);
-
-        internal static bool CanUsePackedPrefix(WireType packedWireType, Type itemType)
-        {
-            // needs to be a suitably simple type *and* be definitely not nullable
-            switch (packedWireType)
-            {
-                case WireType.Fixed32:
-                case WireType.Fixed64:
-                    break;
-                default:
-                    return false; // nope
-            }
-            if (!Helpers.IsValueType(itemType)) return false;
-            return Helpers.GetUnderlyingType(itemType) == null;
-        }
-
-#if FEAT_COMPILER
-        protected override void EmitWrite(ProtoBuf.Compiler.CompilerContext ctx, ProtoBuf.Compiler.Local valueFrom)
-        {
-            // int i and T[] arr
-            using (Compiler.Local arr = ctx.GetLocalWithValue(arrayType, valueFrom))
-            using (Compiler.Local i = new ProtoBuf.Compiler.Local(ctx, ctx.MapType(typeof(int))))
-            {
-                bool writePacked = (options & OPTIONS_WritePacked) != 0;
-                bool fixedLengthPacked = writePacked && CanUsePackedPrefix();
-
-                using (Compiler.Local token = (writePacked && !fixedLengthPacked) ? new Compiler.Local(ctx, ctx.MapType(typeof(SubItemToken))) : null)
-                {
-                    Type mappedWriter = ctx.MapType(typeof(ProtoWriter));
-                    if (writePacked)
-                    {
-                        ctx.LoadValue(fieldNumber);
-                        ctx.LoadValue((int)WireType.String);
-                        ctx.LoadReaderWriter();
-                        ctx.EmitCall(mappedWriter.GetMethod("WriteFieldHeader"));
-
-                        if (fixedLengthPacked)
-                        {
-                            // write directly - no need for buffering
-                            ctx.LoadLength(arr, false);
-                            ctx.LoadValue((int)packedWireType);
-                            ctx.LoadReaderWriter();
-                            ctx.EmitCall(mappedWriter.GetMethod("WritePackedPrefix"));
-                        }
-                        else
-                        {
-                            ctx.LoadValue(arr);
-                            ctx.LoadReaderWriter();
-                            ctx.EmitCall(mappedWriter.GetMethod("StartSubItem"));
-                            ctx.StoreValue(token);
-                        }
-                        ctx.LoadValue(fieldNumber);
-                        ctx.LoadReaderWriter();
-                        ctx.EmitCall(mappedWriter.GetMethod("SetPackedField"));
-                    }
-                    EmitWriteArrayLoop(ctx, i, arr);
-
-                    if (writePacked)
-                    {
-                        if (fixedLengthPacked)
-                        {
-                            ctx.LoadValue(fieldNumber);
-                            ctx.LoadReaderWriter();
-                            ctx.EmitCall(mappedWriter.GetMethod("ClearPackedField"));
-                        }
-                        else
-                        {
-                            ctx.LoadValue(token);
-                            ctx.LoadReaderWriter();
-                            ctx.EmitCall(mappedWriter.GetMethod("EndSubItem"));
-                        }
-                    }
-                }
-            }
-        }
-
-        private void EmitWriteArrayLoop(Compiler.CompilerContext ctx, Compiler.Local i, Compiler.Local arr)
-        {
-            // i = 0
-            ctx.LoadValue(0);
-            ctx.StoreValue(i);
-
-            // range test is last (to minimise branches)
-            Compiler.CodeLabel loopTest = ctx.DefineLabel(), processItem = ctx.DefineLabel();
-            ctx.Branch(loopTest, false);
-            ctx.MarkLabel(processItem);
-
-            // {...}
-            ctx.LoadArrayValue(arr, i);
-            if (SupportNull)
-            {
-                Tail.EmitWrite(ctx, null);
-            }
-            else
-            {
-                ctx.WriteNullCheckedTail(itemType, Tail, null);
-            }
-
-            // i++
-            ctx.LoadValue(i);
-            ctx.LoadValue(1);
-            ctx.Add();
-            ctx.StoreValue(i);
-
-            // i < arr.Length
-            ctx.MarkLabel(loopTest);
-            ctx.LoadValue(i);
-            ctx.LoadLength(arr, false);
-            ctx.BranchIfLess(processItem, false);
-        }
-#endif
-        private bool AppendToCollection => (options & OPTIONS_OverwriteList) == 0;
-
-        private bool SupportNull { get { return (options & OPTIONS_SupportNull) != 0; } }
-
-        public override void Write(object value, ProtoWriter dest)
-        {
-            IList arr = (IList)value;
-            int len = arr.Count;
-            SubItemToken token;
-            bool writePacked = (options & OPTIONS_WritePacked) != 0;
-            bool fixedLengthPacked = writePacked && CanUsePackedPrefix();
-
-            if (writePacked)
-            {
-                ProtoWriter.WriteFieldHeader(fieldNumber, WireType.String, dest);
-
-                if (fixedLengthPacked)
-                {
-                    ProtoWriter.WritePackedPrefix(arr.Count, packedWireType, dest);
-                    token = new SubItemToken(); // default
-                }
-                else
-                {
-                    token = ProtoWriter.StartSubItem(value, dest);
-                }
-                ProtoWriter.SetPackedField(fieldNumber, dest);
-            }
-            else
-            {
-                token = new SubItemToken(); // default
-            }
-            bool checkForNull = !SupportNull;
-            for (int i = 0; i < len; i++)
-            {
-                object obj = arr[i];
-                if (checkForNull && obj == null) { throw new NullReferenceException(); }
-                Tail.Write(obj, dest);
-            }
-            if (writePacked)
-            {
-                if (fixedLengthPacked)
-                {
-                    ProtoWriter.ClearPackedField(fieldNumber, dest);
-                }
-                else
-                {
-                    ProtoWriter.EndSubItem(token, dest);
-                }
-            }
-        }
-        public override object Read(object value, ProtoReader source)
-        {
-            int field = source.FieldNumber;
-            BasicList list = new BasicList();
-            if (packedWireType != WireType.None && source.WireType == WireType.String)
-            {
-                SubItemToken token = ProtoReader.StartSubItem(source);
-                while (ProtoReader.HasSubValue(packedWireType, source))
-                {
-                    list.Add(Tail.Read(null, source));
-                }
-                ProtoReader.EndSubItem(token, source);
-            }
-            else
-            {
-                do
-                {
-                    list.Add(Tail.Read(null, source));
-                } while (source.TryReadFieldHeader(field));
-            }
-            int oldLen = AppendToCollection ? ((value == null ? 0 : ((Array)value).Length)) : 0;
-            Array result = Array.CreateInstance(itemType, oldLen + list.Count);
-            if (oldLen != 0) ((Array)value).CopyTo(result, 0);
-            list.CopyTo(result, oldLen);
-            return result;
-        }
-
-#if FEAT_COMPILER
-        protected override void EmitRead(ProtoBuf.Compiler.CompilerContext ctx, ProtoBuf.Compiler.Local valueFrom)
-        {
-            Type listType;
-            listType = ctx.MapType(typeof(System.Collections.Generic.List<>)).MakeGenericType(itemType);
-            Type expected = ExpectedType;
-            using (Compiler.Local oldArr = AppendToCollection ? ctx.GetLocalWithValue(expected, valueFrom) : null)
-            using (Compiler.Local newArr = new Compiler.Local(ctx, expected))
-            using (Compiler.Local list = new Compiler.Local(ctx, listType))
-            {
-                ctx.EmitCtor(listType);
-                ctx.StoreValue(list);
-                ListDecorator.EmitReadList(ctx, list, Tail, listType.GetMethod("Add"), packedWireType, false);
-
-                // leave this "using" here, as it can share the "FieldNumber" local with EmitReadList
-                using (Compiler.Local oldLen = AppendToCollection ? new ProtoBuf.Compiler.Local(ctx, ctx.MapType(typeof(int))) : null)
-                {
-                    Type[] copyToArrayInt32Args = new Type[] { ctx.MapType(typeof(Array)), ctx.MapType(typeof(int)) };
-
-                    if (AppendToCollection)
-                    {
-                        ctx.LoadLength(oldArr, true);
-                        ctx.CopyValue();
-                        ctx.StoreValue(oldLen);
-
-                        ctx.LoadAddress(list, listType);
-                        ctx.LoadValue(listType.GetProperty("Count"));
-                        ctx.Add();
-                        ctx.CreateArray(itemType, null); // length is on the stack
-                        ctx.StoreValue(newArr);
-
-                        ctx.LoadValue(oldLen);
-                        Compiler.CodeLabel nothingToCopy = ctx.DefineLabel();
-                        ctx.BranchIfFalse(nothingToCopy, true);
-                        ctx.LoadValue(oldArr);
-                        ctx.LoadValue(newArr);
-                        ctx.LoadValue(0); // index in target
-
-                        ctx.EmitCall(expected.GetMethod("CopyTo", copyToArrayInt32Args));
-                        ctx.MarkLabel(nothingToCopy);
-
-                        ctx.LoadValue(list);
-                        ctx.LoadValue(newArr);
-                        ctx.LoadValue(oldLen);
-
-                    }
-                    else
-                    {
-                        ctx.LoadAddress(list, listType);
-                        ctx.LoadValue(listType.GetProperty("Count"));
-                        ctx.CreateArray(itemType, null);
-                        ctx.StoreValue(newArr);
-
-                        ctx.LoadAddress(list, listType);
-                        ctx.LoadValue(newArr);
-                        ctx.LoadValue(0);
-                    }
-
-                    copyToArrayInt32Args[0] = expected; // // prefer: CopyTo(T[], int)
-                    MethodInfo copyTo = listType.GetMethod("CopyTo", copyToArrayInt32Args);
-                    if (copyTo == null)
-                    { // fallback: CopyTo(Array, int)
-                        copyToArrayInt32Args[1] = ctx.MapType(typeof(Array));
-                        copyTo = listType.GetMethod("CopyTo", copyToArrayInt32Args);
-                    }
-                    ctx.EmitCall(copyTo);
-                }
-                ctx.LoadValue(newArr);
-            }
-
-
-        }
-#endif
-    }
-}
-#endif

+ 0 - 59
ThirdParty/protobuf-net/Serializers/BlobSerializer.cs

@@ -1,59 +0,0 @@
-#if !NO_RUNTIME
-using System;
-#if COREFX
-using System.Reflection;
-#endif
-#if FEAT_COMPILER
-using System.Reflection.Emit;
-#endif
-
-namespace ProtoBuf.Serializers
-{
-    sealed class BlobSerializer : IProtoSerializer
-    {
-        public Type ExpectedType { get { return expectedType; } }
-
-        static readonly Type expectedType = typeof(byte[]);
-
-        public BlobSerializer(ProtoBuf.Meta.TypeModel model, bool overwriteList)
-        {
-            this.overwriteList = overwriteList;
-        }
-
-        private readonly bool overwriteList;
-
-        public object Read(object value, ProtoReader source)
-        {
-            return ProtoReader.AppendBytes(overwriteList ? null : (byte[])value, source);
-        }
-
-        public void Write(object value, ProtoWriter dest)
-        {
-            ProtoWriter.WriteBytes((byte[])value, dest);
-        }
-
-        bool IProtoSerializer.RequiresOldValue { get { return !overwriteList; } }
-        bool IProtoSerializer.ReturnsValue { get { return true; } }
-#if FEAT_COMPILER
-        void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ctx.EmitBasicWrite("WriteBytes", valueFrom);
-        }
-        void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            if (overwriteList)
-            {
-                ctx.LoadNullRef();
-            }
-            else
-            {
-                ctx.LoadValue(valueFrom);
-            }
-            ctx.LoadReaderWriter();
-            ctx.EmitCall(ctx.MapType(typeof(ProtoReader))
-               .GetMethod("AppendBytes"));
-        }
-#endif
-    }
-}
-#endif

+ 0 - 41
ThirdParty/protobuf-net/Serializers/BooleanSerializer.cs

@@ -1,41 +0,0 @@
-#if !NO_RUNTIME
-using System;
-
-namespace ProtoBuf.Serializers
-{
-    sealed class BooleanSerializer : IProtoSerializer
-    {
-        static readonly Type expectedType = typeof(bool);
-
-        public BooleanSerializer(ProtoBuf.Meta.TypeModel model) { }
-
-        public Type ExpectedType => expectedType;
-
-        public void Write(object value, ProtoWriter dest)
-        {
-            ProtoWriter.WriteBoolean((bool)value, dest);
-        }
-
-        public object Read(object value, ProtoReader source)
-        {
-            Helpers.DebugAssert(value == null); // since replaces
-            return source.ReadBoolean();
-        }
-
-        bool IProtoSerializer.RequiresOldValue => false;
-
-        bool IProtoSerializer.ReturnsValue => true;
-
-#if FEAT_COMPILER
-        void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ctx.EmitBasicWrite("WriteBoolean", valueFrom);
-        }
-        void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ctx.EmitBasicRead("ReadBoolean", ExpectedType);
-        }
-#endif
-    }
-}
-#endif

+ 0 - 42
ThirdParty/protobuf-net/Serializers/ByteSerializer.cs

@@ -1,42 +0,0 @@
-#if !NO_RUNTIME
-using System;
-
-namespace ProtoBuf.Serializers
-{
-    sealed class ByteSerializer : IProtoSerializer
-    {
-        public Type ExpectedType { get { return expectedType; } }
-
-        static readonly Type expectedType = typeof(byte);
-
-        public ByteSerializer(ProtoBuf.Meta.TypeModel model) { }
-
-        bool IProtoSerializer.RequiresOldValue => false;
-
-        bool IProtoSerializer.ReturnsValue => true;
-
-        public void Write(object value, ProtoWriter dest)
-        {
-            ProtoWriter.WriteByte((byte)value, dest);
-        }
-
-        public object Read(object value, ProtoReader source)
-        {
-            Helpers.DebugAssert(value == null); // since replaces
-            return source.ReadByte();
-        }
-
-#if FEAT_COMPILER
-        void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ctx.EmitBasicWrite("WriteByte", valueFrom);
-        }
-
-        void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ctx.EmitBasicRead("ReadByte", ExpectedType);
-        }
-#endif
-    }
-}
-#endif

+ 0 - 32
ThirdParty/protobuf-net/Serializers/CharSerializer.cs

@@ -1,32 +0,0 @@
-#if !NO_RUNTIME
-using System;
-
-namespace ProtoBuf.Serializers
-{
-    sealed class CharSerializer : UInt16Serializer
-    {
-        static readonly Type expectedType = typeof(char);
-
-        public CharSerializer(ProtoBuf.Meta.TypeModel model) : base(model)
-        {
-
-        }
-
-        public override Type ExpectedType => expectedType;
-
-        public override void Write(object value, ProtoWriter dest)
-        {
-            ProtoWriter.WriteUInt16((ushort)(char)value, dest);
-        }
-
-        public override object Read(object value, ProtoReader source)
-        {
-            Helpers.DebugAssert(value == null); // since replaces
-            return (char)source.ReadUInt16();
-        }
-
-        // no need for any special IL here; ushort and char are
-        // interchangeable as long as there is no boxing/unboxing
-    }
-}
-#endif

+ 0 - 88
ThirdParty/protobuf-net/Serializers/CompiledSerializer.cs

@@ -1,88 +0,0 @@
-#if FEAT_COMPILER
-using System;
-using ProtoBuf.Meta;
-
-namespace ProtoBuf.Serializers
-{
-    sealed class CompiledSerializer : IProtoTypeSerializer
-    {
-        bool IProtoTypeSerializer.HasCallbacks(TypeModel.CallbackType callbackType)
-        {
-            return head.HasCallbacks(callbackType); // these routes only used when bits of the model not compiled
-        }
-
-        bool IProtoTypeSerializer.CanCreateInstance()
-        {
-            return head.CanCreateInstance();
-        }
-
-        object IProtoTypeSerializer.CreateInstance(ProtoReader source)
-        {
-            return head.CreateInstance(source);
-        }
-
-        public void Callback(object value, TypeModel.CallbackType callbackType, SerializationContext context)
-        {
-            head.Callback(value, callbackType, context); // these routes only used when bits of the model not compiled
-        }
-
-        public static CompiledSerializer Wrap(IProtoTypeSerializer head, TypeModel model)
-        {
-            CompiledSerializer result = head as CompiledSerializer;
-            if (result == null)
-            {
-                result = new CompiledSerializer(head, model);
-                Helpers.DebugAssert(((IProtoTypeSerializer)result).ExpectedType == head.ExpectedType);
-            }
-            return result;
-        }
-
-        private readonly IProtoTypeSerializer head;
-        private readonly Compiler.ProtoSerializer serializer;
-        private readonly Compiler.ProtoDeserializer deserializer;
-
-        private CompiledSerializer(IProtoTypeSerializer head, TypeModel model)
-        {
-            this.head = head;
-            serializer = Compiler.CompilerContext.BuildSerializer(head, model);
-            deserializer = Compiler.CompilerContext.BuildDeserializer(head, model);
-        }
-
-        bool IProtoSerializer.RequiresOldValue => head.RequiresOldValue;
-
-        bool IProtoSerializer.ReturnsValue => head.ReturnsValue;
-
-        Type IProtoSerializer.ExpectedType => head.ExpectedType;
-
-        void IProtoSerializer.Write(object value, ProtoWriter dest)
-        {
-            serializer(value, dest);
-        }
-
-        object IProtoSerializer.Read(object value, ProtoReader source)
-        {
-            return deserializer(value, source);
-        }
-
-        void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            head.EmitWrite(ctx, valueFrom);
-        }
-
-        void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            head.EmitRead(ctx, valueFrom);
-        }
-
-        void IProtoTypeSerializer.EmitCallback(Compiler.CompilerContext ctx, Compiler.Local valueFrom, TypeModel.CallbackType callbackType)
-        {
-            head.EmitCallback(ctx, valueFrom, callbackType);
-        }
-
-        void IProtoTypeSerializer.EmitCreateInstance(Compiler.CompilerContext ctx)
-        {
-            head.EmitCreateInstance(ctx);
-        }
-    }
-}
-#endif

+ 0 - 65
ThirdParty/protobuf-net/Serializers/DateTimeSerializer.cs

@@ -1,65 +0,0 @@
-#if !NO_RUNTIME
-using System;
-using System.Reflection;
-
-namespace ProtoBuf.Serializers
-{
-    internal sealed class DateTimeSerializer : IProtoSerializer
-    {
-        private static readonly Type expectedType = typeof(DateTime);
-
-        public Type ExpectedType => expectedType;
-
-        bool IProtoSerializer.RequiresOldValue => false;
-        bool IProtoSerializer.ReturnsValue => true;
-
-        private readonly bool includeKind, wellKnown;
-
-        public DateTimeSerializer(DataFormat dataFormat, ProtoBuf.Meta.TypeModel model)
-        {
-            wellKnown = dataFormat == DataFormat.WellKnown;
-            includeKind = model?.SerializeDateTimeKind() == true;
-        }
-
-        public object Read(object value, ProtoReader source)
-        {
-            if (wellKnown)
-            {
-                return BclHelpers.ReadTimestamp(source);
-            }
-            else
-            {
-                Helpers.DebugAssert(value == null); // since replaces
-                return BclHelpers.ReadDateTime(source);
-            }
-        }
-
-        public void Write(object value, ProtoWriter dest)
-        {
-            if (wellKnown)
-                BclHelpers.WriteTimestamp((DateTime)value, dest);
-            else if (includeKind)
-                BclHelpers.WriteDateTimeWithKind((DateTime)value, dest);
-            else
-                BclHelpers.WriteDateTime((DateTime)value, dest);
-        }
-#if FEAT_COMPILER
-        void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ctx.EmitWrite(ctx.MapType(typeof(BclHelpers)),
-                wellKnown ? nameof(BclHelpers.WriteTimestamp)
-                : includeKind ? nameof(BclHelpers.WriteDateTimeWithKind) : nameof(BclHelpers.WriteDateTime), valueFrom);
-        }
-
-        void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local entity)
-        {
-            if (wellKnown) ctx.LoadValue(entity);
-            ctx.EmitBasicRead(ctx.MapType(typeof(BclHelpers)),
-                wellKnown ? nameof(BclHelpers.ReadTimestamp) : nameof(BclHelpers.ReadDateTime),
-                ExpectedType);
-        }
-#endif
-
-    }
-}
-#endif

+ 0 - 42
ThirdParty/protobuf-net/Serializers/DecimalSerializer.cs

@@ -1,42 +0,0 @@
-#if !NO_RUNTIME
-using System;
-
-namespace ProtoBuf.Serializers
-{
-    sealed class DecimalSerializer : IProtoSerializer
-    {
-        static readonly Type expectedType = typeof(decimal);
-
-        public DecimalSerializer(ProtoBuf.Meta.TypeModel model) { }
-
-        public Type ExpectedType => expectedType;
-
-        bool IProtoSerializer.RequiresOldValue => false;
-
-        bool IProtoSerializer.ReturnsValue => true;
-
-        public object Read(object value, ProtoReader source)
-        {
-            Helpers.DebugAssert(value == null); // since replaces
-            return BclHelpers.ReadDecimal(source);
-        }
-
-        public void Write(object value, ProtoWriter dest)
-        {
-            BclHelpers.WriteDecimal((decimal)value, dest);
-        }
-
-#if FEAT_COMPILER
-        void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ctx.EmitWrite(ctx.MapType(typeof(BclHelpers)), "WriteDecimal", valueFrom);
-        }
-        void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ctx.EmitBasicRead(ctx.MapType(typeof(BclHelpers)), "ReadDecimal", ExpectedType);
-        }
-#endif
-
-    }
-}
-#endif

+ 0 - 259
ThirdParty/protobuf-net/Serializers/DefaultValueDecorator.cs

@@ -1,259 +0,0 @@
-#if !NO_RUNTIME
-using System;
-using System.Reflection;
-using ProtoBuf.Meta;
-
-namespace ProtoBuf.Serializers
-{
-    sealed class DefaultValueDecorator : ProtoDecoratorBase
-    {
-        public override Type ExpectedType => Tail.ExpectedType;
-
-        public override bool RequiresOldValue => Tail.RequiresOldValue;
-
-        public override bool ReturnsValue => Tail.ReturnsValue;
-
-        private readonly object defaultValue;
-        public DefaultValueDecorator(TypeModel model, object defaultValue, IProtoSerializer tail) : base(tail)
-        {
-            if (defaultValue == null) throw new ArgumentNullException(nameof(defaultValue));
-            Type type = model.MapType(defaultValue.GetType());
-            if (type != tail.ExpectedType)
-            {
-                throw new ArgumentException("Default value is of incorrect type", "defaultValue");
-            }
-            this.defaultValue = defaultValue;
-        }
-
-        public override void Write(object value, ProtoWriter dest)
-        {
-            if (!object.Equals(value, defaultValue))
-            {
-                Tail.Write(value, dest);
-            }
-        }
-
-        public override object Read(object value, ProtoReader source)
-        {
-            return Tail.Read(value, source);
-        }
-
-#if FEAT_COMPILER
-        protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            Compiler.CodeLabel done = ctx.DefineLabel();
-            if (valueFrom == null)
-            {
-                ctx.CopyValue(); // on the stack
-                Compiler.CodeLabel needToPop = ctx.DefineLabel();
-                EmitBranchIfDefaultValue(ctx, needToPop);
-                Tail.EmitWrite(ctx, null);
-                ctx.Branch(done, true);
-                ctx.MarkLabel(needToPop);
-                ctx.DiscardValue();
-            }
-            else
-            {
-                ctx.LoadValue(valueFrom); // variable/parameter
-                EmitBranchIfDefaultValue(ctx, done);
-                Tail.EmitWrite(ctx, valueFrom);
-            }
-            ctx.MarkLabel(done);
-        }
-        private void EmitBeq(Compiler.CompilerContext ctx, Compiler.CodeLabel label, Type type)
-        {
-            switch (Helpers.GetTypeCode(type))
-            {
-                case ProtoTypeCode.Boolean:
-                case ProtoTypeCode.Byte:
-                case ProtoTypeCode.Char:
-                case ProtoTypeCode.Double:
-                case ProtoTypeCode.Int16:
-                case ProtoTypeCode.Int32:
-                case ProtoTypeCode.Int64:
-                case ProtoTypeCode.SByte:
-                case ProtoTypeCode.Single:
-                case ProtoTypeCode.UInt16:
-                case ProtoTypeCode.UInt32:
-                case ProtoTypeCode.UInt64:
-                    ctx.BranchIfEqual(label, false);
-                    break;
-                default:
-#if COREFX
-                    MethodInfo method = type.GetMethod("op_Equality", new Type[] { type, type });
-                    if (method == null || !method.IsPublic || !method.IsStatic) method = null;
-#else
-                    MethodInfo method = type.GetMethod("op_Equality", BindingFlags.Public | BindingFlags.Static,
-                        null, new Type[] { type, type }, null);
-#endif
-                    if (method == null || method.ReturnType != ctx.MapType(typeof(bool)))
-                    {
-                        throw new InvalidOperationException("No suitable equality operator found for default-values of type: " + type.FullName);
-                    }
-                    ctx.EmitCall(method);
-                    ctx.BranchIfTrue(label, false);
-                    break;
-
-            }
-        }
-        private void EmitBranchIfDefaultValue(Compiler.CompilerContext ctx, Compiler.CodeLabel label)
-        {
-            Type expected = ExpectedType;
-            switch (Helpers.GetTypeCode(expected))
-            {
-                case ProtoTypeCode.Boolean:
-                    if ((bool)defaultValue)
-                    {
-                        ctx.BranchIfTrue(label, false);
-                    }
-                    else
-                    {
-                        ctx.BranchIfFalse(label, false);
-                    }
-                    break;
-                case ProtoTypeCode.Byte:
-                    if ((byte)defaultValue == (byte)0)
-                    {
-                        ctx.BranchIfFalse(label, false);
-                    }
-                    else
-                    {
-                        ctx.LoadValue((int)(byte)defaultValue);
-                        EmitBeq(ctx, label, expected);
-                    }
-                    break;
-                case ProtoTypeCode.SByte:
-                    if ((sbyte)defaultValue == (sbyte)0)
-                    {
-                        ctx.BranchIfFalse(label, false);
-                    }
-                    else
-                    {
-                        ctx.LoadValue((int)(sbyte)defaultValue);
-                        EmitBeq(ctx, label, expected);
-                    }
-                    break;
-                case ProtoTypeCode.Int16:
-                    if ((short)defaultValue == (short)0)
-                    {
-                        ctx.BranchIfFalse(label, false);
-                    }
-                    else
-                    {
-                        ctx.LoadValue((int)(short)defaultValue);
-                        EmitBeq(ctx, label, expected);
-                    }
-                    break;
-                case ProtoTypeCode.UInt16:
-                    if ((ushort)defaultValue == (ushort)0)
-                    {
-                        ctx.BranchIfFalse(label, false);
-                    }
-                    else
-                    {
-                        ctx.LoadValue((int)(ushort)defaultValue);
-                        EmitBeq(ctx, label, expected);
-                    }
-                    break;
-                case ProtoTypeCode.Int32:
-                    if ((int)defaultValue == (int)0)
-                    {
-                        ctx.BranchIfFalse(label, false);
-                    }
-                    else
-                    {
-                        ctx.LoadValue((int)defaultValue);
-                        EmitBeq(ctx, label, expected);
-                    }
-                    break;
-                case ProtoTypeCode.UInt32:
-                    if ((uint)defaultValue == (uint)0)
-                    {
-                        ctx.BranchIfFalse(label, false);
-                    }
-                    else
-                    {
-                        ctx.LoadValue((int)(uint)defaultValue);
-                        EmitBeq(ctx, label, expected);
-                    }
-                    break;
-                case ProtoTypeCode.Char:
-                    if ((char)defaultValue == (char)0)
-                    {
-                        ctx.BranchIfFalse(label, false);
-                    }
-                    else
-                    {
-                        ctx.LoadValue((int)(char)defaultValue);
-                        EmitBeq(ctx, label, expected);
-                    }
-                    break;
-                case ProtoTypeCode.Int64:
-                    ctx.LoadValue((long)defaultValue);
-                    EmitBeq(ctx, label, expected);
-                    break;
-                case ProtoTypeCode.UInt64:
-                    ctx.LoadValue((long)(ulong)defaultValue);
-                    EmitBeq(ctx, label, expected);
-                    break;
-                case ProtoTypeCode.Double:
-                    ctx.LoadValue((double)defaultValue);
-                    EmitBeq(ctx, label, expected);
-                    break;
-                case ProtoTypeCode.Single:
-                    ctx.LoadValue((float)defaultValue);
-                    EmitBeq(ctx, label, expected);
-                    break;
-                case ProtoTypeCode.String:
-                    ctx.LoadValue((string)defaultValue);
-                    EmitBeq(ctx, label, expected);
-                    break;
-                case ProtoTypeCode.Decimal:
-                    {
-                        decimal d = (decimal)defaultValue;
-                        ctx.LoadValue(d);
-                        EmitBeq(ctx, label, expected);
-                    }
-                    break;
-                case ProtoTypeCode.TimeSpan:
-                    {
-                        TimeSpan ts = (TimeSpan)defaultValue;
-                        if (ts == TimeSpan.Zero)
-                        {
-                            ctx.LoadValue(typeof(TimeSpan).GetField("Zero"));
-                        }
-                        else
-                        {
-                            ctx.LoadValue(ts.Ticks);
-                            ctx.EmitCall(ctx.MapType(typeof(TimeSpan)).GetMethod("FromTicks"));
-                        }
-                        EmitBeq(ctx, label, expected);
-                        break;
-                    }
-                case ProtoTypeCode.Guid:
-                    {
-                        ctx.LoadValue((Guid)defaultValue);
-                        EmitBeq(ctx, label, expected);
-                        break;
-                    }
-                case ProtoTypeCode.DateTime:
-                    {
-                        ctx.LoadValue(((DateTime)defaultValue).ToBinary());
-                        ctx.EmitCall(ctx.MapType(typeof(DateTime)).GetMethod("FromBinary"));
-
-                        EmitBeq(ctx, label, expected);
-                        break;
-                    }
-                default:
-                    throw new NotSupportedException("Type cannot be represented as a default value: " + expected.FullName);
-            }
-        }
-
-        protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            Tail.EmitRead(ctx, valueFrom);
-        }
-#endif
-    }
-}
-#endif

+ 0 - 42
ThirdParty/protobuf-net/Serializers/DoubleSerializer.cs

@@ -1,42 +0,0 @@
-#if !NO_RUNTIME
-using System;
-
-namespace ProtoBuf.Serializers
-{
-    sealed class DoubleSerializer : IProtoSerializer
-    {
-        static readonly Type expectedType = typeof(double);
-
-        public DoubleSerializer(ProtoBuf.Meta.TypeModel model) { }
-
-        public Type ExpectedType => expectedType;
-
-        bool IProtoSerializer.RequiresOldValue => false;
-
-        bool IProtoSerializer.ReturnsValue => true;
-
-        public object Read(object value, ProtoReader source)
-        {
-            Helpers.DebugAssert(value == null); // since replaces
-            return source.ReadDouble();
-        }
-
-        public void Write(object value, ProtoWriter dest)
-        {
-            ProtoWriter.WriteDouble((double)value, dest);
-        }
-
-#if FEAT_COMPILER
-        void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ctx.EmitBasicWrite("WriteDouble", valueFrom);
-        }
-
-        void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ctx.EmitBasicRead("ReadDouble", ExpectedType);
-        }
-#endif
-    }
-}
-#endif

+ 0 - 267
ThirdParty/protobuf-net/Serializers/EnumSerializer.cs

@@ -1,267 +0,0 @@
-#if !NO_RUNTIME
-using System;
-using ProtoBuf.Meta;
-using System.Reflection;
-
-namespace ProtoBuf.Serializers
-{
-    sealed class EnumSerializer : IProtoSerializer
-    {
-        public readonly struct EnumPair
-        {
-            public readonly object RawValue; // note that this is boxing, but I'll live with it
-            public readonly Enum TypedValue; // note that this is boxing, but I'll live with it
-            public readonly int WireValue;
-            public EnumPair(int wireValue, object raw, Type type)
-            {
-                WireValue = wireValue;
-                RawValue = raw;
-                TypedValue = (Enum)Enum.ToObject(type, raw);
-            }
-        }
-
-        private readonly Type enumType;
-        private readonly EnumPair[] map;
-        public EnumSerializer(Type enumType, EnumPair[] map)
-        {
-            this.enumType = enumType ?? throw new ArgumentNullException(nameof(enumType));
-            this.map = map;
-            if (map != null)
-            {
-                for (int i = 1; i < map.Length; i++)
-                    for (int j = 0; j < i; j++)
-                    {
-                        if (map[i].WireValue == map[j].WireValue && !Equals(map[i].RawValue, map[j].RawValue))
-                        {
-                            throw new ProtoException("Multiple enums with wire-value " + map[i].WireValue.ToString());
-                        }
-                        if (Equals(map[i].RawValue, map[j].RawValue) && map[i].WireValue != map[j].WireValue)
-                        {
-                            throw new ProtoException("Multiple enums with deserialized-value " + map[i].RawValue);
-                        }
-                    }
-
-            }
-        }
-
-        private ProtoTypeCode GetTypeCode()
-        {
-            Type type = Helpers.GetUnderlyingType(enumType);
-            if (type == null) type = enumType;
-            return Helpers.GetTypeCode(type);
-        }
-
-        public Type ExpectedType => enumType;
-
-        bool IProtoSerializer.RequiresOldValue => false;
-
-        bool IProtoSerializer.ReturnsValue => true;
-
-        private int EnumToWire(object value)
-        {
-            unchecked
-            {
-                switch (GetTypeCode())
-                { // unbox then convert to int
-                    case ProtoTypeCode.Byte: return (int)(byte)value;
-                    case ProtoTypeCode.SByte: return (int)(sbyte)value;
-                    case ProtoTypeCode.Int16: return (int)(short)value;
-                    case ProtoTypeCode.Int32: return (int)value;
-                    case ProtoTypeCode.Int64: return (int)(long)value;
-                    case ProtoTypeCode.UInt16: return (int)(ushort)value;
-                    case ProtoTypeCode.UInt32: return (int)(uint)value;
-                    case ProtoTypeCode.UInt64: return (int)(ulong)value;
-                    default: throw new InvalidOperationException();
-                }
-            }
-        }
-
-        private object WireToEnum(int value)
-        {
-            unchecked
-            {
-                switch (GetTypeCode())
-                { // convert from int then box 
-                    case ProtoTypeCode.Byte: return Enum.ToObject(enumType, (byte)value);
-                    case ProtoTypeCode.SByte: return Enum.ToObject(enumType, (sbyte)value);
-                    case ProtoTypeCode.Int16: return Enum.ToObject(enumType, (short)value);
-                    case ProtoTypeCode.Int32: return Enum.ToObject(enumType, value);
-                    case ProtoTypeCode.Int64: return Enum.ToObject(enumType, (long)value);
-                    case ProtoTypeCode.UInt16: return Enum.ToObject(enumType, (ushort)value);
-                    case ProtoTypeCode.UInt32: return Enum.ToObject(enumType, (uint)value);
-                    case ProtoTypeCode.UInt64: return Enum.ToObject(enumType, (ulong)value);
-                    default: throw new InvalidOperationException();
-                }
-            }
-        }
-
-        public object Read(object value, ProtoReader source)
-        {
-            Helpers.DebugAssert(value == null); // since replaces
-            int wireValue = source.ReadInt32();
-            if (map == null)
-            {
-                return WireToEnum(wireValue);
-            }
-            for (int i = 0; i < map.Length; i++)
-            {
-                if (map[i].WireValue == wireValue)
-                {
-                    return map[i].TypedValue;
-                }
-            }
-            source.ThrowEnumException(ExpectedType, wireValue);
-            return null; // to make compiler happy
-        }
-
-        public void Write(object value, ProtoWriter dest)
-        {
-            if (map == null)
-            {
-                ProtoWriter.WriteInt32(EnumToWire(value), dest);
-            }
-            else
-            {
-                for (int i = 0; i < map.Length; i++)
-                {
-                    if (object.Equals(map[i].TypedValue, value))
-                    {
-                        ProtoWriter.WriteInt32(map[i].WireValue, dest);
-                        return;
-                    }
-                }
-                ProtoWriter.ThrowEnumException(dest, value);
-            }
-        }
-
-#if FEAT_COMPILER
-        void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ProtoTypeCode typeCode = GetTypeCode();
-            if (map == null)
-            {
-                ctx.LoadValue(valueFrom);
-                ctx.ConvertToInt32(typeCode, false);
-                ctx.EmitBasicWrite("WriteInt32", null);
-            }
-            else
-            {
-                using (Compiler.Local loc = ctx.GetLocalWithValue(ExpectedType, valueFrom))
-                {
-                    Compiler.CodeLabel @continue = ctx.DefineLabel();
-                    for (int i = 0; i < map.Length; i++)
-                    {
-                        Compiler.CodeLabel tryNextValue = ctx.DefineLabel(), processThisValue = ctx.DefineLabel();
-                        ctx.LoadValue(loc);
-                        WriteEnumValue(ctx, typeCode, map[i].RawValue);
-                        ctx.BranchIfEqual(processThisValue, true);
-                        ctx.Branch(tryNextValue, true);
-                        ctx.MarkLabel(processThisValue);
-                        ctx.LoadValue(map[i].WireValue);
-                        ctx.EmitBasicWrite("WriteInt32", null);
-                        ctx.Branch(@continue, false);
-                        ctx.MarkLabel(tryNextValue);
-                    }
-                    ctx.LoadReaderWriter();
-                    ctx.LoadValue(loc);
-                    ctx.CastToObject(ExpectedType);
-                    ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("ThrowEnumException"));
-                    ctx.MarkLabel(@continue);
-                }
-            }
-        }
-
-        void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ProtoTypeCode typeCode = GetTypeCode();
-            if (map == null)
-            {
-                ctx.EmitBasicRead("ReadInt32", ctx.MapType(typeof(int)));
-                ctx.ConvertFromInt32(typeCode, false);
-            }
-            else
-            {
-                int[] wireValues = new int[map.Length];
-                object[] values = new object[map.Length];
-                for (int i = 0; i < map.Length; i++)
-                {
-                    wireValues[i] = map[i].WireValue;
-                    values[i] = map[i].RawValue;
-                }
-                using (Compiler.Local result = new Compiler.Local(ctx, ExpectedType))
-                using (Compiler.Local wireValue = new Compiler.Local(ctx, ctx.MapType(typeof(int))))
-                {
-                    ctx.EmitBasicRead("ReadInt32", ctx.MapType(typeof(int)));
-                    ctx.StoreValue(wireValue);
-                    Compiler.CodeLabel @continue = ctx.DefineLabel();
-                    foreach (BasicList.Group group in BasicList.GetContiguousGroups(wireValues, values))
-                    {
-                        Compiler.CodeLabel tryNextGroup = ctx.DefineLabel();
-                        int groupItemCount = group.Items.Count;
-                        if (groupItemCount == 1)
-                        {
-                            // discreet group; use an equality test
-                            ctx.LoadValue(wireValue);
-                            ctx.LoadValue(group.First);
-                            Compiler.CodeLabel processThisValue = ctx.DefineLabel();
-                            ctx.BranchIfEqual(processThisValue, true);
-                            ctx.Branch(tryNextGroup, false);
-                            WriteEnumValue(ctx, typeCode, processThisValue, @continue, group.Items[0], @result);
-                        }
-                        else
-                        {
-                            // implement as a jump-table-based switch
-                            ctx.LoadValue(wireValue);
-                            ctx.LoadValue(group.First);
-                            ctx.Subtract(); // jump-tables are zero-based
-                            Compiler.CodeLabel[] jmp = new Compiler.CodeLabel[groupItemCount];
-                            for (int i = 0; i < groupItemCount; i++)
-                            {
-                                jmp[i] = ctx.DefineLabel();
-                            }
-                            ctx.Switch(jmp);
-                            // write the default...
-                            ctx.Branch(tryNextGroup, false);
-                            for (int i = 0; i < groupItemCount; i++)
-                            {
-                                WriteEnumValue(ctx, typeCode, jmp[i], @continue, group.Items[i], @result);
-                            }
-                        }
-                        ctx.MarkLabel(tryNextGroup);
-                    }
-                    // throw source.CreateEnumException(ExpectedType, wireValue);
-                    ctx.LoadReaderWriter();
-                    ctx.LoadValue(ExpectedType);
-                    ctx.LoadValue(wireValue);
-                    ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("ThrowEnumException"));
-                    ctx.MarkLabel(@continue);
-                    ctx.LoadValue(result);
-                }
-            }
-        }
-        private static void WriteEnumValue(Compiler.CompilerContext ctx, ProtoTypeCode typeCode, object value)
-        {
-            switch (typeCode)
-            {
-                case ProtoTypeCode.Byte: ctx.LoadValue((int)(byte)value); break;
-                case ProtoTypeCode.SByte: ctx.LoadValue((int)(sbyte)value); break;
-                case ProtoTypeCode.Int16: ctx.LoadValue((int)(short)value); break;
-                case ProtoTypeCode.Int32: ctx.LoadValue((int)(int)value); break;
-                case ProtoTypeCode.Int64: ctx.LoadValue((long)(long)value); break;
-                case ProtoTypeCode.UInt16: ctx.LoadValue((int)(ushort)value); break;
-                case ProtoTypeCode.UInt32: ctx.LoadValue((int)(uint)value); break;
-                case ProtoTypeCode.UInt64: ctx.LoadValue((long)(ulong)value); break;
-                default: throw new InvalidOperationException();
-            }
-        }
-        private static void WriteEnumValue(Compiler.CompilerContext ctx, ProtoTypeCode typeCode, Compiler.CodeLabel handler, Compiler.CodeLabel @continue, object value, Compiler.Local local)
-        {
-            ctx.MarkLabel(handler);
-            WriteEnumValue(ctx, typeCode, value);
-            ctx.StoreValue(local);
-            ctx.Branch(@continue, false); // "continue"
-        }
-#endif
-    }
-}
-#endif

+ 0 - 104
ThirdParty/protobuf-net/Serializers/FieldDecorator.cs

@@ -1,104 +0,0 @@
-#if !NO_RUNTIME
-using System;
-using System.Reflection;
-
-namespace ProtoBuf.Serializers
-{
-    sealed class FieldDecorator : ProtoDecoratorBase
-    {
-        public override Type ExpectedType => forType;
-        private readonly FieldInfo field;
-        private readonly Type forType;
-        public override bool RequiresOldValue => true;
-        public override bool ReturnsValue => false;
-        public FieldDecorator(Type forType, FieldInfo field, IProtoSerializer tail) : base(tail)
-        {
-            Helpers.DebugAssert(forType != null);
-            Helpers.DebugAssert(field != null);
-            this.forType = forType;
-            this.field = field;
-        }
-
-        public override void Write(object value, ProtoWriter dest)
-        {
-            Helpers.DebugAssert(value != null);
-            value = field.GetValue(value);
-            if (value != null) Tail.Write(value, dest);
-        }
-
-        public override object Read(object value, ProtoReader source)
-        {
-            Helpers.DebugAssert(value != null);
-            object newValue = Tail.Read((Tail.RequiresOldValue ? field.GetValue(value) : null), source);
-            if (newValue != null) field.SetValue(value, newValue);
-            return null;
-        }
-
-
-#if FEAT_COMPILER
-        protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ctx.LoadAddress(valueFrom, ExpectedType);
-            ctx.LoadValue(field);
-            ctx.WriteNullCheckedTail(field.FieldType, Tail, null);
-        }
-        protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            using (Compiler.Local loc = ctx.GetLocalWithValue(ExpectedType, valueFrom))
-            {
-                if (Tail.RequiresOldValue)
-                {
-                    ctx.LoadAddress(loc, ExpectedType);
-                    ctx.LoadValue(field);
-                }
-                // value is either now on the stack or not needed
-                ctx.ReadNullCheckedTail(field.FieldType, Tail, null);
-
-                // the field could be a backing field that needs to be raised back to
-                // the property if we're doing a full compile
-                MemberInfo member = field;
-                ctx.CheckAccessibility(ref member);
-                bool writeValue = member is FieldInfo;
-
-                if (writeValue)
-                {
-                    if (Tail.ReturnsValue)
-                    {
-                        using (Compiler.Local newVal = new Compiler.Local(ctx, field.FieldType))
-                        {
-                            ctx.StoreValue(newVal);
-                            if (Helpers.IsValueType(field.FieldType))
-                            {
-                                ctx.LoadAddress(loc, ExpectedType);
-                                ctx.LoadValue(newVal);
-                                ctx.StoreValue(field);
-                            }
-                            else
-                            {
-                                Compiler.CodeLabel allDone = ctx.DefineLabel();
-                                ctx.LoadValue(newVal);
-                                ctx.BranchIfFalse(allDone, true); // interpret null as "don't assign"
-
-                                ctx.LoadAddress(loc, ExpectedType);
-                                ctx.LoadValue(newVal);
-                                ctx.StoreValue(field);
-
-                                ctx.MarkLabel(allDone);
-                            }
-                        }
-                    }
-                }
-                else
-                {
-                    // can't use result
-                    if (Tail.ReturnsValue)
-                    {
-                        ctx.DiscardValue();
-                    }
-                }
-            }
-        }
-#endif
-    }
-}
-#endif

+ 0 - 43
ThirdParty/protobuf-net/Serializers/GuidSerializer.cs

@@ -1,43 +0,0 @@
-#if !NO_RUNTIME
-using System;
-
-namespace ProtoBuf.Serializers
-{
-    sealed class GuidSerializer : IProtoSerializer
-    {
-        static readonly Type expectedType = typeof(Guid);
-
-        public GuidSerializer(ProtoBuf.Meta.TypeModel model) { }
-
-        public Type ExpectedType { get { return expectedType; } }
-
-        bool IProtoSerializer.RequiresOldValue => false;
-
-        bool IProtoSerializer.ReturnsValue => true;
-
-        public void Write(object value, ProtoWriter dest)
-        {
-            BclHelpers.WriteGuid((Guid)value, dest);
-        }
-
-        public object Read(object value, ProtoReader source)
-        {
-            Helpers.DebugAssert(value == null); // since replaces
-            return BclHelpers.ReadGuid(source);
-        }
-
-#if FEAT_COMPILER
-        void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ctx.EmitWrite(ctx.MapType(typeof(BclHelpers)), "WriteGuid", valueFrom);
-        }
-
-        void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ctx.EmitBasicRead(ctx.MapType(typeof(BclHelpers)), "ReadGuid", ExpectedType);
-        }
-#endif
-
-    }
-}
-#endif

+ 0 - 64
ThirdParty/protobuf-net/Serializers/IProtoSerializer.cs

@@ -1,64 +0,0 @@
-#if !NO_RUNTIME
-using System;
-
-
-namespace ProtoBuf.Serializers
-{
-    interface IProtoSerializer
-    {
-        /// <summary>
-        /// The type that this serializer is intended to work for.
-        /// </summary>
-        Type ExpectedType { get; }
-
-        /// <summary>
-        /// Perform the steps necessary to serialize this data.
-        /// </summary>
-        /// <param name="value">The value to be serialized.</param>
-        /// <param name="dest">The writer entity that is accumulating the output data.</param>
-        void Write(object value, ProtoWriter dest);
-
-        /// <summary>
-        /// Perform the steps necessary to deserialize this data.
-        /// </summary>
-        /// <param name="value">The current value, if appropriate.</param>
-        /// <param name="source">The reader providing the input data.</param>
-        /// <returns>The updated / replacement value.</returns>
-        object Read(object value, ProtoReader source);
-
-        /// <summary>
-        /// Indicates whether a Read operation <em>replaces</em> the existing value, or
-        /// <em>extends</em> the value. If false, the "value" parameter to Read is
-        /// discarded, and should be passed in as null.
-        /// </summary>
-        bool RequiresOldValue { get; }
-        /// <summary>
-        /// Now all Read operations return a value (although most do); if false no
-        /// value should be expected.
-        /// </summary>
-        bool ReturnsValue { get; }
-
-#if FEAT_COMPILER
-        /// <summary>Emit the IL necessary to perform the given actions
-        /// to serialize this data.
-        /// </summary>
-        /// <param name="ctx">Details and utilities for the method being generated.</param>
-        /// <param name="valueFrom">The source of the data to work against;
-        /// If the value is only needed once, then LoadValue is sufficient. If
-        /// the value is needed multiple times, then note that a "null"
-        /// means "the top of the stack", in which case you should create your
-        /// own copy - GetLocalWithValue.</param>
-        void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom);
-
-        /// <summary>
-        /// Emit the IL necessary to perform the given actions to deserialize this data.
-        /// </summary>
-        /// <param name="ctx">Details and utilities for the method being generated.</param>
-        /// <param name="entity">For nested values, the instance holding the values; note
-        /// that this is not always provided - a null means not supplied. Since this is always
-        /// a variable or argument, it is not necessary to consume this value.</param>
-        void EmitRead(Compiler.CompilerContext ctx, Compiler.Local entity);
-#endif
-    }
-}
-#endif

+ 0 - 20
ThirdParty/protobuf-net/Serializers/IProtoTypeSerializer.cs

@@ -1,20 +0,0 @@
-#if !NO_RUNTIME
-using ProtoBuf.Meta;
-namespace ProtoBuf.Serializers
-{
-    interface IProtoTypeSerializer : IProtoSerializer
-    {
-        bool HasCallbacks(TypeModel.CallbackType callbackType);
-        bool CanCreateInstance();
-        object CreateInstance(ProtoReader source);
-        void Callback(object value, TypeModel.CallbackType callbackType, SerializationContext context);
-
-#if FEAT_COMPILER
-        void EmitCallback(Compiler.CompilerContext ctx, Compiler.Local valueFrom, TypeModel.CallbackType callbackType);
-#endif
-#if FEAT_COMPILER
-        void EmitCreateInstance(Compiler.CompilerContext ctx);
-#endif
-    }
-}
-#endif

+ 0 - 10
ThirdParty/protobuf-net/Serializers/ISerializerProxy.cs

@@ -1,10 +0,0 @@
-#if !NO_RUNTIME
-
-namespace ProtoBuf.Serializers
-{
-    interface ISerializerProxy
-    {
-        IProtoSerializer Serializer { get; }
-    }
-}
-#endif

+ 0 - 304
ThirdParty/protobuf-net/Serializers/ImmutableCollectionDecorator.cs

@@ -1,304 +0,0 @@
-#if !NO_RUNTIME
-using System;
-using System.Collections;
-using System.Reflection;
-using ProtoBuf.Meta;
-
-namespace ProtoBuf.Serializers
-{
-    sealed class ImmutableCollectionDecorator : ListDecorator
-    {
-        protected override bool RequireAdd { get { return false; } }
-
-        static Type ResolveIReadOnlyCollection(Type declaredType, Type t)
-        {
-#if COREFX || PROFILE259
-            if (CheckIsIReadOnlyCollectionExactly(declaredType.GetTypeInfo())) return declaredType;
-			foreach (Type intImplBasic in declaredType.GetTypeInfo().ImplementedInterfaces)
-            {
-                TypeInfo intImpl = intImplBasic.GetTypeInfo();
-                if (CheckIsIReadOnlyCollectionExactly(intImpl)) return intImplBasic;
-            }
-#else
-            if (CheckIsIReadOnlyCollectionExactly(declaredType)) return declaredType;
-            foreach (Type intImpl in declaredType.GetInterfaces())
-            {
-                if (CheckIsIReadOnlyCollectionExactly(intImpl)) return intImpl;
-            }
-#endif
-            return null;
-        }
-
-#if WINRT || COREFX || PROFILE259
-        static bool CheckIsIReadOnlyCollectionExactly(TypeInfo t)
-#else
-        static bool CheckIsIReadOnlyCollectionExactly(Type t)
-#endif
-        {
-            if (t != null && t.IsGenericType && t.Name.StartsWith("IReadOnlyCollection`"))
-            {
-#if WINRT || COREFX || PROFILE259
-                Type[] typeArgs = t.GenericTypeArguments;
-                if (typeArgs.Length != 1 && typeArgs[0].GetTypeInfo().Equals(t)) return false;
-#else
-                Type[] typeArgs = t.GetGenericArguments();
-                if (typeArgs.Length != 1 && typeArgs[0] != t) return false;
-#endif
-                    
-                return true;
-            }
-            return false;
-        }
-
-        internal static bool IdentifyImmutable(TypeModel model, Type declaredType, out MethodInfo builderFactory, out PropertyInfo isEmpty, out PropertyInfo length, out MethodInfo add, out MethodInfo addRange, out MethodInfo finish)
-        {
-            builderFactory = add = addRange = finish = null;
-            isEmpty = length = null;
-            if (model == null || declaredType == null) return false;
-#if COREFX || PROFILE259
-			TypeInfo declaredTypeInfo = declaredType.GetTypeInfo();
-#else
-            Type declaredTypeInfo = declaredType;
-#endif
-
-            // try to detect immutable collections; firstly, they are all generic, and all implement IReadOnlyCollection<T> for some T
-            if (!declaredTypeInfo.IsGenericType) return false;
-
-#if COREFX || PROFILE259
-			Type[] typeArgs = declaredTypeInfo.GenericTypeArguments, effectiveType;
-#else
-            Type[] typeArgs = declaredTypeInfo.GetGenericArguments(), effectiveType;
-#endif
-            switch (typeArgs.Length)
-            {
-                case 1:
-                    effectiveType = typeArgs;
-                    break; // fine
-                case 2:
-                    Type kvp = model.MapType(typeof(System.Collections.Generic.KeyValuePair<,>));
-                    if (kvp == null) return false;
-                    kvp = kvp.MakeGenericType(typeArgs);
-                    effectiveType = new Type[] { kvp };
-                    break;
-                default:
-                    return false; // no clue!
-            }
-
-            if (ResolveIReadOnlyCollection(declaredType, null) == null) return false; // no IReadOnlyCollection<T> found
-
-            // and we want to use the builder API, so for generic Foo<T> or IFoo<T> we want to use Foo.CreateBuilder<T>
-            string name = declaredType.Name;
-            int i = name.IndexOf('`');
-            if (i <= 0) return false;
-            name = declaredTypeInfo.IsInterface ? name.Substring(1, i - 1) : name.Substring(0, i);
-
-            Type outerType = model.GetType(declaredType.Namespace + "." + name, declaredTypeInfo.Assembly);
-            // I hate special-cases...
-            if (outerType == null && name == "ImmutableSet")
-            {
-                outerType = model.GetType(declaredType.Namespace + ".ImmutableHashSet", declaredTypeInfo.Assembly);
-            }
-            if (outerType == null) return false;
-
-#if PROFILE259
-			foreach (MethodInfo method in outerType.GetTypeInfo().DeclaredMethods)
-#else
-            foreach (MethodInfo method in outerType.GetMethods())
-#endif
-            {
-                if (!method.IsStatic || method.Name != "CreateBuilder" || !method.IsGenericMethodDefinition || method.GetParameters().Length != 0
-                    || method.GetGenericArguments().Length != typeArgs.Length) continue;
-
-                builderFactory = method.MakeGenericMethod(typeArgs);
-                break;
-            }
-            Type voidType = model.MapType(typeof(void));
-            if (builderFactory == null || builderFactory.ReturnType == null || builderFactory.ReturnType == voidType) return false;
-
-#if COREFX
-            TypeInfo typeInfo = declaredType.GetTypeInfo();
-#else
-            Type typeInfo = declaredType;
-#endif
-            isEmpty = Helpers.GetProperty(typeInfo, "IsDefaultOrEmpty", false); //struct based immutabletypes can have both a "default" and "empty" state
-            if (isEmpty == null) isEmpty = Helpers.GetProperty(typeInfo, "IsEmpty", false);
-            if (isEmpty == null)
-            {
-                //Fallback to checking length if a "IsEmpty" property is not found
-                length = Helpers.GetProperty(typeInfo, "Length", false);
-                if (length == null) length = Helpers.GetProperty(typeInfo, "Count", false);
-
-                if (length == null) length = Helpers.GetProperty(ResolveIReadOnlyCollection(declaredType, effectiveType[0]), "Count", false);
-
-                if (length == null) return false;
-            }
-
-            add = Helpers.GetInstanceMethod(builderFactory.ReturnType, "Add", effectiveType);
-            if (add == null) return false;
-
-            finish = Helpers.GetInstanceMethod(builderFactory.ReturnType, "ToImmutable", Helpers.EmptyTypes);
-            if (finish == null || finish.ReturnType == null || finish.ReturnType == voidType) return false;
-
-            if (!(finish.ReturnType == declaredType || Helpers.IsAssignableFrom(declaredType, finish.ReturnType))) return false;
-
-            addRange = Helpers.GetInstanceMethod(builderFactory.ReturnType, "AddRange", new Type[] { declaredType });
-            if (addRange == null)
-            {
-                Type enumerable = model.MapType(typeof(System.Collections.Generic.IEnumerable<>), false);
-                if (enumerable != null)
-                {
-                    addRange = Helpers.GetInstanceMethod(builderFactory.ReturnType, "AddRange", new Type[] { enumerable.MakeGenericType(effectiveType) });
-                }
-            }
-
-            return true;
-        }
-
-        private readonly MethodInfo builderFactory, add, addRange, finish;
-        private readonly PropertyInfo isEmpty, length;
-        internal ImmutableCollectionDecorator(TypeModel model, Type declaredType, Type concreteType, IProtoSerializer tail, int fieldNumber, bool writePacked, WireType packedWireType, bool returnList, bool overwriteList, bool supportNull,
-            MethodInfo builderFactory, PropertyInfo isEmpty, PropertyInfo length, MethodInfo add, MethodInfo addRange, MethodInfo finish)
-            : base(model, declaredType, concreteType, tail, fieldNumber, writePacked, packedWireType, returnList, overwriteList, supportNull)
-        {
-            this.builderFactory = builderFactory;
-            this.isEmpty = isEmpty;
-            this.length = length;
-            this.add = add;
-            this.addRange = addRange;
-            this.finish = finish;
-        }
-
-        public override object Read(object value, ProtoReader source)
-        {
-            object builderInstance = builderFactory.Invoke(null, null);
-            int field = source.FieldNumber;
-            object[] args = new object[1];
-            if (AppendToCollection && value != null && (isEmpty != null ? !(bool)isEmpty.GetValue(value, null) : (int)length.GetValue(value, null) != 0))
-            {
-                if (addRange != null)
-                {
-                    args[0] = value;
-                    addRange.Invoke(builderInstance, args);
-                }
-                else
-                {
-                    foreach (object item in (ICollection)value)
-                    {
-                        args[0] = item;
-                        add.Invoke(builderInstance, args);
-                    }
-                }
-            }
-
-            if (packedWireType != WireType.None && source.WireType == WireType.String)
-            {
-                SubItemToken token = ProtoReader.StartSubItem(source);
-                while (ProtoReader.HasSubValue(packedWireType, source))
-                {
-                    args[0] = Tail.Read(null, source);
-                    add.Invoke(builderInstance, args);
-                }
-                ProtoReader.EndSubItem(token, source);
-            }
-            else
-            {
-                do
-                {
-                    args[0] = Tail.Read(null, source);
-                    add.Invoke(builderInstance, args);
-                } while (source.TryReadFieldHeader(field));
-            }
-
-            return finish.Invoke(builderInstance, null);
-        }
-
-#if FEAT_COMPILER
-        protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            using (Compiler.Local oldList = AppendToCollection ? ctx.GetLocalWithValue(ExpectedType, valueFrom) : null)
-            using (Compiler.Local builder = new Compiler.Local(ctx, builderFactory.ReturnType))
-            {
-                ctx.EmitCall(builderFactory);
-                ctx.StoreValue(builder);
-
-                if (AppendToCollection)
-                {
-                    Compiler.CodeLabel done = ctx.DefineLabel();
-                    if (!Helpers.IsValueType(ExpectedType))
-                    {
-                        ctx.LoadValue(oldList);
-                        ctx.BranchIfFalse(done, false); // old value null; nothing to add
-                    }
-
-                    ctx.LoadAddress(oldList, oldList.Type);
-                    if (isEmpty != null)
-                    {
-                        ctx.EmitCall(Helpers.GetGetMethod(isEmpty, false, false));
-                        ctx.BranchIfTrue(done, false); // old list is empty; nothing to add
-                    }
-                    else
-                    {
-                        ctx.EmitCall(Helpers.GetGetMethod(length, false, false));
-                        ctx.BranchIfFalse(done, false); // old list is empty; nothing to add
-                    }
-
-                    Type voidType = ctx.MapType(typeof(void));
-                    if (addRange != null)
-                    {
-                        ctx.LoadValue(builder);
-                        ctx.LoadValue(oldList);
-                        ctx.EmitCall(addRange);
-                        if (addRange.ReturnType != null && add.ReturnType != voidType) ctx.DiscardValue();
-                    }
-                    else
-                    {
-                        // loop and call Add repeatedly
-                        MethodInfo moveNext, current, getEnumerator = GetEnumeratorInfo(ctx.Model, out moveNext, out current);
-                        Helpers.DebugAssert(moveNext != null);
-                        Helpers.DebugAssert(current != null);
-                        Helpers.DebugAssert(getEnumerator != null);
-
-                        Type enumeratorType = getEnumerator.ReturnType;
-                        using (Compiler.Local iter = new Compiler.Local(ctx, enumeratorType))
-                        {
-                            ctx.LoadAddress(oldList, ExpectedType);
-                            ctx.EmitCall(getEnumerator);
-                            ctx.StoreValue(iter);
-                            using (ctx.Using(iter))
-                            {
-                                Compiler.CodeLabel body = ctx.DefineLabel(), next = ctx.DefineLabel();
-                                ctx.Branch(next, false);
-
-                                ctx.MarkLabel(body);
-                                ctx.LoadAddress(builder, builder.Type);
-                                ctx.LoadAddress(iter, enumeratorType);
-                                ctx.EmitCall(current);
-                                ctx.EmitCall(add);
-                                if (add.ReturnType != null && add.ReturnType != voidType) ctx.DiscardValue();
-
-                                ctx.MarkLabel(@next);
-                                ctx.LoadAddress(iter, enumeratorType);
-                                ctx.EmitCall(moveNext);
-                                ctx.BranchIfTrue(body, false);
-                            }
-                        }
-                    }
-
-
-                    ctx.MarkLabel(done);
-                }
-
-                EmitReadList(ctx, builder, Tail, add, packedWireType, false);
-
-                ctx.LoadAddress(builder, builder.Type);
-                ctx.EmitCall(finish);
-                if (ExpectedType != finish.ReturnType)
-                {
-                    ctx.Cast(ExpectedType);
-                }
-            }
-        }
-#endif
-    }
-}
-#endif

+ 0 - 42
ThirdParty/protobuf-net/Serializers/Int16Serializer.cs

@@ -1,42 +0,0 @@
-#if !NO_RUNTIME
-using System;
-
-namespace ProtoBuf.Serializers
-{
-    sealed class Int16Serializer : IProtoSerializer
-    {
-        static readonly Type expectedType = typeof(short);
-
-        public Int16Serializer(ProtoBuf.Meta.TypeModel model) { }
-
-        public Type ExpectedType => expectedType;
-
-        bool IProtoSerializer.RequiresOldValue => false;
-
-        bool IProtoSerializer.ReturnsValue => true;
-
-        public object Read(object value, ProtoReader source)
-        {
-            Helpers.DebugAssert(value == null); // since replaces
-            return source.ReadInt16();
-        }
-
-        public void Write(object value, ProtoWriter dest)
-        {
-            ProtoWriter.WriteInt16((short)value, dest);
-        }
-
-#if FEAT_COMPILER
-        void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ctx.EmitBasicWrite("WriteInt16", valueFrom);
-        }
-        void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ctx.EmitBasicRead("ReadInt16", ExpectedType);
-        }
-#endif
-
-    }
-}
-#endif

+ 0 - 42
ThirdParty/protobuf-net/Serializers/Int32Serializer.cs

@@ -1,42 +0,0 @@
-#if !NO_RUNTIME
-using System;
-
-namespace ProtoBuf.Serializers
-{
-    sealed class Int32Serializer : IProtoSerializer
-    {
-        static readonly Type expectedType = typeof(int);
-
-        public Int32Serializer(ProtoBuf.Meta.TypeModel model) { }
-
-        public Type ExpectedType => expectedType;
-
-        bool IProtoSerializer.RequiresOldValue => false;
-
-        bool IProtoSerializer.ReturnsValue => true;
-
-        public object Read(object value, ProtoReader source)
-        {
-            Helpers.DebugAssert(value == null); // since replaces
-            return source.ReadInt32();
-        }
-
-        public void Write(object value, ProtoWriter dest)
-        {
-            ProtoWriter.WriteInt32((int)value, dest);
-        }
-
-#if FEAT_COMPILER
-        void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ctx.EmitBasicWrite("WriteInt32", valueFrom);
-        }
-        void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ctx.EmitBasicRead("ReadInt32", ExpectedType);
-        }
-#endif
-
-    }
-}
-#endif

+ 0 - 41
ThirdParty/protobuf-net/Serializers/Int64Serializer.cs

@@ -1,41 +0,0 @@
-#if !NO_RUNTIME
-using System;
-
-namespace ProtoBuf.Serializers
-{
-    sealed class Int64Serializer : IProtoSerializer
-    {
-        static readonly Type expectedType = typeof(long);
-
-        public Int64Serializer(ProtoBuf.Meta.TypeModel model) { }
-
-        public Type ExpectedType => expectedType;
-
-        bool IProtoSerializer.RequiresOldValue => false;
-
-        bool IProtoSerializer.ReturnsValue => true;
-
-        public object Read(object value, ProtoReader source)
-        {
-            Helpers.DebugAssert(value == null); // since replaces
-            return source.ReadInt64();
-        }
-
-        public void Write(object value, ProtoWriter dest)
-        {
-            ProtoWriter.WriteInt64((long)value, dest);
-        }
-
-#if FEAT_COMPILER
-        void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ctx.EmitBasicWrite("WriteInt64", valueFrom);
-        }
-        void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ctx.EmitBasicRead("ReadInt64", ExpectedType);
-        }
-#endif
-    }
-}
-#endif

+ 0 - 579
ThirdParty/protobuf-net/Serializers/ListDecorator.cs

@@ -1,579 +0,0 @@
-#if !NO_RUNTIME
-using System;
-using System.Collections;
-using ProtoBuf.Meta;
-using System.Reflection;
-
-namespace ProtoBuf.Serializers
-{
-    class ListDecorator : ProtoDecoratorBase
-    {
-        internal static bool CanPack(WireType wireType)
-        {
-            switch (wireType)
-            {
-                case WireType.Fixed32:
-                case WireType.Fixed64:
-                case WireType.SignedVariant:
-                case WireType.Variant:
-                    return true;
-                default:
-                    return false;
-            }
-        }
-
-        private readonly byte options;
-
-        private const byte OPTIONS_IsList = 1,
-                           OPTIONS_SuppressIList = 2,
-                           OPTIONS_WritePacked = 4,
-                           OPTIONS_ReturnList = 8,
-                           OPTIONS_OverwriteList = 16,
-                           OPTIONS_SupportNull = 32;
-
-        private readonly Type declaredType, concreteType;
-
-        private readonly MethodInfo add;
-
-        private readonly int fieldNumber;
-
-        private bool IsList { get { return (options & OPTIONS_IsList) != 0; } }
-        private bool SuppressIList { get { return (options & OPTIONS_SuppressIList) != 0; } }
-        private bool WritePacked { get { return (options & OPTIONS_WritePacked) != 0; } }
-        private bool SupportNull { get { return (options & OPTIONS_SupportNull) != 0; } }
-        private bool ReturnList { get { return (options & OPTIONS_ReturnList) != 0; } }
-        protected readonly WireType packedWireType;
-
-        internal static ListDecorator Create(TypeModel model, Type declaredType, Type concreteType, IProtoSerializer tail, int fieldNumber, bool writePacked, WireType packedWireType, bool returnList, bool overwriteList, bool supportNull)
-        {
-            if (returnList && ImmutableCollectionDecorator.IdentifyImmutable(model, declaredType,
-                out MethodInfo builderFactory,
-                out PropertyInfo isEmpty,
-                out PropertyInfo length,
-                out MethodInfo add,
-                out MethodInfo addRange,
-                out MethodInfo finish))
-            {
-                return new ImmutableCollectionDecorator(
-                    model, declaredType, concreteType, tail, fieldNumber, writePacked, packedWireType, returnList, overwriteList, supportNull,
-                    builderFactory, isEmpty, length, add, addRange, finish);
-            }
-
-            return new ListDecorator(model, declaredType, concreteType, tail, fieldNumber, writePacked, packedWireType, returnList, overwriteList, supportNull);
-        }
-
-        protected ListDecorator(TypeModel model, Type declaredType, Type concreteType, IProtoSerializer tail, int fieldNumber, bool writePacked, WireType packedWireType, bool returnList, bool overwriteList, bool supportNull)
-            : base(tail)
-        {
-            if (returnList) options |= OPTIONS_ReturnList;
-            if (overwriteList) options |= OPTIONS_OverwriteList;
-            if (supportNull) options |= OPTIONS_SupportNull;
-            if ((writePacked || packedWireType != WireType.None) && fieldNumber <= 0) throw new ArgumentOutOfRangeException("fieldNumber");
-            if (!CanPack(packedWireType))
-            {
-                if (writePacked) throw new InvalidOperationException("Only simple data-types can use packed encoding");
-                packedWireType = WireType.None;
-            }
-
-            this.fieldNumber = fieldNumber;
-            if (writePacked) options |= OPTIONS_WritePacked;
-            this.packedWireType = packedWireType;
-            if (declaredType == null) throw new ArgumentNullException("declaredType");
-            if (declaredType.IsArray) throw new ArgumentException("Cannot treat arrays as lists", "declaredType");
-            this.declaredType = declaredType;
-            this.concreteType = concreteType;
-
-            // look for a public list.Add(typedObject) method
-            if (RequireAdd)
-            {
-                bool isList;
-                add = TypeModel.ResolveListAdd(model, declaredType, tail.ExpectedType, out isList);
-                if (isList)
-                {
-                    options |= OPTIONS_IsList;
-                    string fullName = declaredType.FullName;
-                    if (fullName != null && fullName.StartsWith("System.Data.Linq.EntitySet`1[["))
-                    { // see http://stackoverflow.com/questions/6194639/entityset-is-there-a-sane-reason-that-ilist-add-doesnt-set-assigned
-                        options |= OPTIONS_SuppressIList;
-                    }
-                }
-                if (add == null) throw new InvalidOperationException("Unable to resolve a suitable Add method for " + declaredType.FullName);
-            }
-
-        }
-        protected virtual bool RequireAdd => true;
-
-        public override Type ExpectedType => declaredType;
-
-        public override bool RequiresOldValue => AppendToCollection;
-
-        public override bool ReturnsValue => ReturnList;
-
-        protected bool AppendToCollection
-        {
-            get { return (options & OPTIONS_OverwriteList) == 0; }
-        }
-
-#if FEAT_COMPILER
-        protected override void EmitRead(ProtoBuf.Compiler.CompilerContext ctx, ProtoBuf.Compiler.Local valueFrom)
-        {
-            /* This looks more complex than it is. Look at the non-compiled Read to
-             * see what it is trying to do, but note that it needs to cope with a
-             * few more scenarios. Note that it picks the **most specific** Add,
-             * unlike the runtime version that uses IList when possible. The core
-             * is just a "do {list.Add(readValue())} while {thereIsMore}"
-             * 
-             * The complexity is due to:
-             *  - value types vs reference types (boxing etc)
-             *  - initialization if we need to pass in a value to the tail
-             *  - handling whether or not the tail *returns* the value vs updates the input
-             */
-            bool returnList = ReturnList;
-
-            using (Compiler.Local list = AppendToCollection ? ctx.GetLocalWithValue(ExpectedType, valueFrom) : new Compiler.Local(ctx, declaredType))
-            using (Compiler.Local origlist = (returnList && AppendToCollection && !Helpers.IsValueType(ExpectedType)) ? new Compiler.Local(ctx, ExpectedType) : null)
-            {
-                if (!AppendToCollection)
-                { // always new
-                    ctx.LoadNullRef();
-                    ctx.StoreValue(list);
-                }
-                else if (returnList && origlist != null)
-                { // need a copy
-                    ctx.LoadValue(list);
-                    ctx.StoreValue(origlist);
-                }
-                if (concreteType != null)
-                {
-                    ctx.LoadValue(list);
-                    Compiler.CodeLabel notNull = ctx.DefineLabel();
-                    ctx.BranchIfTrue(notNull, true);
-                    ctx.EmitCtor(concreteType);
-                    ctx.StoreValue(list);
-                    ctx.MarkLabel(notNull);
-                }
-
-                bool castListForAdd = !add.DeclaringType.IsAssignableFrom(declaredType);
-                EmitReadList(ctx, list, Tail, add, packedWireType, castListForAdd);
-
-                if (returnList)
-                {
-                    if (AppendToCollection && origlist != null)
-                    {
-                        // remember ^^^^ we had a spare copy of the list on the stack; now we'll compare
-                        ctx.LoadValue(origlist);
-                        ctx.LoadValue(list); // [orig] [new-value]
-                        Compiler.CodeLabel sameList = ctx.DefineLabel(), allDone = ctx.DefineLabel();
-                        ctx.BranchIfEqual(sameList, true);
-                        ctx.LoadValue(list);
-                        ctx.Branch(allDone, true);
-                        ctx.MarkLabel(sameList);
-                        ctx.LoadNullRef();
-                        ctx.MarkLabel(allDone);
-                    }
-                    else
-                    {
-                        ctx.LoadValue(list);
-                    }
-                }
-            }
-        }
-
-        internal static void EmitReadList(ProtoBuf.Compiler.CompilerContext ctx, Compiler.Local list, IProtoSerializer tail, MethodInfo add, WireType packedWireType, bool castListForAdd)
-        {
-            using (Compiler.Local fieldNumber = new Compiler.Local(ctx, ctx.MapType(typeof(int))))
-            {
-                Compiler.CodeLabel readPacked = packedWireType == WireType.None ? new Compiler.CodeLabel() : ctx.DefineLabel();
-                if (packedWireType != WireType.None)
-                {
-                    ctx.LoadReaderWriter();
-                    ctx.LoadValue(typeof(ProtoReader).GetProperty("WireType"));
-                    ctx.LoadValue((int)WireType.String);
-                    ctx.BranchIfEqual(readPacked, false);
-                }
-                ctx.LoadReaderWriter();
-                ctx.LoadValue(typeof(ProtoReader).GetProperty("FieldNumber"));
-                ctx.StoreValue(fieldNumber);
-
-                Compiler.CodeLabel @continue = ctx.DefineLabel();
-                ctx.MarkLabel(@continue);
-
-                EmitReadAndAddItem(ctx, list, tail, add, castListForAdd);
-
-                ctx.LoadReaderWriter();
-                ctx.LoadValue(fieldNumber);
-                ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("TryReadFieldHeader"));
-                ctx.BranchIfTrue(@continue, false);
-
-                if (packedWireType != WireType.None)
-                {
-                    Compiler.CodeLabel allDone = ctx.DefineLabel();
-                    ctx.Branch(allDone, false);
-                    ctx.MarkLabel(readPacked);
-
-                    ctx.LoadReaderWriter();
-                    ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("StartSubItem"));
-
-                    Compiler.CodeLabel testForData = ctx.DefineLabel(), noMoreData = ctx.DefineLabel();
-                    ctx.MarkLabel(testForData);
-                    ctx.LoadValue((int)packedWireType);
-                    ctx.LoadReaderWriter();
-                    ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("HasSubValue"));
-                    ctx.BranchIfFalse(noMoreData, false);
-
-                    EmitReadAndAddItem(ctx, list, tail, add, castListForAdd);
-                    ctx.Branch(testForData, false);
-
-                    ctx.MarkLabel(noMoreData);
-                    ctx.LoadReaderWriter();
-                    ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("EndSubItem"));
-                    ctx.MarkLabel(allDone);
-                }
-            }
-        }
-
-        private static void EmitReadAndAddItem(Compiler.CompilerContext ctx, Compiler.Local list, IProtoSerializer tail, MethodInfo add, bool castListForAdd)
-        {
-            ctx.LoadAddress(list, list.Type); // needs to be the reference in case the list is value-type (static-call)
-            if (castListForAdd) ctx.Cast(add.DeclaringType);
-
-            Type itemType = tail.ExpectedType;
-            bool tailReturnsValue = tail.ReturnsValue;
-            if (tail.RequiresOldValue)
-            {
-                if (Helpers.IsValueType(itemType) || !tailReturnsValue)
-                {
-                    // going to need a variable
-                    using (Compiler.Local item = new Compiler.Local(ctx, itemType))
-                    {
-                        if (Helpers.IsValueType(itemType))
-                        {   // initialise the struct
-                            ctx.LoadAddress(item, itemType);
-                            ctx.EmitCtor(itemType);
-                        }
-                        else
-                        {   // assign null
-                            ctx.LoadNullRef();
-                            ctx.StoreValue(item);
-                        }
-                        tail.EmitRead(ctx, item);
-                        if (!tailReturnsValue) { ctx.LoadValue(item); }
-                    }
-                }
-                else
-                {    // no variable; pass the null on the stack and take the value *off* the stack
-                    ctx.LoadNullRef();
-                    tail.EmitRead(ctx, null);
-                }
-            }
-            else
-            {
-                if (tailReturnsValue)
-                {   // out only (on the stack); just emit it
-                    tail.EmitRead(ctx, null);
-                }
-                else
-                {   // doesn't take anything in nor return anything! WTF?
-                    throw new InvalidOperationException();
-                }
-            }
-            // our "Add" is chosen either to take the correct type, or to take "object";
-            // we may need to box the value
-
-            Type addParamType = add.GetParameters()[0].ParameterType;
-            if (addParamType != itemType)
-            {
-                if (addParamType == ctx.MapType(typeof(object)))
-                {
-                    ctx.CastToObject(itemType);
-                }
-                else if (Helpers.GetUnderlyingType(addParamType) == itemType)
-                { // list is nullable
-                    ConstructorInfo ctor = Helpers.GetConstructor(addParamType, new Type[] { itemType }, false);
-                    ctx.EmitCtor(ctor); // the itemType on the stack is now a Nullable<ItemType>
-                }
-                else
-                {
-                    throw new InvalidOperationException("Conflicting item/add type");
-                }
-            }
-            ctx.EmitCall(add, list.Type);
-            if (add.ReturnType != ctx.MapType(typeof(void)))
-            {
-                ctx.DiscardValue();
-            }
-        }
-#endif
-
-#if COREFX
-        private static readonly TypeInfo ienumeratorType = typeof(IEnumerator).GetTypeInfo(), ienumerableType = typeof (IEnumerable).GetTypeInfo();
-#else
-        private static readonly System.Type ienumeratorType = typeof(IEnumerator), ienumerableType = typeof(IEnumerable);
-#endif
-        protected MethodInfo GetEnumeratorInfo(TypeModel model, out MethodInfo moveNext, out MethodInfo current)
-            => GetEnumeratorInfo(model, ExpectedType, Tail.ExpectedType, out moveNext, out current);
-        internal static MethodInfo GetEnumeratorInfo(TypeModel model, Type expectedType, Type itemType, out MethodInfo moveNext, out MethodInfo current)
-        {
-
-#if COREFX
-            TypeInfo enumeratorType = null, iteratorType;
-#else
-            Type enumeratorType = null, iteratorType;
-#endif
-
-            // try a custom enumerator
-            MethodInfo getEnumerator = Helpers.GetInstanceMethod(expectedType, "GetEnumerator", null);
-
-            Type getReturnType = null;
-            if (getEnumerator != null)
-            {
-                getReturnType = getEnumerator.ReturnType;
-                iteratorType = getReturnType
-#if COREFX || COREFX
-                    .GetTypeInfo()
-#endif
-                    ;
-                moveNext = Helpers.GetInstanceMethod(iteratorType, "MoveNext", null);
-                PropertyInfo prop = Helpers.GetProperty(iteratorType, "Current", false);
-                current = prop == null ? null : Helpers.GetGetMethod(prop, false, false);
-#if PROFILE259
-				if (moveNext == null && (model.MapType(ienumeratorType).GetTypeInfo().IsAssignableFrom(iteratorType.GetTypeInfo())))
-#else
-                if (moveNext == null && (model.MapType(ienumeratorType).IsAssignableFrom(iteratorType)))
-#endif
-                {
-                    moveNext = Helpers.GetInstanceMethod(model.MapType(ienumeratorType), "MoveNext", null);
-                }
-                // fully typed
-                if (moveNext != null && moveNext.ReturnType == model.MapType(typeof(bool))
-                    && current != null && current.ReturnType == itemType)
-                {
-                    return getEnumerator;
-                }
-                moveNext = current = getEnumerator = null;
-            }
-
-            // try IEnumerable<T>
-            Type tmp = model.MapType(typeof(System.Collections.Generic.IEnumerable<>), false);
-
-            if (tmp != null)
-            {
-                tmp = tmp.MakeGenericType(itemType);
-
-#if COREFX
-                enumeratorType = tmp.GetTypeInfo();
-#else
-                enumeratorType = tmp;
-#endif
-            }
-;
-#if PROFILE259
-			if (enumeratorType != null && enumeratorType.GetTypeInfo().IsAssignableFrom(expectedType
-#else
-            if (enumeratorType != null && enumeratorType.IsAssignableFrom(expectedType
-#endif
-#if COREFX || PROFILE259
-                .GetTypeInfo()
-#endif
-                ))
-            {
-                getEnumerator = Helpers.GetInstanceMethod(enumeratorType, "GetEnumerator");
-                getReturnType = getEnumerator.ReturnType;
-
-#if COREFX
-                iteratorType = getReturnType.GetTypeInfo();
-#else
-                iteratorType = getReturnType;
-#endif
-
-                moveNext = Helpers.GetInstanceMethod(model.MapType(ienumeratorType), "MoveNext");
-                current = Helpers.GetGetMethod(Helpers.GetProperty(iteratorType, "Current", false), false, false);
-                return getEnumerator;
-            }
-            // give up and fall-back to non-generic IEnumerable
-            enumeratorType = model.MapType(ienumerableType);
-            getEnumerator = Helpers.GetInstanceMethod(enumeratorType, "GetEnumerator");
-            getReturnType = getEnumerator.ReturnType;
-            iteratorType = getReturnType
-#if COREFX
-                .GetTypeInfo()
-#endif
-                ;
-            moveNext = Helpers.GetInstanceMethod(iteratorType, "MoveNext");
-            current = Helpers.GetGetMethod(Helpers.GetProperty(iteratorType, "Current", false), false, false);
-            return getEnumerator;
-        }
-#if FEAT_COMPILER
-        protected override void EmitWrite(ProtoBuf.Compiler.CompilerContext ctx, ProtoBuf.Compiler.Local valueFrom)
-        {
-            using (Compiler.Local list = ctx.GetLocalWithValue(ExpectedType, valueFrom))
-            {
-                MethodInfo getEnumerator = GetEnumeratorInfo(ctx.Model, out MethodInfo moveNext, out MethodInfo current);
-                Helpers.DebugAssert(moveNext != null);
-                Helpers.DebugAssert(current != null);
-                Helpers.DebugAssert(getEnumerator != null);
-                Type enumeratorType = getEnumerator.ReturnType;
-                bool writePacked = WritePacked;
-                using (Compiler.Local iter = new Compiler.Local(ctx, enumeratorType))
-                using (Compiler.Local token = writePacked ? new Compiler.Local(ctx, ctx.MapType(typeof(SubItemToken))) : null)
-                {
-                    if (writePacked)
-                    {
-                        ctx.LoadValue(fieldNumber);
-                        ctx.LoadValue((int)WireType.String);
-                        ctx.LoadReaderWriter();
-                        ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("WriteFieldHeader"));
-
-                        ctx.LoadValue(list);
-                        ctx.LoadReaderWriter();
-                        ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("StartSubItem"));
-                        ctx.StoreValue(token);
-
-                        ctx.LoadValue(fieldNumber);
-                        ctx.LoadReaderWriter();
-                        ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("SetPackedField"));
-                    }
-
-                    ctx.LoadAddress(list, ExpectedType);
-                    ctx.EmitCall(getEnumerator, ExpectedType);
-                    ctx.StoreValue(iter);
-                    using (ctx.Using(iter))
-                    {
-                        Compiler.CodeLabel body = ctx.DefineLabel(), next = ctx.DefineLabel();
-                        ctx.Branch(next, false);
-
-                        ctx.MarkLabel(body);
-
-                        ctx.LoadAddress(iter, enumeratorType);
-                        ctx.EmitCall(current, enumeratorType);
-                        Type itemType = Tail.ExpectedType;
-                        if (itemType != ctx.MapType(typeof(object)) && current.ReturnType == ctx.MapType(typeof(object)))
-                        {
-                            ctx.CastFromObject(itemType);
-                        }
-                        Tail.EmitWrite(ctx, null);
-
-                        ctx.MarkLabel(@next);
-                        ctx.LoadAddress(iter, enumeratorType);
-                        ctx.EmitCall(moveNext, enumeratorType);
-                        ctx.BranchIfTrue(body, false);
-                    }
-
-                    if (writePacked)
-                    {
-                        ctx.LoadValue(token);
-                        ctx.LoadReaderWriter();
-                        ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("EndSubItem"));
-                    }
-                }
-            }
-        }
-#endif
-
-        public override void Write(object value, ProtoWriter dest)
-        {
-            SubItemToken token;
-            bool writePacked = WritePacked;
-            bool fixedSizePacked = writePacked & CanUsePackedPrefix(value) && value is ICollection;
-            if (writePacked)
-            {
-                ProtoWriter.WriteFieldHeader(fieldNumber, WireType.String, dest);
-                if (fixedSizePacked)
-                {
-                    ProtoWriter.WritePackedPrefix(((ICollection)value).Count, packedWireType, dest);
-                    token = default(SubItemToken);
-                }
-                else
-                {
-                    token = ProtoWriter.StartSubItem(value, dest);
-                }
-                ProtoWriter.SetPackedField(fieldNumber, dest);
-            }
-            else
-            {
-                token = new SubItemToken(); // default
-            }
-            bool checkForNull = !SupportNull;
-            foreach (object subItem in (IEnumerable)value)
-            {
-                if (checkForNull && subItem == null) { throw new NullReferenceException(); }
-                Tail.Write(subItem, dest);
-            }
-            if (writePacked)
-            {
-                if (fixedSizePacked)
-                {
-                    ProtoWriter.ClearPackedField(fieldNumber, dest);
-                }
-                else
-                {
-                    ProtoWriter.EndSubItem(token, dest);
-                }
-            }
-        }
-
-        private bool CanUsePackedPrefix(object obj) =>
-            ArrayDecorator.CanUsePackedPrefix(packedWireType, Tail.ExpectedType);
-
-        public override object Read(object value, ProtoReader source)
-        {
-            try
-            {
-                int field = source.FieldNumber;
-                object origValue = value;
-                if (value == null) value = Activator.CreateInstance(concreteType);
-                bool isList = IsList && !SuppressIList;
-                if (packedWireType != WireType.None && source.WireType == WireType.String)
-                {
-                    SubItemToken token = ProtoReader.StartSubItem(source);
-                    if (isList)
-                    {
-                        IList list = (IList)value;
-                        while (ProtoReader.HasSubValue(packedWireType, source))
-                        {
-                            list.Add(Tail.Read(null, source));
-                        }
-                    }
-                    else
-                    {
-                        object[] args = new object[1];
-                        while (ProtoReader.HasSubValue(packedWireType, source))
-                        {
-                            args[0] = Tail.Read(null, source);
-                            add.Invoke(value, args);
-                        }
-                    }
-                    ProtoReader.EndSubItem(token, source);
-                }
-                else
-                {
-                    if (isList)
-                    {
-                        IList list = (IList)value;
-                        do
-                        {
-                            list.Add(Tail.Read(null, source));
-                        } while (source.TryReadFieldHeader(field));
-                    }
-                    else
-                    {
-                        object[] args = new object[1];
-                        do
-                        {
-                            args[0] = Tail.Read(null, source);
-                            add.Invoke(value, args);
-                        } while (source.TryReadFieldHeader(field));
-                    }
-                }
-                return origValue == value ? null : value;
-            }
-            catch (TargetInvocationException tie)
-            {
-                if (tie.InnerException != null) throw tie.InnerException;
-                throw;
-            }
-        }
-
-    }
-}
-#endif

+ 0 - 298
ThirdParty/protobuf-net/Serializers/MapDecorator.cs

@@ -1,298 +0,0 @@
-using ProtoBuf.Meta;
-using System;
-#if FEAT_COMPILER
-using ProtoBuf.Compiler;
-#endif
-using System.Collections.Generic;
-using System.Reflection;
-
-namespace ProtoBuf.Serializers
-{
-    class MapDecorator<TDictionary, TKey, TValue> : ProtoDecoratorBase where TDictionary : class, IDictionary<TKey, TValue>
-    {
-        private readonly Type concreteType;
-        private readonly IProtoSerializer keyTail;
-        private readonly int fieldNumber;
-        private readonly WireType wireType;
-
-        internal MapDecorator(TypeModel model, Type concreteType, IProtoSerializer keyTail, IProtoSerializer valueTail,
-            int fieldNumber, WireType wireType, WireType keyWireType, WireType valueWireType, bool overwriteList)
-            : base(DefaultValue == null
-                  ? (IProtoSerializer)new TagDecorator(2, valueWireType, false, valueTail)
-                  : (IProtoSerializer)new DefaultValueDecorator(model, DefaultValue, new TagDecorator(2, valueWireType, false, valueTail)))
-        {
-            this.wireType = wireType;
-            this.keyTail = new DefaultValueDecorator(model, DefaultKey, new TagDecorator(1, keyWireType, false, keyTail));
-            this.fieldNumber = fieldNumber;
-            this.concreteType = concreteType ?? typeof(TDictionary);
-
-            if (keyTail.RequiresOldValue) throw new InvalidOperationException("Key tail should not require the old value");
-            if (!keyTail.ReturnsValue) throw new InvalidOperationException("Key tail should return a value");
-            if (!valueTail.ReturnsValue) throw new InvalidOperationException("Value tail should return a value");
-
-            AppendToCollection = !overwriteList;
-        }
-
-        private static readonly MethodInfo indexerSet = GetIndexerSetter();
-
-        private static MethodInfo GetIndexerSetter()
-        {
-#if PROFILE259
-			foreach(var prop in typeof(TDictionary).GetRuntimeProperties())
-#else
-            foreach (var prop in typeof(TDictionary).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
-#endif
-            {
-                if (prop.Name != "Item") continue;
-                if (prop.PropertyType != typeof(TValue)) continue;
-
-                var args = prop.GetIndexParameters();
-                if (args == null || args.Length != 1) continue;
-
-                if (args[0].ParameterType != typeof(TKey)) continue;
-#if PROFILE259
-				var method = prop.SetMethod;
-#else
-                var method = prop.GetSetMethod(true);
-#endif
-                if (method != null)
-                {
-                    return method;
-                }
-            }
-            throw new InvalidOperationException("Unable to resolve indexer for map");
-        }
-
-        private static readonly TKey DefaultKey = (typeof(TKey) == typeof(string)) ? (TKey)(object)"" : default(TKey);
-        private static readonly TValue DefaultValue = (typeof(TValue) == typeof(string)) ? (TValue)(object)"" : default(TValue);
-        public override Type ExpectedType => typeof(TDictionary);
-
-        public override bool ReturnsValue => true;
-
-        public override bool RequiresOldValue => AppendToCollection;
-
-        private bool AppendToCollection { get; }
-
-        public override object Read(object untyped, ProtoReader source)
-        {
-            TDictionary typed = AppendToCollection ? ((TDictionary)untyped) : null;
-            if (typed == null) typed = (TDictionary)Activator.CreateInstance(concreteType);
-
-            do
-            {
-                var key = DefaultKey;
-                var value = DefaultValue;
-                SubItemToken token = ProtoReader.StartSubItem(source);
-                int field;
-                while ((field = source.ReadFieldHeader()) > 0)
-                {
-                    switch (field)
-                    {
-                        case 1:
-                            key = (TKey)keyTail.Read(null, source);
-                            break;
-                        case 2:
-                            value = (TValue)Tail.Read(Tail.RequiresOldValue ? (object)value : null, source);
-                            break;
-                        default:
-                            source.SkipField();
-                            break;
-                    }
-                }
-
-                ProtoReader.EndSubItem(token, source);
-                typed[key] = value;
-            } while (source.TryReadFieldHeader(fieldNumber));
-
-            return typed;
-        }
-
-        public override void Write(object untyped, ProtoWriter dest)
-        {
-            foreach (var pair in (TDictionary)untyped)
-            {
-                ProtoWriter.WriteFieldHeader(fieldNumber, wireType, dest);
-                var token = ProtoWriter.StartSubItem(null, dest);
-                if (pair.Key != null) keyTail.Write(pair.Key, dest);
-                if (pair.Value != null) Tail.Write(pair.Value, dest);
-                ProtoWriter.EndSubItem(token, dest);
-            }
-        }
-
-#if FEAT_COMPILER
-        protected override void EmitWrite(CompilerContext ctx, Local valueFrom)
-        {
-            Type itemType = typeof(KeyValuePair<TKey, TValue>);
-            MethodInfo moveNext, current, getEnumerator = ListDecorator.GetEnumeratorInfo(ctx.Model,
-                ExpectedType, itemType, out moveNext, out current);
-            Type enumeratorType = getEnumerator.ReturnType;
-
-            MethodInfo key = itemType.GetProperty(nameof(KeyValuePair<TKey, TValue>.Key)).GetGetMethod(),
-                @value = itemType.GetProperty(nameof(KeyValuePair<TKey, TValue>.Value)).GetGetMethod();
-
-            using (Compiler.Local list = ctx.GetLocalWithValue(ExpectedType, valueFrom))
-            using (Compiler.Local iter = new Compiler.Local(ctx, enumeratorType))
-            using (Compiler.Local token = new Compiler.Local(ctx, typeof(SubItemToken)))
-            using (Compiler.Local kvp = new Compiler.Local(ctx, itemType))
-            {
-                ctx.LoadAddress(list, ExpectedType);
-                ctx.EmitCall(getEnumerator, ExpectedType);
-                ctx.StoreValue(iter);
-                using (ctx.Using(iter))
-                {
-                    Compiler.CodeLabel body = ctx.DefineLabel(), next = ctx.DefineLabel();
-                    ctx.Branch(next, false);
-
-                    ctx.MarkLabel(body);
-
-                    ctx.LoadAddress(iter, enumeratorType);
-                    ctx.EmitCall(current, enumeratorType);
-
-                    if (itemType != ctx.MapType(typeof(object)) && current.ReturnType == ctx.MapType(typeof(object)))
-                    {
-                        ctx.CastFromObject(itemType);
-                    }
-                    ctx.StoreValue(kvp);
-
-                    ctx.LoadValue(fieldNumber);
-                    ctx.LoadValue((int)wireType);
-                    ctx.LoadReaderWriter();
-                    ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("WriteFieldHeader"));
-
-                    ctx.LoadNullRef();
-                    ctx.LoadReaderWriter();
-                    ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("StartSubItem"));
-                    ctx.StoreValue(token);
-
-                    ctx.LoadAddress(kvp, itemType);
-                    ctx.EmitCall(key, itemType);
-                    ctx.WriteNullCheckedTail(typeof(TKey), keyTail, null);
-
-                    ctx.LoadAddress(kvp, itemType);
-                    ctx.EmitCall(value, itemType);
-                    ctx.WriteNullCheckedTail(typeof(TValue), Tail, null);
-
-                    ctx.LoadValue(token);
-                    ctx.LoadReaderWriter();
-                    ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("EndSubItem"));
-
-                    ctx.MarkLabel(@next);
-                    ctx.LoadAddress(iter, enumeratorType);
-                    ctx.EmitCall(moveNext, enumeratorType);
-                    ctx.BranchIfTrue(body, false);
-                }
-            }
-        }
-        protected override void EmitRead(CompilerContext ctx, Local valueFrom)
-        {
-            using (Compiler.Local list = AppendToCollection ? ctx.GetLocalWithValue(ExpectedType, valueFrom)
-                : new Compiler.Local(ctx, typeof(TDictionary)))
-            using (Compiler.Local token = new Compiler.Local(ctx, typeof(SubItemToken)))
-            using (Compiler.Local key = new Compiler.Local(ctx, typeof(TKey)))
-            using (Compiler.Local @value = new Compiler.Local(ctx, typeof(TValue)))
-            using (Compiler.Local fieldNumber = new Compiler.Local(ctx, ctx.MapType(typeof(int))))
-            {
-                if (!AppendToCollection)
-                { // always new
-                    ctx.LoadNullRef();
-                    ctx.StoreValue(list);
-                }
-                if (concreteType != null)
-                {
-                    ctx.LoadValue(list);
-                    Compiler.CodeLabel notNull = ctx.DefineLabel();
-                    ctx.BranchIfTrue(notNull, true);
-                    ctx.EmitCtor(concreteType);
-                    ctx.StoreValue(list);
-                    ctx.MarkLabel(notNull);
-                }
-
-                var redoFromStart = ctx.DefineLabel();
-                ctx.MarkLabel(redoFromStart);
-
-                // key = default(TKey); value = default(TValue);
-                if (typeof(TKey) == typeof(string))
-                {
-                    ctx.LoadValue("");
-                    ctx.StoreValue(key);
-                }
-                else
-                {
-                    ctx.InitLocal(typeof(TKey), key);
-                }
-                if (typeof(TValue) == typeof(string))
-                {
-                    ctx.LoadValue("");
-                    ctx.StoreValue(value);
-                }
-                else
-                {
-                    ctx.InitLocal(typeof(TValue), @value);
-                }
-
-                // token = ProtoReader.StartSubItem(reader);
-                ctx.LoadReaderWriter();
-                ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("StartSubItem"));
-                ctx.StoreValue(token);
-
-                Compiler.CodeLabel @continue = ctx.DefineLabel(), processField = ctx.DefineLabel();
-                // while ...
-                ctx.Branch(@continue, false);
-
-                // switch(fieldNumber)
-                ctx.MarkLabel(processField);
-                ctx.LoadValue(fieldNumber);
-                CodeLabel @default = ctx.DefineLabel(), one = ctx.DefineLabel(), two = ctx.DefineLabel();
-                ctx.Switch(new[] { @default, one, two }); // zero based, hence explicit 0
-
-                // case 0: default: reader.SkipField();
-                ctx.MarkLabel(@default);
-                ctx.LoadReaderWriter();
-                ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("SkipField"));
-                ctx.Branch(@continue, false);
-
-                // case 1: key = ...
-                ctx.MarkLabel(one);
-                keyTail.EmitRead(ctx, null);
-                ctx.StoreValue(key);
-                ctx.Branch(@continue, false);
-
-                // case 2: value = ...
-                ctx.MarkLabel(two);
-                Tail.EmitRead(ctx, Tail.RequiresOldValue ? @value : null);
-                ctx.StoreValue(value);
-
-                // (fieldNumber = reader.ReadFieldHeader()) > 0
-                ctx.MarkLabel(@continue);
-                ctx.EmitBasicRead("ReadFieldHeader", ctx.MapType(typeof(int)));
-                ctx.CopyValue();
-                ctx.StoreValue(fieldNumber);
-                ctx.LoadValue(0);
-                ctx.BranchIfGreater(processField, false);
-
-                // ProtoReader.EndSubItem(token, reader);
-                ctx.LoadValue(token);
-                ctx.LoadReaderWriter();
-                ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("EndSubItem"));
-
-                // list[key] = value;
-                ctx.LoadAddress(list, ExpectedType);
-                ctx.LoadValue(key);
-                ctx.LoadValue(@value);
-                ctx.EmitCall(indexerSet);
-
-                // while reader.TryReadFieldReader(fieldNumber)
-                ctx.LoadReaderWriter();
-                ctx.LoadValue(this.fieldNumber);
-                ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("TryReadFieldHeader"));
-                ctx.BranchIfTrue(redoFromStart, false);
-
-                if (ReturnsValue)
-                {
-                    ctx.LoadValue(list);
-                }
-            }
-        }
-#endif
-    }
-}

+ 0 - 76
ThirdParty/protobuf-net/Serializers/MemberSpecifiedDecorator.cs

@@ -1,76 +0,0 @@
-#if !NO_RUNTIME
-using System;
-using System.Reflection;
-
-namespace ProtoBuf.Serializers
-{
-    sealed class MemberSpecifiedDecorator : ProtoDecoratorBase
-    {
-        public override Type ExpectedType => Tail.ExpectedType;
-
-        public override bool RequiresOldValue => Tail.RequiresOldValue;
-
-        public override bool ReturnsValue => Tail.ReturnsValue;
-
-        private readonly MethodInfo getSpecified, setSpecified;
-        public MemberSpecifiedDecorator(MethodInfo getSpecified, MethodInfo setSpecified, IProtoSerializer tail)
-            : base(tail)
-        {
-            if (getSpecified == null && setSpecified == null) throw new InvalidOperationException();
-            this.getSpecified = getSpecified;
-            this.setSpecified = setSpecified;
-        }
-
-        public override void Write(object value, ProtoWriter dest)
-        {
-            if (getSpecified == null || (bool)getSpecified.Invoke(value, null))
-            {
-                Tail.Write(value, dest);
-            }
-        }
-
-        public override object Read(object value, ProtoReader source)
-        {
-            object result = Tail.Read(value, source);
-            if (setSpecified != null) setSpecified.Invoke(value, new object[] { true });
-            return result;
-        }
-
-#if FEAT_COMPILER
-        protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            if (getSpecified == null)
-            {
-                Tail.EmitWrite(ctx, valueFrom);
-                return;
-            }
-            using (Compiler.Local loc = ctx.GetLocalWithValue(ExpectedType, valueFrom))
-            {
-                ctx.LoadAddress(loc, ExpectedType);
-                ctx.EmitCall(getSpecified);
-                Compiler.CodeLabel done = ctx.DefineLabel();
-                ctx.BranchIfFalse(done, false);
-                Tail.EmitWrite(ctx, loc);
-                ctx.MarkLabel(done);
-            }
-
-        }
-        protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            if (setSpecified == null)
-            {
-                Tail.EmitRead(ctx, valueFrom);
-                return;
-            }
-            using (Compiler.Local loc = ctx.GetLocalWithValue(ExpectedType, valueFrom))
-            {
-                Tail.EmitRead(ctx, loc);
-                ctx.LoadAddress(loc, ExpectedType);
-                ctx.LoadValue(1); // true
-                ctx.EmitCall(setSpecified);
-            }
-        }
-#endif
-    }
-}
-#endif

+ 0 - 64
ThirdParty/protobuf-net/Serializers/NetObjectSerializer.cs

@@ -1,64 +0,0 @@
-#if !NO_RUNTIME
-using System;
-using System.Reflection;
-using ProtoBuf.Meta;
-
-namespace ProtoBuf.Serializers
-{
-    sealed class NetObjectSerializer : IProtoSerializer
-    {
-        private readonly int key;
-        private readonly Type type;
-
-        private readonly BclHelpers.NetObjectOptions options;
-
-        public NetObjectSerializer(TypeModel model, Type type, int key, BclHelpers.NetObjectOptions options)
-        {
-            bool dynamicType = (options & BclHelpers.NetObjectOptions.DynamicType) != 0;
-            this.key = dynamicType ? -1 : key;
-            this.type = dynamicType ? model.MapType(typeof(object)) : type;
-            this.options = options;
-        }
-
-        public Type ExpectedType => type;
-
-        public bool ReturnsValue => true;
-
-        public bool RequiresOldValue => true;
-
-        public object Read(object value, ProtoReader source)
-        {
-            return BclHelpers.ReadNetObject(value, source, key, type == typeof(object) ? null : type, options);
-        }
-
-        public void Write(object value, ProtoWriter dest)
-        {
-            BclHelpers.WriteNetObject(value, dest, key, options);
-        }
-
-#if FEAT_COMPILER
-        public void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ctx.LoadValue(valueFrom);
-            ctx.CastToObject(type);
-            ctx.LoadReaderWriter();
-            ctx.LoadValue(ctx.MapMetaKeyToCompiledKey(key));
-            if (type == ctx.MapType(typeof(object))) ctx.LoadNullRef();
-            else ctx.LoadValue(type);
-            ctx.LoadValue((int)options);
-            ctx.EmitCall(ctx.MapType(typeof(BclHelpers)).GetMethod("ReadNetObject"));
-            ctx.CastFromObject(type);
-        }
-        public void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ctx.LoadValue(valueFrom);
-            ctx.CastToObject(type);
-            ctx.LoadReaderWriter();
-            ctx.LoadValue(ctx.MapMetaKeyToCompiledKey(key));
-            ctx.LoadValue((int)options);
-            ctx.EmitCall(ctx.MapType(typeof(BclHelpers)).GetMethod("WriteNetObject"));
-        }
-#endif
-    }
-}
-#endif

+ 0 - 167
ThirdParty/protobuf-net/Serializers/NullDecorator.cs

@@ -1,167 +0,0 @@
-#if !NO_RUNTIME
-using System;
-using System.Reflection;
-
-using ProtoBuf.Meta;
-
-namespace ProtoBuf.Serializers
-{
-    sealed class NullDecorator : ProtoDecoratorBase
-    {
-        private readonly Type expectedType;
-        public const int Tag = 1;
-        public NullDecorator(TypeModel model, IProtoSerializer tail) : base(tail)
-        {
-            if (!tail.ReturnsValue)
-                throw new NotSupportedException("NullDecorator only supports implementations that return values");
-
-            Type tailType = tail.ExpectedType;
-            if (Helpers.IsValueType(tailType))
-            {
-                expectedType = model.MapType(typeof(Nullable<>)).MakeGenericType(tailType);
-            }
-            else
-            {
-                expectedType = tailType;
-            }
-        }
-
-        public override Type ExpectedType => expectedType;
-
-        public override bool ReturnsValue => true;
-
-        public override bool RequiresOldValue => true;
-
-#if FEAT_COMPILER
-        protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            using (Compiler.Local oldValue = ctx.GetLocalWithValue(expectedType, valueFrom))
-            using (Compiler.Local token = new Compiler.Local(ctx, ctx.MapType(typeof(SubItemToken))))
-            using (Compiler.Local field = new Compiler.Local(ctx, ctx.MapType(typeof(int))))
-            {
-                ctx.LoadReaderWriter();
-                ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("StartSubItem"));
-                ctx.StoreValue(token);
-
-                Compiler.CodeLabel next = ctx.DefineLabel(), processField = ctx.DefineLabel(), end = ctx.DefineLabel();
-
-                ctx.MarkLabel(next);
-
-                ctx.EmitBasicRead("ReadFieldHeader", ctx.MapType(typeof(int)));
-                ctx.CopyValue();
-                ctx.StoreValue(field);
-                ctx.LoadValue(Tag); // = 1 - process
-                ctx.BranchIfEqual(processField, true);
-                ctx.LoadValue(field);
-                ctx.LoadValue(1); // < 1 - exit
-                ctx.BranchIfLess(end, false);
-
-                // default: skip
-                ctx.LoadReaderWriter();
-                ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("SkipField"));
-                ctx.Branch(next, true);
-
-                // process
-                ctx.MarkLabel(processField);
-                if (Tail.RequiresOldValue)
-                {
-                    if (Helpers.IsValueType(expectedType))
-                    {
-                        ctx.LoadAddress(oldValue, expectedType);
-                        ctx.EmitCall(expectedType.GetMethod("GetValueOrDefault", Helpers.EmptyTypes));
-                    }
-                    else
-                    {
-                        ctx.LoadValue(oldValue);
-                    }
-                }
-                Tail.EmitRead(ctx, null);
-                // note we demanded always returns a value
-                if (Helpers.IsValueType(expectedType))
-                {
-                    ctx.EmitCtor(expectedType, Tail.ExpectedType); // re-nullable<T> it
-                }
-                ctx.StoreValue(oldValue);
-                ctx.Branch(next, false);
-
-                // outro
-                ctx.MarkLabel(end);
-
-                ctx.LoadValue(token);
-                ctx.LoadReaderWriter();
-                ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("EndSubItem"));
-                ctx.LoadValue(oldValue); // load the old value
-            }
-        }
-        protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            using (Compiler.Local valOrNull = ctx.GetLocalWithValue(expectedType, valueFrom))
-            using (Compiler.Local token = new Compiler.Local(ctx, ctx.MapType(typeof(SubItemToken))))
-            {
-                ctx.LoadNullRef();
-                ctx.LoadReaderWriter();
-                ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("StartSubItem"));
-                ctx.StoreValue(token);
-
-                if (Helpers.IsValueType(expectedType))
-                {
-                    ctx.LoadAddress(valOrNull, expectedType);
-                    ctx.LoadValue(expectedType.GetProperty("HasValue"));
-                }
-                else
-                {
-                    ctx.LoadValue(valOrNull);
-                }
-                Compiler.CodeLabel @end = ctx.DefineLabel();
-                ctx.BranchIfFalse(@end, false);
-                if (Helpers.IsValueType(expectedType))
-                {
-                    ctx.LoadAddress(valOrNull, expectedType);
-                    ctx.EmitCall(expectedType.GetMethod("GetValueOrDefault", Helpers.EmptyTypes));
-                }
-                else
-                {
-                    ctx.LoadValue(valOrNull);
-                }
-                Tail.EmitWrite(ctx, null);
-
-                ctx.MarkLabel(@end);
-
-                ctx.LoadValue(token);
-                ctx.LoadReaderWriter();
-                ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("EndSubItem"));
-            }
-        }
-#endif
-
-        public override object Read(object value, ProtoReader source)
-        {
-            SubItemToken tok = ProtoReader.StartSubItem(source);
-            int field;
-            while ((field = source.ReadFieldHeader()) > 0)
-            {
-                if (field == Tag)
-                {
-                    value = Tail.Read(value, source);
-                }
-                else
-                {
-                    source.SkipField();
-                }
-            }
-            ProtoReader.EndSubItem(tok, source);
-            return value;
-        }
-
-        public override void Write(object value, ProtoWriter dest)
-        {
-            SubItemToken token = ProtoWriter.StartSubItem(null, dest);
-            if (value != null)
-            {
-                Tail.Write(value, dest);
-            }
-            ProtoWriter.EndSubItem(token, dest);
-        }
-    }
-}
-#endif

+ 0 - 111
ThirdParty/protobuf-net/Serializers/ParseableSerializer.cs

@@ -1,111 +0,0 @@
-#if !NO_RUNTIME
-using System;
-using System.Net;
-using ProtoBuf.Meta;
-using System.Reflection;
-
-namespace ProtoBuf.Serializers
-{
-    sealed class ParseableSerializer : IProtoSerializer
-    {
-        private readonly MethodInfo parse;
-        public static ParseableSerializer TryCreate(Type type, TypeModel model)
-        {
-            if (type == null) throw new ArgumentNullException("type");
-#if PORTABLE || COREFX || PROFILE259
-			MethodInfo method = null;
-
-#if COREFX || PROFILE259
-			foreach (MethodInfo tmp in type.GetTypeInfo().GetDeclaredMethods("Parse"))
-#else
-            foreach (MethodInfo tmp in type.GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly))
-#endif
-            {
-                ParameterInfo[] p;
-                if (tmp.Name == "Parse" && tmp.IsPublic && tmp.IsStatic && tmp.DeclaringType == type && (p = tmp.GetParameters()) != null && p.Length == 1 && p[0].ParameterType == typeof(string))
-                {
-                    method = tmp;
-                    break;
-                }
-            }
-#else
-            MethodInfo method = type.GetMethod("Parse",
-                BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly,
-                null, new Type[] { model.MapType(typeof(string)) }, null);
-#endif
-            if (method != null && method.ReturnType == type)
-            {
-                if (Helpers.IsValueType(type))
-                {
-                    MethodInfo toString = GetCustomToString(type);
-                    if (toString == null || toString.ReturnType != model.MapType(typeof(string))) return null; // need custom ToString, fools
-                }
-                return new ParseableSerializer(method);
-            }
-            return null;
-        }
-        private static MethodInfo GetCustomToString(Type type)
-        {
-#if PORTABLE || COREFX || PROFILE259
-			MethodInfo method = Helpers.GetInstanceMethod(type, "ToString", Helpers.EmptyTypes);
-            if (method == null || !method.IsPublic || method.IsStatic || method.DeclaringType != type) return null;
-            return method;
-#else
-
-            return type.GetMethod("ToString", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
-                        null, Helpers.EmptyTypes, null);
-#endif
-        }
-
-        private ParseableSerializer(MethodInfo parse)
-        {
-            this.parse = parse;
-        }
-
-        public Type ExpectedType => parse.DeclaringType;
-
-        bool IProtoSerializer.RequiresOldValue { get { return false; } }
-        bool IProtoSerializer.ReturnsValue { get { return true; } }
-
-        public object Read(object value, ProtoReader source)
-        {
-            Helpers.DebugAssert(value == null); // since replaces
-            return parse.Invoke(null, new object[] { source.ReadString() });
-        }
-
-        public void Write(object value, ProtoWriter dest)
-        {
-            ProtoWriter.WriteString(value.ToString(), dest);
-        }
-
-#if FEAT_COMPILER
-        void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            Type type = ExpectedType;
-            if (Helpers.IsValueType(type))
-            {   // note that for structs, we've already asserted that a custom ToString
-                // exists; no need to handle the box/callvirt scenario
-
-                // force it to a variable if needed, so we can take the address
-                using (Compiler.Local loc = ctx.GetLocalWithValue(type, valueFrom))
-                {
-                    ctx.LoadAddress(loc, type);
-                    ctx.EmitCall(GetCustomToString(type));
-                }
-            }
-            else
-            {
-                ctx.EmitCall(ctx.MapType(typeof(object)).GetMethod("ToString"));
-            }
-            ctx.EmitBasicWrite("WriteString", valueFrom);
-        }
-        void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ctx.EmitBasicRead("ReadString", ctx.MapType(typeof(string)));
-            ctx.EmitCall(parse);
-        }
-#endif
-
-    }
-}
-#endif

+ 0 - 167
ThirdParty/protobuf-net/Serializers/PropertyDecorator.cs

@@ -1,167 +0,0 @@
-#if !NO_RUNTIME
-using System;
-using System.Reflection;
-
-using ProtoBuf.Meta;
-
-namespace ProtoBuf.Serializers
-{
-    sealed class PropertyDecorator : ProtoDecoratorBase
-    {
-        public override Type ExpectedType => forType;
-        private readonly PropertyInfo property;
-        private readonly Type forType;
-        public override bool RequiresOldValue => true;
-        public override bool ReturnsValue => false;
-        private readonly bool readOptionsWriteValue;
-        private readonly MethodInfo shadowSetter;
-
-        public PropertyDecorator(TypeModel model, Type forType, PropertyInfo property, IProtoSerializer tail) : base(tail)
-        {
-            Helpers.DebugAssert(forType != null);
-            Helpers.DebugAssert(property != null);
-            this.forType = forType;
-            this.property = property;
-            SanityCheck(model, property, tail, out readOptionsWriteValue, true, true);
-            shadowSetter = GetShadowSetter(model, property);
-        }
-
-        private static void SanityCheck(TypeModel model, PropertyInfo property, IProtoSerializer tail, out bool writeValue, bool nonPublic, bool allowInternal)
-        {
-            if (property == null) throw new ArgumentNullException("property");
-
-            writeValue = tail.ReturnsValue && (GetShadowSetter(model, property) != null || (property.CanWrite && Helpers.GetSetMethod(property, nonPublic, allowInternal) != null));
-            if (!property.CanRead || Helpers.GetGetMethod(property, nonPublic, allowInternal) == null)
-            {
-                throw new InvalidOperationException("Cannot serialize property without a get accessor");
-            }
-            if (!writeValue && (!tail.RequiresOldValue || Helpers.IsValueType(tail.ExpectedType)))
-            { // so we can't save the value, and the tail doesn't use it either... not helpful
-                // or: can't write the value, so the struct value will be lost
-                throw new InvalidOperationException("Cannot apply changes to property " + property.DeclaringType.FullName + "." + property.Name);
-            }
-        }
-        static MethodInfo GetShadowSetter(TypeModel model, PropertyInfo property)
-        {
-#if COREFX
-            MethodInfo method = Helpers.GetInstanceMethod(property.DeclaringType.GetTypeInfo(), "Set" + property.Name, new Type[] { property.PropertyType });
-#else
-
-#if PROFILE259
-            Type reflectedType = property.DeclaringType;
-#else
-            Type reflectedType = property.ReflectedType;
-#endif
-            MethodInfo method = Helpers.GetInstanceMethod(reflectedType, "Set" + property.Name, new Type[] { property.PropertyType });
-#endif
-            if (method == null || !method.IsPublic || method.ReturnType != model.MapType(typeof(void))) return null;
-            return method;
-        }
-
-        public override void Write(object value, ProtoWriter dest)
-        {
-            Helpers.DebugAssert(value != null);
-            value = property.GetValue(value, null);
-            if (value != null) Tail.Write(value, dest);
-        }
-
-        public override object Read(object value, ProtoReader source)
-        {
-            Helpers.DebugAssert(value != null);
-
-            object oldVal = Tail.RequiresOldValue ? property.GetValue(value, null) : null;
-            object newVal = Tail.Read(oldVal, source);
-            if (readOptionsWriteValue && newVal != null) // if the tail returns a null, intepret that as *no assign*
-            {
-                if (shadowSetter == null)
-                {
-                    property.SetValue(value, newVal, null);
-                }
-                else
-                {
-                    shadowSetter.Invoke(value, new object[] { newVal });
-                }
-            }
-            return null;
-        }
-
-#if FEAT_COMPILER
-        protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ctx.LoadAddress(valueFrom, ExpectedType);
-            ctx.LoadValue(property);
-            ctx.WriteNullCheckedTail(property.PropertyType, Tail, null);
-        }
-
-        protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            SanityCheck(ctx.Model, property, Tail, out bool writeValue, ctx.NonPublic, ctx.AllowInternal(property));
-            if (Helpers.IsValueType(ExpectedType) && valueFrom == null)
-            {
-                throw new InvalidOperationException("Attempt to mutate struct on the head of the stack; changes would be lost");
-            }
-
-            using (Compiler.Local loc = ctx.GetLocalWithValue(ExpectedType, valueFrom))
-            {
-                if (Tail.RequiresOldValue)
-                {
-                    ctx.LoadAddress(loc, ExpectedType); // stack is: old-addr
-                    ctx.LoadValue(property); // stack is: old-value
-                }
-                Type propertyType = property.PropertyType;
-                ctx.ReadNullCheckedTail(propertyType, Tail, null); // stack is [new-value]
-
-                if (writeValue)
-                {
-                    using (Compiler.Local newVal = new Compiler.Local(ctx, property.PropertyType))
-                    {
-                        ctx.StoreValue(newVal); // stack is empty
-
-                        Compiler.CodeLabel allDone = new Compiler.CodeLabel(); // <=== default structs
-                        if (!Helpers.IsValueType(propertyType))
-                        { // if the tail returns a null, intepret that as *no assign*
-                            allDone = ctx.DefineLabel();
-                            ctx.LoadValue(newVal); // stack is: new-value
-                            ctx.BranchIfFalse(@allDone, true); // stack is empty
-                        }
-                        // assign the value
-                        ctx.LoadAddress(loc, ExpectedType); // parent-addr
-                        ctx.LoadValue(newVal); // parent-obj|new-value
-                        if (shadowSetter == null)
-                        {
-                            ctx.StoreValue(property); // empty
-                        }
-                        else
-                        {
-                            ctx.EmitCall(shadowSetter); // empty
-                        }
-                        if (!Helpers.IsValueType(propertyType))
-                        {
-                            ctx.MarkLabel(allDone);
-                        }
-                    }
-
-                }
-                else
-                { // don't want return value; drop it if anything there
-                    // stack is [new-value]
-                    if (Tail.ReturnsValue) { ctx.DiscardValue(); }
-                }
-            }
-        }
-#endif
-
-        internal static bool CanWrite(TypeModel model, MemberInfo member)
-        {
-            if (member == null) throw new ArgumentNullException(nameof(member));
-
-            if (member is PropertyInfo prop)
-            {
-                return prop.CanWrite || GetShadowSetter(model, prop) != null;
-            }
-
-            return member is FieldInfo; // fields are always writeable; anything else: JUST SAY NO!
-        }
-    }
-}
-#endif

+ 0 - 24
ThirdParty/protobuf-net/Serializers/ProtoDecoratorBase.cs

@@ -1,24 +0,0 @@
-#if !NO_RUNTIME
-using System;
-
-namespace ProtoBuf.Serializers
-{
-    abstract class ProtoDecoratorBase : IProtoSerializer
-    {
-        public abstract Type ExpectedType { get; }
-        protected readonly IProtoSerializer Tail;
-        protected ProtoDecoratorBase(IProtoSerializer tail) { this.Tail = tail; }
-        public abstract bool ReturnsValue { get; }
-        public abstract bool RequiresOldValue { get; }
-        public abstract void Write(object value, ProtoWriter dest);
-        public abstract object Read(object value, ProtoReader source);
-
-#if FEAT_COMPILER
-        void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) { EmitWrite(ctx, valueFrom); }
-        protected abstract void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom);
-        void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) { EmitRead(ctx, valueFrom); }
-        protected abstract void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom);
-#endif
-    }
-}
-#endif

+ 0 - 90
ThirdParty/protobuf-net/Serializers/ReflectedUriDecorator.cs

@@ -1,90 +0,0 @@
-#if !NO_RUNTIME
-#if PORTABLE
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Linq;
-using System.Reflection;
-
-namespace ProtoBuf.Serializers
-{
-    /// <summary>
-    /// Manipulates with uris via reflection rather than strongly typed objects.
-    /// This is because in PCLs, the Uri type may not match (WinRT uses Internal/Uri, .Net uses System/Uri)
-    /// </summary>
-    sealed class ReflectedUriDecorator : ProtoDecoratorBase
-    {
-        private readonly Type expectedType;
-
-        private readonly PropertyInfo absoluteUriProperty;
-
-        private readonly ConstructorInfo typeConstructor;
-
-        public ReflectedUriDecorator(Type type, ProtoBuf.Meta.TypeModel model, IProtoSerializer tail) : base(tail)
-        {
-            expectedType = type;
-
-#if PROFILE259
-			absoluteUriProperty = expectedType.GetRuntimeProperty("AbsoluteUri");
-	        IEnumerable<ConstructorInfo> constructors = expectedType.GetTypeInfo().DeclaredConstructors;
-	        typeConstructor = null;
-			foreach(ConstructorInfo constructor in constructors)
-			{
-				ParameterInfo[] parameters = constructor.GetParameters();
-				ParameterInfo parameterFirst = parameters.FirstOrDefault();
-				Type stringType = typeof(string);
-				if (parameterFirst != null && 
-					parameterFirst.ParameterType == stringType)
-				{
-					typeConstructor = constructor;
-					break;
-				}
-	        }
-#else
-			absoluteUriProperty = expectedType.GetProperty("AbsoluteUri");
-            typeConstructor = expectedType.GetConstructor(new Type[] { typeof(string) });
-#endif
-		}
-		public override Type ExpectedType { get { return expectedType; } }
-        public override bool RequiresOldValue { get { return false; } }
-        public override bool ReturnsValue { get { return true; } }
-        
-        public override void Write(object value, ProtoWriter dest)
-        {
-            Tail.Write(absoluteUriProperty.GetValue(value, null), dest);
-        }
-        public override object Read(object value, ProtoReader source)
-        {
-            Helpers.DebugAssert(value == null); // not expecting incoming
-            string s = (string)Tail.Read(null, source);
-
-            return s.Length == 0 ? null : typeConstructor.Invoke(new object[] { s });
-        }
-
-#if FEAT_COMPILER
-        protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ctx.LoadValue(valueFrom);
-            ctx.LoadValue(absoluteUriProperty);
-            Tail.EmitWrite(ctx, null);
-        }
-        protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            Tail.EmitRead(ctx, valueFrom);
-            ctx.CopyValue();
-            Compiler.CodeLabel @nonEmpty = ctx.DefineLabel(), @end = ctx.DefineLabel();
-            ctx.LoadValue(typeof(string).GetProperty("Length"));
-            ctx.BranchIfTrue(@nonEmpty, true);
-            ctx.DiscardValue();
-            ctx.LoadNullRef();
-            ctx.Branch(@end, true);
-            ctx.MarkLabel(@nonEmpty);
-            ctx.EmitCtor(expectedType, ctx.MapType(typeof(string)));
-            ctx.MarkLabel(@end);
-            
-        }
-#endif
-    }
-}
-#endif
-#endif

+ 0 - 45
ThirdParty/protobuf-net/Serializers/SByteSerializer.cs

@@ -1,45 +0,0 @@
-#if !NO_RUNTIME
-using System;
-
-namespace ProtoBuf.Serializers
-{
-    sealed class SByteSerializer : IProtoSerializer
-    {
-        static readonly Type expectedType = typeof(sbyte);
-
-        public SByteSerializer(ProtoBuf.Meta.TypeModel model)
-        {
-
-        }
-
-        public Type ExpectedType => expectedType;
-
-        bool IProtoSerializer.RequiresOldValue => false;
-
-        bool IProtoSerializer.ReturnsValue => true;
-
-        public object Read(object value, ProtoReader source)
-        {
-            Helpers.DebugAssert(value == null); // since replaces
-            return source.ReadSByte();
-        }
-
-        public void Write(object value, ProtoWriter dest)
-        {
-            ProtoWriter.WriteSByte((sbyte)value, dest);
-        }
-
-#if FEAT_COMPILER
-        void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ctx.EmitBasicWrite("WriteSByte", valueFrom);
-        }
-        void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ctx.EmitBasicRead("ReadSByte", ExpectedType);
-        }
-#endif
-
-    }
-}
-#endif

+ 0 - 45
ThirdParty/protobuf-net/Serializers/SingleSerializer.cs

@@ -1,45 +0,0 @@
-#if !NO_RUNTIME
-using System;
-using ProtoBuf.Meta;
-
-namespace ProtoBuf.Serializers
-{
-    sealed class SingleSerializer : IProtoSerializer
-    {
-        static readonly Type expectedType = typeof(float);
-
-        public Type ExpectedType { get { return expectedType; } }
-
-        public SingleSerializer(TypeModel model)
-        {
-        }
-
-        bool IProtoSerializer.RequiresOldValue => false;
-
-        bool IProtoSerializer.ReturnsValue => true;
-
-        public object Read(object value, ProtoReader source)
-        {
-            Helpers.DebugAssert(value == null); // since replaces
-            return source.ReadSingle();
-        }
-
-        public void Write(object value, ProtoWriter dest)
-        {
-            ProtoWriter.WriteSingle((float)value, dest);
-        }
-
-
-#if FEAT_COMPILER
-        void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ctx.EmitBasicWrite("WriteSingle", valueFrom);
-        }
-        void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ctx.EmitBasicRead("ReadSingle", ExpectedType);
-        }
-#endif
-    }
-}
-#endif

+ 0 - 41
ThirdParty/protobuf-net/Serializers/StringSerializer.cs

@@ -1,41 +0,0 @@
-#if !NO_RUNTIME
-using System;
-
-namespace ProtoBuf.Serializers
-{
-    sealed class StringSerializer : IProtoSerializer
-    {
-        static readonly Type expectedType = typeof(string);
-
-        public StringSerializer(ProtoBuf.Meta.TypeModel model)
-        {
-        }
-
-        public Type ExpectedType => expectedType;
-
-        public void Write(object value, ProtoWriter dest)
-        {
-            ProtoWriter.WriteString((string)value, dest);
-        }
-        bool IProtoSerializer.RequiresOldValue => false;
-
-        bool IProtoSerializer.ReturnsValue => true;
-
-        public object Read(object value, ProtoReader source)
-        {
-            Helpers.DebugAssert(value == null); // since replaces
-            return source.ReadString();
-        }
-#if FEAT_COMPILER
-        void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ctx.EmitBasicWrite("WriteString", valueFrom);
-        }
-        void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ctx.EmitBasicRead("ReadString", ExpectedType);
-        }
-#endif
-    }
-}
-#endif

+ 0 - 138
ThirdParty/protobuf-net/Serializers/SubItemSerializer.cs

@@ -1,138 +0,0 @@
-#if !NO_RUNTIME
-using System;
-using ProtoBuf.Meta;
-
-#if FEAT_COMPILER
-using System.Reflection.Emit;
-#endif
-
-namespace ProtoBuf.Serializers
-{
-    sealed class SubItemSerializer : IProtoTypeSerializer
-    {
-        bool IProtoTypeSerializer.HasCallbacks(TypeModel.CallbackType callbackType)
-        {
-            return ((IProtoTypeSerializer)proxy.Serializer).HasCallbacks(callbackType);
-        }
-
-        bool IProtoTypeSerializer.CanCreateInstance()
-        {
-            return ((IProtoTypeSerializer)proxy.Serializer).CanCreateInstance();
-        }
-
-#if FEAT_COMPILER
-        void IProtoTypeSerializer.EmitCallback(Compiler.CompilerContext ctx, Compiler.Local valueFrom, TypeModel.CallbackType callbackType)
-        {
-            ((IProtoTypeSerializer)proxy.Serializer).EmitCallback(ctx, valueFrom, callbackType);
-        }
-
-        void IProtoTypeSerializer.EmitCreateInstance(Compiler.CompilerContext ctx)
-        {
-            ((IProtoTypeSerializer)proxy.Serializer).EmitCreateInstance(ctx);
-        }
-#endif
-
-        void IProtoTypeSerializer.Callback(object value, TypeModel.CallbackType callbackType, SerializationContext context)
-        {
-            ((IProtoTypeSerializer)proxy.Serializer).Callback(value, callbackType, context);
-        }
-
-        object IProtoTypeSerializer.CreateInstance(ProtoReader source)
-        {
-            return ((IProtoTypeSerializer)proxy.Serializer).CreateInstance(source);
-        }
-
-        private readonly int key;
-        private readonly Type type;
-        private readonly ISerializerProxy proxy;
-        private readonly bool recursionCheck;
-        public SubItemSerializer(Type type, int key, ISerializerProxy proxy, bool recursionCheck)
-        {
-            this.type = type ?? throw new ArgumentNullException(nameof(type));
-            this.proxy = proxy ?? throw new ArgumentNullException(nameof(proxy));
-            this.key = key;
-            this.recursionCheck = recursionCheck;
-        }
-
-        Type IProtoSerializer.ExpectedType => type;
-
-        bool IProtoSerializer.RequiresOldValue => true;
-
-        bool IProtoSerializer.ReturnsValue => true;
-
-        void IProtoSerializer.Write(object value, ProtoWriter dest)
-        {
-            if (recursionCheck)
-            {
-                ProtoWriter.WriteObject(value, key, dest);
-            }
-            else
-            {
-                ProtoWriter.WriteRecursionSafeObject(value, key, dest);
-            }
-        }
-
-        object IProtoSerializer.Read(object value, ProtoReader source)
-        {
-            return ProtoReader.ReadObject(value, key, source);
-        }
-
-#if FEAT_COMPILER
-        bool EmitDedicatedMethod(Compiler.CompilerContext ctx, Compiler.Local valueFrom, bool read)
-        {
-            MethodBuilder method = ctx.GetDedicatedMethod(key, read);
-            if (method == null) return false;
-
-            using (Compiler.Local token = new ProtoBuf.Compiler.Local(ctx, ctx.MapType(typeof(SubItemToken))))
-            {
-                Type rwType = ctx.MapType(read ? typeof(ProtoReader) : typeof(ProtoWriter));
-                ctx.LoadValue(valueFrom);
-                if (!read) // write requires the object for StartSubItem; read doesn't
-                {  // (if recursion-check is disabled [subtypes] then null is fine too)
-                    if (Helpers.IsValueType(type) || !recursionCheck) { ctx.LoadNullRef(); }
-                    else { ctx.CopyValue(); }
-                }
-                ctx.LoadReaderWriter();
-                ctx.EmitCall(Helpers.GetStaticMethod(rwType, "StartSubItem",
-                    read ? new Type[] { rwType } : new Type[] { ctx.MapType(typeof(object)), rwType }));
-                ctx.StoreValue(token);
-
-                // note: value already on the stack
-                ctx.LoadReaderWriter();
-                ctx.EmitCall(method);
-                // handle inheritance (we will be calling the *base* version of things,
-                // but we expect Read to return the "type" type)
-                if (read && type != method.ReturnType) ctx.Cast(this.type);
-                ctx.LoadValue(token);
-                ctx.LoadReaderWriter();
-                ctx.EmitCall(Helpers.GetStaticMethod(rwType, "EndSubItem", new Type[] { ctx.MapType(typeof(SubItemToken)), rwType }));
-            }
-            return true;
-        }
-        void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            if (!EmitDedicatedMethod(ctx, valueFrom, false))
-            {
-                ctx.LoadValue(valueFrom);
-                if (Helpers.IsValueType(type)) ctx.CastToObject(type);
-                ctx.LoadValue(ctx.MapMetaKeyToCompiledKey(key)); // re-map for formality, but would expect identical, else dedicated method
-                ctx.LoadReaderWriter();
-                ctx.EmitCall(Helpers.GetStaticMethod(ctx.MapType(typeof(ProtoWriter)), recursionCheck ? "WriteObject" : "WriteRecursionSafeObject", new Type[] { ctx.MapType(typeof(object)), ctx.MapType(typeof(int)), ctx.MapType(typeof(ProtoWriter)) }));
-            }
-        }
-        void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            if (!EmitDedicatedMethod(ctx, valueFrom, true))
-            {
-                ctx.LoadValue(valueFrom);
-                if (Helpers.IsValueType(type)) ctx.CastToObject(type);
-                ctx.LoadValue(ctx.MapMetaKeyToCompiledKey(key)); // re-map for formality, but would expect identical, else dedicated method
-                ctx.LoadReaderWriter();
-                ctx.EmitCall(Helpers.GetStaticMethod(ctx.MapType(typeof(ProtoReader)), "ReadObject"));
-                ctx.CastFromObject(type);
-            }
-        }
-#endif
-    }
-}
-#endif

+ 0 - 157
ThirdParty/protobuf-net/Serializers/SurrogateSerializer.cs

@@ -1,157 +0,0 @@
-#if !NO_RUNTIME
-using System;
-using ProtoBuf.Meta;
-using System.Reflection;
-
-namespace ProtoBuf.Serializers
-{
-    sealed class SurrogateSerializer : IProtoTypeSerializer
-    {
-        bool IProtoTypeSerializer.HasCallbacks(ProtoBuf.Meta.TypeModel.CallbackType callbackType) { return false; }
-#if FEAT_COMPILER
-        void IProtoTypeSerializer.EmitCallback(Compiler.CompilerContext ctx, Compiler.Local valueFrom, ProtoBuf.Meta.TypeModel.CallbackType callbackType) { }
-        void IProtoTypeSerializer.EmitCreateInstance(Compiler.CompilerContext ctx) { throw new NotSupportedException(); }
-#endif
-        bool IProtoTypeSerializer.CanCreateInstance() => false;
-
-        object IProtoTypeSerializer.CreateInstance(ProtoReader source) => throw new NotSupportedException();
-
-        void IProtoTypeSerializer.Callback(object value, ProtoBuf.Meta.TypeModel.CallbackType callbackType, SerializationContext context) { }
-
-        public bool ReturnsValue => false;
-
-        public bool RequiresOldValue => true;
-
-        public Type ExpectedType => forType;
-
-        private readonly Type forType, declaredType;
-        private readonly MethodInfo toTail, fromTail;
-        IProtoTypeSerializer rootTail;
-
-        public SurrogateSerializer(TypeModel model, Type forType, Type declaredType, IProtoTypeSerializer rootTail)
-        {
-            Helpers.DebugAssert(forType != null, "forType");
-            Helpers.DebugAssert(declaredType != null, "declaredType");
-            Helpers.DebugAssert(rootTail != null, "rootTail");
-            Helpers.DebugAssert(rootTail.RequiresOldValue, "RequiresOldValue");
-            Helpers.DebugAssert(!rootTail.ReturnsValue, "ReturnsValue");
-            Helpers.DebugAssert(declaredType == rootTail.ExpectedType || Helpers.IsSubclassOf(declaredType, rootTail.ExpectedType));
-            this.forType = forType;
-            this.declaredType = declaredType;
-            this.rootTail = rootTail;
-            toTail = GetConversion(model, true);
-            fromTail = GetConversion(model, false);
-        }
-        private static bool HasCast(TypeModel model, Type type, Type from, Type to, out MethodInfo op)
-        {
-#if PROFILE259
-			System.Collections.Generic.List<MethodInfo> list = new System.Collections.Generic.List<MethodInfo>();
-            foreach (var item in type.GetRuntimeMethods())
-            {
-                if (item.IsStatic) list.Add(item);
-            }
-            MethodInfo[] found = list.ToArray();
-#else
-            const BindingFlags flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
-            MethodInfo[] found = type.GetMethods(flags);
-#endif
-            ParameterInfo[] paramTypes;
-            Type convertAttributeType = null;
-            for (int i = 0; i < found.Length; i++)
-            {
-                MethodInfo m = found[i];
-                if (m.ReturnType != to) continue;
-                paramTypes = m.GetParameters();
-                if (paramTypes.Length == 1 && paramTypes[0].ParameterType == from)
-                {
-                    if (convertAttributeType == null)
-                    {
-                        convertAttributeType = model.MapType(typeof(ProtoConverterAttribute), false);
-                        if (convertAttributeType == null)
-                        { // attribute isn't defined in the source assembly: stop looking
-                            break;
-                        }
-                    }
-                    if (m.IsDefined(convertAttributeType, true))
-                    {
-                        op = m;
-                        return true;
-                    }
-                }
-            }
-
-            for (int i = 0; i < found.Length; i++)
-            {
-                MethodInfo m = found[i];
-                if ((m.Name != "op_Implicit" && m.Name != "op_Explicit") || m.ReturnType != to)
-                {
-                    continue;
-                }
-                paramTypes = m.GetParameters();
-                if (paramTypes.Length == 1 && paramTypes[0].ParameterType == from)
-                {
-                    op = m;
-                    return true;
-                }
-            }
-            op = null;
-            return false;
-        }
-
-        public MethodInfo GetConversion(TypeModel model, bool toTail)
-        {
-            Type to = toTail ? declaredType : forType;
-            Type from = toTail ? forType : declaredType;
-            MethodInfo op;
-            if (HasCast(model, declaredType, from, to, out op) || HasCast(model, forType, from, to, out op))
-            {
-                return op;
-            }
-            throw new InvalidOperationException("No suitable conversion operator found for surrogate: " +
-                forType.FullName + " / " + declaredType.FullName);
-        }
-
-        public void Write(object value, ProtoWriter writer)
-        {
-            rootTail.Write(toTail.Invoke(null, new object[] { value }), writer);
-        }
-
-        public object Read(object value, ProtoReader source)
-        {
-            // convert the incoming value
-            object[] args = { value };
-            value = toTail.Invoke(null, args);
-
-            // invoke the tail and convert the outgoing value
-            args[0] = rootTail.Read(value, source);
-            return fromTail.Invoke(null, args);
-        }
-
-#if FEAT_COMPILER
-        void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            Helpers.DebugAssert(valueFrom != null); // don't support stack-head for this
-            using (Compiler.Local converted = new Compiler.Local(ctx, declaredType)) // declare/re-use local
-            {
-                ctx.LoadValue(valueFrom); // load primary onto stack
-                ctx.EmitCall(toTail); // static convert op, primary-to-surrogate
-                ctx.StoreValue(converted); // store into surrogate local
-
-                rootTail.EmitRead(ctx, converted); // downstream processing against surrogate local
-
-                ctx.LoadValue(converted); // load from surrogate local
-                ctx.EmitCall(fromTail);  // static convert op, surrogate-to-primary
-                ctx.StoreValue(valueFrom); // store back into primary
-            }
-        }
-
-        void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ctx.LoadValue(valueFrom);
-            ctx.EmitCall(toTail);
-            rootTail.EmitWrite(ctx, null);
-        }
-#endif
-    }
-}
-#endif

+ 0 - 46
ThirdParty/protobuf-net/Serializers/SystemTypeSerializer.cs

@@ -1,46 +0,0 @@
-using System;
-
-#if !NO_RUNTIME
-
-namespace ProtoBuf.Serializers
-{
-    sealed class SystemTypeSerializer : IProtoSerializer
-    {
-        static readonly Type expectedType = typeof(Type);
-
-        public SystemTypeSerializer(ProtoBuf.Meta.TypeModel model)
-        {
-
-        }
-
-        public Type ExpectedType => expectedType;
-
-        void IProtoSerializer.Write(object value, ProtoWriter dest)
-        {
-            ProtoWriter.WriteType((Type)value, dest);
-        }
-
-        object IProtoSerializer.Read(object value, ProtoReader source)
-        {
-            Helpers.DebugAssert(value == null); // since replaces
-            return source.ReadType();
-        }
-
-        bool IProtoSerializer.RequiresOldValue => false;
-
-        bool IProtoSerializer.ReturnsValue => true;
-
-#if FEAT_COMPILER
-        void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ctx.EmitBasicWrite("WriteType", valueFrom);
-        }
-        void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
-        {
-            ctx.EmitBasicRead("ReadType", ExpectedType);
-        }
-#endif
-    }
-}
-
-#endif

Některé soubory nejsou zobrazeny, neboť je v těchto rozdílových datech změněno mnoho souborů