json.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using BeetleX;
  2. using BeetleX.Buffers;
  3. using SpanJson;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Text;
  7. using System.Text.Json;
  8. using System.Threading.Tasks;
  9. namespace PlatformBenchmarks
  10. {
  11. public partial class HttpHandler
  12. {
  13. private readonly static uint _jsonPayloadSize = (uint)System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(new JsonMessage { message = "Hello, World!" }, SerializerOptions).Length;
  14. private readonly static AsciiString _jsonPreamble =
  15. _headerContentLength + _jsonPayloadSize.ToString();
  16. private static readonly JsonSerializerOptions SerializerOptions = new JsonSerializerOptions();
  17. private static Utf8JsonWriter GetUtf8JsonWriter(PipeStream stream, HttpToken token)
  18. {
  19. var buffer = stream.CreateBufferWriter();
  20. if (token.Utf8JsonWriter == null)
  21. {
  22. token.Utf8JsonWriter = new Utf8JsonWriter(buffer, new JsonWriterOptions { SkipValidation = true });
  23. }
  24. var writer = token.Utf8JsonWriter;
  25. writer.Reset(buffer);
  26. return writer;
  27. }
  28. public ValueTask Json(PipeStream stream, HttpToken token, ISession session)
  29. {
  30. if (Program.Debug)
  31. {
  32. System.Text.Json.JsonSerializer.Serialize<JsonMessage>(GetUtf8JsonWriter(stream, token), new JsonMessage { message = "Hello, World!" }, SerializerOptions);
  33. }
  34. else
  35. {
  36. SpanJson.JsonSerializer.NonGeneric.Utf8.SerializeAsync(new JsonMessage { message = "Hello, World!" }, stream);
  37. }
  38. OnCompleted(stream, session, token);
  39. return ValueTask.CompletedTask;
  40. }
  41. }
  42. }