TupleSerializer.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. #if !NO_RUNTIME
  2. using System;
  3. using System.Reflection;
  4. using ProtoBuf.Meta;
  5. namespace ProtoBuf.Serializers
  6. {
  7. sealed class TupleSerializer : IProtoTypeSerializer
  8. {
  9. private readonly MemberInfo[] members;
  10. private readonly ConstructorInfo ctor;
  11. private IProtoSerializer[] tails;
  12. public TupleSerializer(RuntimeTypeModel model, ConstructorInfo ctor, MemberInfo[] members)
  13. {
  14. this.ctor = ctor ?? throw new ArgumentNullException(nameof(ctor));
  15. this.members = members ?? throw new ArgumentNullException(nameof(members));
  16. this.tails = new IProtoSerializer[members.Length];
  17. ParameterInfo[] parameters = ctor.GetParameters();
  18. for (int i = 0; i < members.Length; i++)
  19. {
  20. WireType wireType;
  21. Type finalType = parameters[i].ParameterType;
  22. Type itemType = null, defaultType = null;
  23. MetaType.ResolveListTypes(model, finalType, ref itemType, ref defaultType);
  24. Type tmp = itemType == null ? finalType : itemType;
  25. bool asReference = false;
  26. int typeIndex = model.FindOrAddAuto(tmp, false, true, false);
  27. if (typeIndex >= 0)
  28. {
  29. asReference = model[tmp].AsReferenceDefault;
  30. }
  31. IProtoSerializer tail = ValueMember.TryGetCoreSerializer(model, DataFormat.Default, tmp, out wireType, asReference, false, false, true), serializer;
  32. if (tail == null)
  33. {
  34. throw new InvalidOperationException("No serializer defined for type: " + tmp.FullName);
  35. }
  36. tail = new TagDecorator(i + 1, wireType, false, tail);
  37. if (itemType == null)
  38. {
  39. serializer = tail;
  40. }
  41. else
  42. {
  43. if (finalType.IsArray)
  44. {
  45. serializer = new ArrayDecorator(model, tail, i + 1, false, wireType, finalType, false, false);
  46. }
  47. else
  48. {
  49. serializer = ListDecorator.Create(model, finalType, defaultType, tail, i + 1, false, wireType, true, false, false);
  50. }
  51. }
  52. tails[i] = serializer;
  53. }
  54. }
  55. public bool HasCallbacks(Meta.TypeModel.CallbackType callbackType)
  56. {
  57. return false;
  58. }
  59. #if FEAT_COMPILER
  60. public void EmitCallback(Compiler.CompilerContext ctx, Compiler.Local valueFrom, Meta.TypeModel.CallbackType callbackType) { }
  61. #endif
  62. public Type ExpectedType => ctor.DeclaringType;
  63. void IProtoTypeSerializer.Callback(object value, Meta.TypeModel.CallbackType callbackType, SerializationContext context) { }
  64. object IProtoTypeSerializer.CreateInstance(ProtoReader source) { throw new NotSupportedException(); }
  65. private object GetValue(object obj, int index)
  66. {
  67. PropertyInfo prop;
  68. FieldInfo field;
  69. if ((prop = members[index] as PropertyInfo) != null)
  70. {
  71. if (obj == null)
  72. return Helpers.IsValueType(prop.PropertyType) ? Activator.CreateInstance(prop.PropertyType) : null;
  73. return prop.GetValue(obj, null);
  74. }
  75. else if ((field = members[index] as FieldInfo) != null)
  76. {
  77. if (obj == null)
  78. return Helpers.IsValueType(field.FieldType) ? Activator.CreateInstance(field.FieldType) : null;
  79. return field.GetValue(obj);
  80. }
  81. else
  82. {
  83. throw new InvalidOperationException();
  84. }
  85. }
  86. public object Read(object value, ProtoReader source)
  87. {
  88. object[] values = new object[members.Length];
  89. bool invokeCtor = false;
  90. if (value == null)
  91. {
  92. invokeCtor = true;
  93. }
  94. for (int i = 0; i < values.Length; i++)
  95. values[i] = GetValue(value, i);
  96. int field;
  97. while ((field = source.ReadFieldHeader()) > 0)
  98. {
  99. invokeCtor = true;
  100. if (field <= tails.Length)
  101. {
  102. IProtoSerializer tail = tails[field - 1];
  103. values[field - 1] = tails[field - 1].Read(tail.RequiresOldValue ? values[field - 1] : null, source);
  104. }
  105. else
  106. {
  107. source.SkipField();
  108. }
  109. }
  110. return invokeCtor ? ctor.Invoke(values) : value;
  111. }
  112. public void Write(object value, ProtoWriter dest)
  113. {
  114. for (int i = 0; i < tails.Length; i++)
  115. {
  116. object val = GetValue(value, i);
  117. if (val != null) tails[i].Write(val, dest);
  118. }
  119. }
  120. public bool RequiresOldValue => true;
  121. public bool ReturnsValue => false;
  122. Type GetMemberType(int index)
  123. {
  124. Type result = Helpers.GetMemberType(members[index]);
  125. if (result == null) throw new InvalidOperationException();
  126. return result;
  127. }
  128. bool IProtoTypeSerializer.CanCreateInstance() { return false; }
  129. #if FEAT_COMPILER
  130. public void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
  131. {
  132. using (Compiler.Local loc = ctx.GetLocalWithValue(ctor.DeclaringType, valueFrom))
  133. {
  134. for (int i = 0; i < tails.Length; i++)
  135. {
  136. Type type = GetMemberType(i);
  137. ctx.LoadAddress(loc, ExpectedType);
  138. if (members[i] is FieldInfo)
  139. {
  140. ctx.LoadValue((FieldInfo)members[i]);
  141. }
  142. else if (members[i] is PropertyInfo)
  143. {
  144. ctx.LoadValue((PropertyInfo)members[i]);
  145. }
  146. ctx.WriteNullCheckedTail(type, tails[i], null);
  147. }
  148. }
  149. }
  150. void IProtoTypeSerializer.EmitCreateInstance(Compiler.CompilerContext ctx) { throw new NotSupportedException(); }
  151. public void EmitRead(Compiler.CompilerContext ctx, Compiler.Local incoming)
  152. {
  153. using (Compiler.Local objValue = ctx.GetLocalWithValue(ExpectedType, incoming))
  154. {
  155. Compiler.Local[] locals = new Compiler.Local[members.Length];
  156. try
  157. {
  158. for (int i = 0; i < locals.Length; i++)
  159. {
  160. Type type = GetMemberType(i);
  161. bool store = true;
  162. locals[i] = new Compiler.Local(ctx, type);
  163. if (!Helpers.IsValueType(ExpectedType))
  164. {
  165. // value-types always read the old value
  166. if (Helpers.IsValueType(type))
  167. {
  168. switch (Helpers.GetTypeCode(type))
  169. {
  170. case ProtoTypeCode.Boolean:
  171. case ProtoTypeCode.Byte:
  172. case ProtoTypeCode.Int16:
  173. case ProtoTypeCode.Int32:
  174. case ProtoTypeCode.SByte:
  175. case ProtoTypeCode.UInt16:
  176. case ProtoTypeCode.UInt32:
  177. ctx.LoadValue(0);
  178. break;
  179. case ProtoTypeCode.Int64:
  180. case ProtoTypeCode.UInt64:
  181. ctx.LoadValue(0L);
  182. break;
  183. case ProtoTypeCode.Single:
  184. ctx.LoadValue(0.0F);
  185. break;
  186. case ProtoTypeCode.Double:
  187. ctx.LoadValue(0.0D);
  188. break;
  189. case ProtoTypeCode.Decimal:
  190. ctx.LoadValue(0M);
  191. break;
  192. case ProtoTypeCode.Guid:
  193. ctx.LoadValue(Guid.Empty);
  194. break;
  195. default:
  196. ctx.LoadAddress(locals[i], type);
  197. ctx.EmitCtor(type);
  198. store = false;
  199. break;
  200. }
  201. }
  202. else
  203. {
  204. ctx.LoadNullRef();
  205. }
  206. if (store)
  207. {
  208. ctx.StoreValue(locals[i]);
  209. }
  210. }
  211. }
  212. Compiler.CodeLabel skipOld = Helpers.IsValueType(ExpectedType)
  213. ? new Compiler.CodeLabel()
  214. : ctx.DefineLabel();
  215. if (!Helpers.IsValueType(ExpectedType))
  216. {
  217. ctx.LoadAddress(objValue, ExpectedType);
  218. ctx.BranchIfFalse(skipOld, false);
  219. }
  220. for (int i = 0; i < members.Length; i++)
  221. {
  222. ctx.LoadAddress(objValue, ExpectedType);
  223. if (members[i] is FieldInfo)
  224. {
  225. ctx.LoadValue((FieldInfo)members[i]);
  226. }
  227. else if (members[i] is PropertyInfo)
  228. {
  229. ctx.LoadValue((PropertyInfo)members[i]);
  230. }
  231. ctx.StoreValue(locals[i]);
  232. }
  233. if (!Helpers.IsValueType(ExpectedType)) ctx.MarkLabel(skipOld);
  234. using (Compiler.Local fieldNumber = new Compiler.Local(ctx, ctx.MapType(typeof(int))))
  235. {
  236. Compiler.CodeLabel @continue = ctx.DefineLabel(),
  237. processField = ctx.DefineLabel(),
  238. notRecognised = ctx.DefineLabel();
  239. ctx.Branch(@continue, false);
  240. Compiler.CodeLabel[] handlers = new Compiler.CodeLabel[members.Length];
  241. for (int i = 0; i < members.Length; i++)
  242. {
  243. handlers[i] = ctx.DefineLabel();
  244. }
  245. ctx.MarkLabel(processField);
  246. ctx.LoadValue(fieldNumber);
  247. ctx.LoadValue(1);
  248. ctx.Subtract(); // jump-table is zero-based
  249. ctx.Switch(handlers);
  250. // and the default:
  251. ctx.Branch(notRecognised, false);
  252. for (int i = 0; i < handlers.Length; i++)
  253. {
  254. ctx.MarkLabel(handlers[i]);
  255. IProtoSerializer tail = tails[i];
  256. Compiler.Local oldValIfNeeded = tail.RequiresOldValue ? locals[i] : null;
  257. ctx.ReadNullCheckedTail(locals[i].Type, tail, oldValIfNeeded);
  258. if (tail.ReturnsValue)
  259. {
  260. if (Helpers.IsValueType(locals[i].Type))
  261. {
  262. ctx.StoreValue(locals[i]);
  263. }
  264. else
  265. {
  266. Compiler.CodeLabel hasValue = ctx.DefineLabel(), allDone = ctx.DefineLabel();
  267. ctx.CopyValue();
  268. ctx.BranchIfTrue(hasValue, true); // interpret null as "don't assign"
  269. ctx.DiscardValue();
  270. ctx.Branch(allDone, true);
  271. ctx.MarkLabel(hasValue);
  272. ctx.StoreValue(locals[i]);
  273. ctx.MarkLabel(allDone);
  274. }
  275. }
  276. ctx.Branch(@continue, false);
  277. }
  278. ctx.MarkLabel(notRecognised);
  279. ctx.LoadReaderWriter();
  280. ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("SkipField"));
  281. ctx.MarkLabel(@continue);
  282. ctx.EmitBasicRead("ReadFieldHeader", ctx.MapType(typeof(int)));
  283. ctx.CopyValue();
  284. ctx.StoreValue(fieldNumber);
  285. ctx.LoadValue(0);
  286. ctx.BranchIfGreater(processField, false);
  287. }
  288. for (int i = 0; i < locals.Length; i++)
  289. {
  290. ctx.LoadValue(locals[i]);
  291. }
  292. ctx.EmitCtor(ctor);
  293. ctx.StoreValue(objValue);
  294. }
  295. finally
  296. {
  297. for (int i = 0; i < locals.Length; i++)
  298. {
  299. if (locals[i] != null)
  300. locals[i].Dispose(); // release for re-use
  301. }
  302. }
  303. }
  304. }
  305. #endif
  306. }
  307. }
  308. #endif