@@ -22,10 +22,21 @@ public PrerenderComponentApplicationStore(string existingState)
22
22
if ( existingState is null )
23
23
{
24
24
throw new ArgumentNullException ( nameof ( existingState ) ) ;
25
- }
25
+ }
26
26
27
- ExistingState = JsonSerializer . Deserialize < Dictionary < string , ReadOnlySequence < byte > > > ( Convert . FromBase64String ( existingState ) ) ??
28
- throw new ArgumentException ( nameof ( existingState ) ) ;
27
+ var state = JsonSerializer . Deserialize < Dictionary < string , byte [ ] > > ( Convert . FromBase64String ( existingState ) ) ;
28
+ if ( state == null )
29
+ {
30
+ throw new ArgumentException ( "Could not deserialize state correctly" , nameof ( existingState ) ) ;
31
+ }
32
+
33
+ var stateDictionary = new Dictionary < string , ReadOnlySequence < byte > > ( ) ;
34
+ foreach ( var ( key , value ) in state )
35
+ {
36
+ stateDictionary . Add ( key , new ReadOnlySequence < byte > ( value ) ) ;
37
+ }
38
+
39
+ ExistingState = stateDictionary ;
29
40
}
30
41
31
42
#nullable enable
@@ -41,7 +52,37 @@ public Task<IDictionary<string, ReadOnlySequence<byte>>> GetPersistedStateAsync(
41
52
42
53
protected virtual byte [ ] SerializeState ( IReadOnlyDictionary < string , ReadOnlySequence < byte > > state )
43
54
{
44
- return JsonSerializer . SerializeToUtf8Bytes ( state ) ;
55
+ // System.Text.Json doesn't support serializing ReadonlySequence<byte> so we need to buffer
56
+ // the data with a memory pool here. We will change our serialization strategy in the future here
57
+ // so that we can avoid this step.
58
+ var pool = MemoryPool < byte > . Shared ;
59
+ var memory = new List < IMemoryOwner < byte > > ( ) ;
60
+ var serialization = new Dictionary < string , Memory < byte > > ( ) ;
61
+ try
62
+ {
63
+ foreach ( var ( key , value ) in state )
64
+ {
65
+ IMemoryOwner < byte > buffer = null ;
66
+ if ( value . Length < pool . MaxBufferSize )
67
+ {
68
+ buffer = pool . Rent ( ( int ) value . Length ) ;
69
+ memory . Add ( buffer ) ;
70
+ value . CopyTo ( buffer . Memory . Span . Slice ( 0 , ( int ) value . Length ) ) ;
71
+ }
72
+
73
+ serialization . Add ( key , buffer != null ? buffer . Memory . Slice ( 0 , ( int ) value . Length ) : value . ToArray ( ) ) ;
74
+ }
75
+
76
+ return JsonSerializer . SerializeToUtf8Bytes ( serialization , JsonSerializerOptionsProvider . Options ) ;
77
+ }
78
+ finally
79
+ {
80
+ serialization . Clear ( ) ;
81
+ foreach ( var item in memory )
82
+ {
83
+ item . Dispose ( ) ;
84
+ }
85
+ }
45
86
}
46
87
47
88
public Task PersistStateAsync ( IReadOnlyDictionary < string , ReadOnlySequence < byte > > state )
0 commit comments