You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 line
2.2 KiB

  1. using JT809.Protocol.JT809Enums;
  2. using JT809.Protocol.JT809Exceptions;
  3. using JT809.Protocol.JT809Extensions;
  4. using System;
  5. using System.Buffers;
  6. using System.Collections.Generic;
  7. using System.Text;
  8. namespace JT809.Protocol
  9. {
  10. public static class JT809Serializer
  11. {
  12. public static byte[] Serialize(JT809Package jT809Package)
  13. {
  14. var formatter = JT809FormatterExtensions.GetFormatter<JT809Package>();
  15. var pool = MemoryPool<byte>.Shared;
  16. IMemoryOwner<byte> buffer = pool.Rent(4096);
  17. try
  18. {
  19. var len = formatter.Serialize(buffer, 0, jT809Package);
  20. return buffer.Memory.Slice(0, len).ToArray();
  21. }
  22. finally
  23. {
  24. // 源码:System.Memory.MemoryPool
  25. // private static readonly MemoryPool<T> s_shared = new ArrayMemoryPool<T>();
  26. // 单例内存池 不需要手动释放资源
  27. buffer.Dispose();
  28. }
  29. }
  30. public static JT809Package Deserialize(ReadOnlySpan<byte> bytes)
  31. {
  32. var formatter = JT809FormatterExtensions.GetFormatter<JT809Package>();
  33. return formatter.Deserialize(bytes, out int readSize);
  34. }
  35. public static byte[] Serialize<T>(T obj)
  36. {
  37. var formatter = JT809FormatterExtensions.GetFormatter<T>();
  38. var pool = MemoryPool<byte>.Shared;
  39. IMemoryOwner<byte> buffer = pool.Rent(4096);
  40. try
  41. {
  42. var len = formatter.Serialize(buffer, 0, obj);
  43. return buffer.Memory.Slice(0, len).ToArray();
  44. }
  45. finally
  46. {
  47. // 源码:System.Memory.MemoryPool
  48. // private static readonly MemoryPool<T> s_shared = new ArrayMemoryPool<T>();
  49. // 单例内存池 不需要手动释放资源
  50. buffer.Dispose();
  51. }
  52. }
  53. public static T Deserialize<T>(ReadOnlySpan<byte> bytes)
  54. {
  55. var formatter = JT809FormatterExtensions.GetFormatter<T>();
  56. int readSize;
  57. return formatter.Deserialize(bytes, out readSize);
  58. }
  59. }
  60. }