DateTimeSerializer.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #if !NO_RUNTIME
  2. using System;
  3. using System.Reflection;
  4. namespace ProtoBuf.Serializers
  5. {
  6. internal sealed class DateTimeSerializer : IProtoSerializer
  7. {
  8. private static readonly Type expectedType = typeof(DateTime);
  9. public Type ExpectedType => expectedType;
  10. bool IProtoSerializer.RequiresOldValue => false;
  11. bool IProtoSerializer.ReturnsValue => true;
  12. private readonly bool includeKind, wellKnown;
  13. public DateTimeSerializer(DataFormat dataFormat, ProtoBuf.Meta.TypeModel model)
  14. {
  15. wellKnown = dataFormat == DataFormat.WellKnown;
  16. includeKind = model?.SerializeDateTimeKind() == true;
  17. }
  18. public object Read(object value, ProtoReader source)
  19. {
  20. if (wellKnown)
  21. {
  22. return BclHelpers.ReadTimestamp(source);
  23. }
  24. else
  25. {
  26. Helpers.DebugAssert(value == null); // since replaces
  27. return BclHelpers.ReadDateTime(source);
  28. }
  29. }
  30. public void Write(object value, ProtoWriter dest)
  31. {
  32. if (wellKnown)
  33. BclHelpers.WriteTimestamp((DateTime)value, dest);
  34. else if (includeKind)
  35. BclHelpers.WriteDateTimeWithKind((DateTime)value, dest);
  36. else
  37. BclHelpers.WriteDateTime((DateTime)value, dest);
  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.WriteTimestamp)
  44. : includeKind ? nameof(BclHelpers.WriteDateTimeWithKind) : nameof(BclHelpers.WriteDateTime), valueFrom);
  45. }
  46. void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local entity)
  47. {
  48. if (wellKnown) ctx.LoadValue(entity);
  49. ctx.EmitBasicRead(ctx.MapType(typeof(BclHelpers)),
  50. wellKnown ? nameof(BclHelpers.ReadTimestamp) : nameof(BclHelpers.ReadDateTime),
  51. ExpectedType);
  52. }
  53. #endif
  54. }
  55. }
  56. #endif