TimeSpanSerializer.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #if !NO_RUNTIME
  2. using System;
  3. namespace ProtoBuf.Serializers
  4. {
  5. sealed class TimeSpanSerializer : IProtoSerializer
  6. {
  7. static readonly Type expectedType = typeof(TimeSpan);
  8. private readonly bool wellKnown;
  9. public TimeSpanSerializer(DataFormat dataFormat, ProtoBuf.Meta.TypeModel model)
  10. {
  11. wellKnown = dataFormat == DataFormat.WellKnown;
  12. }
  13. public Type ExpectedType => expectedType;
  14. bool IProtoSerializer.RequiresOldValue => false;
  15. bool IProtoSerializer.ReturnsValue => true;
  16. public object Read(object value, ProtoReader source)
  17. {
  18. if (wellKnown)
  19. {
  20. return BclHelpers.ReadDuration(source);
  21. }
  22. else
  23. {
  24. Helpers.DebugAssert(value == null); // since replaces
  25. return BclHelpers.ReadTimeSpan(source);
  26. }
  27. }
  28. public void Write(object value, ProtoWriter dest)
  29. {
  30. if (wellKnown)
  31. {
  32. BclHelpers.WriteDuration((TimeSpan)value, dest);
  33. }
  34. else
  35. {
  36. BclHelpers.WriteTimeSpan((TimeSpan)value, dest);
  37. }
  38. }
  39. #if FEAT_COMPILER
  40. void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
  41. {
  42. ctx.EmitWrite(ctx.MapType(typeof(BclHelpers)),
  43. wellKnown ? nameof(BclHelpers.WriteDuration) : nameof(BclHelpers.WriteTimeSpan), valueFrom);
  44. }
  45. void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
  46. {
  47. if (wellKnown) ctx.LoadValue(valueFrom);
  48. ctx.EmitBasicRead(ctx.MapType(typeof(BclHelpers)),
  49. wellKnown ? nameof(BclHelpers.ReadDuration) : nameof(BclHelpers.ReadTimeSpan),
  50. ExpectedType);
  51. }
  52. #endif
  53. }
  54. }
  55. #endif