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