aboutsummaryrefslogtreecommitdiff
path: root/libs/VNLib.Plugins.Sessions.Cache.Client/src/SessionDataSerialzer.cs
blob: 1d83f9c656c909ed27344da4932ac82299c3e5b6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
/*
* Copyright (c) 2023 Vaughn Nugent
* 
* Library: VNLib
* Package: VNLib.Plugins.Sessions.Cache.Client
* File: SessionDataSerialzer.cs 
*
* SessionDataSerialzer.cs is part of VNLib.Plugins.Sessions.Cache.Client which is part of the larger 
* VNLib collection of libraries and utilities.
*
* VNLib.Plugins.Sessions.Cache.Client is free software: you can redistribute it and/or modify 
* it under the terms of the GNU Affero General Public License as 
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* VNLib.Plugins.Sessions.Cache.Client is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program.  If not, see https://www.gnu.org/licenses/.
*/

using System;
using System.Text;
using System.Buffers;
using System.Collections.Generic;

using VNLib.Utils.Memory;
using VNLib.Utils.Extensions;
using VNLib.Data.Caching;

namespace VNLib.Plugins.Sessions.Cache.Client
{
    
    /// <summary>
    /// Very basic session data serializer memory optimized for key-value
    /// string pairs
    /// </summary>
    internal sealed class SessionDataSerialzer : ICacheObjectSerialzer, ICacheObjectDeserialzer
    {
        const string KV_DELIMITER = "\0\0";

        readonly int CharBufferSize;

        public SessionDataSerialzer(int charBufferSize)
        {
            CharBufferSize = charBufferSize;
        }

        object? ICacheObjectDeserialzer.Deserialze(Type type, ReadOnlySpan<byte> buffer)
        {
            if (!type.IsAssignableTo(typeof(IDictionary<string, string>)))
            {
                throw new NotSupportedException("This deserialzer only supports IDictionary<string,string>");
            }

            //Get char count from bin buffer
            int charCount = Encoding.UTF8.GetCharCount(buffer);

            //Alloc decode buffer
            using UnsafeMemoryHandle<char> charBuffer = MemoryUtil.UnsafeAllocNearestPage<char>(charCount, true);

            //decode chars
            Encoding.UTF8.GetChars(buffer, charBuffer.Span);

            //Alloc new dict to write strings to
            Dictionary<string, string> output = new(StringComparer.OrdinalIgnoreCase);

            //Reader to track position of char buffer
            ForwardOnlyReader<char> reader = new(charBuffer.Span[0..charCount]);

            //Read data from the object data buffer
            while (reader.WindowSize > 0)
            {
                //get index of next separator
                int sep = GetNextToken(ref reader);

                //No more separators are found, skip
                if (sep == -1)
                {
                    break;
                }

                //Get pointer to key before reading value
                ReadOnlySpan<char> key = reader.Window[0..sep];

                //Advance reader to next sequence
                reader.Advance(sep + KV_DELIMITER.Length);

                //Find next sepearator to recover the value
                sep = GetNextToken(ref reader);

                if (sep == -1)
                {
                    break;
                }

                //Store value
                ReadOnlySpan<char> value = reader.Window[0..sep];

                //Set the kvp in the dict
                output[key.ToString()] = value.ToString();

                //Advance reader again
                reader.Advance(sep + 2);
            }

            return output;
        }

        private static int GetNextToken(ref ForwardOnlyReader<char> reader) => reader.Window.IndexOf(KV_DELIMITER);

        void ICacheObjectSerialzer.Serialize<T>(T obj, IBufferWriter<byte> finiteWriter)
        {
            if(obj is not Dictionary<string, string> dict)
            {
                throw new NotSupportedException("Data type is not supported by this serializer");
            }
         
            //Alloc char buffer, sessions should be under 16k 
            using UnsafeMemoryHandle<char> charBuffer = MemoryUtil.UnsafeAllocNearestPage<char>(CharBufferSize);

            using Dictionary<string, string>.Enumerator e = dict.GetEnumerator();

            ForwardOnlyWriter<char> writer = new(charBuffer.Span);

            while (e.MoveNext())
            {
                KeyValuePair<string, string> element = e.Current;

                /*
                 * confim there is enough room in the writer, if there is not
                 * flush to the buffer writer
                 */
                if(element.Key.Length + element.Value.Length + 4 > writer.RemainingSize)
                {
                    //Flush to the output
                    Encoding.UTF8.GetBytes(writer.AsSpan(), finiteWriter);

                    //Reset the writer
                    writer.Reset();
                }

                //Add key/value elements
                writer.Append(element.Key);
                writer.Append(KV_DELIMITER);
                writer.Append(element.Value);
                writer.Append(KV_DELIMITER);               
            }

            //encode remaining data
            Encoding.UTF8.GetBytes(writer.AsSpan(), finiteWriter);
        }
    }
}