NetObjectSerializer.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #if !NO_RUNTIME
  2. using System;
  3. using ProtoBuf.Meta;
  4. #if FEAT_IKVM
  5. using Type = IKVM.Reflection.Type;
  6. using IKVM.Reflection;
  7. #else
  8. using System.Reflection;
  9. #endif
  10. namespace ProtoBuf.Serializers
  11. {
  12. sealed class NetObjectSerializer : IProtoSerializer
  13. {
  14. private readonly int key;
  15. private readonly Type type;
  16. private readonly BclHelpers.NetObjectOptions options;
  17. public NetObjectSerializer(TypeModel model, Type type, int key, BclHelpers.NetObjectOptions options)
  18. {
  19. bool dynamicType = (options & BclHelpers.NetObjectOptions.DynamicType) != 0;
  20. this.key = dynamicType ? -1 : key;
  21. this.type = dynamicType ? model.MapType(typeof(object)) : type;
  22. this.options = options;
  23. }
  24. public Type ExpectedType
  25. {
  26. get { return type; }
  27. }
  28. public bool ReturnsValue
  29. {
  30. get { return true; }
  31. }
  32. public bool RequiresOldValue
  33. {
  34. get { return true; }
  35. }
  36. #if !FEAT_IKVM
  37. public object Read(object value, ProtoReader source)
  38. {
  39. return BclHelpers.ReadNetObject(value, source, key, type == typeof(object) ? null : type, options);
  40. }
  41. public void Write(object value, ProtoWriter dest)
  42. {
  43. BclHelpers.WriteNetObject(value, dest, key, options);
  44. }
  45. #endif
  46. #if FEAT_COMPILER
  47. public void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
  48. {
  49. ctx.LoadValue(valueFrom);
  50. ctx.CastToObject(type);
  51. ctx.LoadReaderWriter();
  52. ctx.LoadValue(ctx.MapMetaKeyToCompiledKey(key));
  53. if (type == ctx.MapType(typeof(object))) ctx.LoadNullRef();
  54. else ctx.LoadValue(type);
  55. ctx.LoadValue((int)options);
  56. ctx.EmitCall(ctx.MapType(typeof(BclHelpers)).GetMethod("ReadNetObject"));
  57. ctx.CastFromObject(type);
  58. }
  59. public void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
  60. {
  61. ctx.LoadValue(valueFrom);
  62. ctx.CastToObject(type);
  63. ctx.LoadReaderWriter();
  64. ctx.LoadValue(ctx.MapMetaKeyToCompiledKey(key));
  65. ctx.LoadValue((int)options);
  66. ctx.EmitCall(ctx.MapType(typeof(BclHelpers)).GetMethod("WriteNetObject"));
  67. }
  68. #endif
  69. }
  70. }
  71. #endif