aboutsummaryrefslogtreecommitdiff
path: root/src/Ryujinx.Horizon/Sdk/Ngc/Detail/AhoCorasick.cs
blob: 6acb9be975ccafb215db68c193e609ca50b7eab0 (plain) (blame)
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
using System;
using System.Diagnostics;
using System.Text;

namespace Ryujinx.Horizon.Sdk.Ngc.Detail
{
    class AhoCorasick
    {
        public delegate bool MatchCallback(ReadOnlySpan<byte> text, int matchStartOffset, int matchEndOffset, int nodeId, ref MatchState state);
        public delegate bool MatchCallback<T>(ReadOnlySpan<byte> text, int matchStartOffset, int matchEndOffset, int nodeId, ref T state);

        private readonly SparseSet _wordMap = new();
        private readonly CompressedArray _wordLengths = new();
        private readonly SparseSet _multiWordMap = new();
        private readonly CompressedArray _multiWordIndices = new();
        private readonly SparseSet _nodeMap = new();
        private uint _nodesPerCharacter;
        private readonly Bp _bp = new();

        public bool Import(ref BinaryReader reader)
        {
            if (!_wordLengths.Import(ref reader) ||
                !_wordMap.Import(ref reader) ||
                !_multiWordIndices.Import(ref reader) ||
                !_multiWordMap.Import(ref reader))
            {
                return false;
            }

            if (!reader.Read(out _nodesPerCharacter))
            {
                return false;
            }

            return _nodeMap.Import(ref reader) && _bp.Import(ref reader);
        }

        public void Match(ReadOnlySpan<byte> utf8Text, MatchCallback callback, ref MatchState state)
        {
            int nodeId = 0;

            for (int index = 0; index < utf8Text.Length; index++)
            {
                long c = utf8Text[index];

                while (true)
                {
                    long nodeSparseIndex = _nodesPerCharacter * c + (uint)nodeId;
                    int nodePlainIndex = _nodeMap.Rank1(nodeSparseIndex);

                    if (nodePlainIndex != 0)
                    {
                        long foundNodeSparseIndex = _nodeMap.Select1Ex(nodePlainIndex - 1);

                        if (foundNodeSparseIndex > 0 && foundNodeSparseIndex == nodeSparseIndex)
                        {
                            nodeId = nodePlainIndex;

                            if (callback != null)
                            {
                                // Match full word.
                                if (_wordMap.Has(nodePlainIndex))
                                {
                                    int wordLength = _wordLengths[_wordMap.Rank1((uint)nodePlainIndex) - 1];
                                    int startIndex = index + 1 - wordLength;

                                    if (!callback(utf8Text, startIndex, index + 1, nodeId, ref state))
                                    {
                                        return;
                                    }
                                }

                                // If this is a phrase composed of multiple words, also match each sub-word.
                                while (_multiWordMap.Has(nodePlainIndex))
                                {
                                    nodePlainIndex = _multiWordIndices[_multiWordMap.Rank1((uint)nodePlainIndex) - 1];

                                    int wordLength = _wordMap.Has(nodePlainIndex) ? _wordLengths[_wordMap.Rank1(nodePlainIndex) - 1] : 0;
                                    int startIndex = index + 1 - wordLength;

                                    if (!callback(utf8Text, startIndex, index + 1, nodePlainIndex, ref state))
                                    {
                                        return;
                                    }
                                }
                            }

                            break;
                        }
                    }

                    if (nodeId == 0)
                    {
                        break;
                    }

                    int nodePos = _bp.ToPos(nodeId);
                    nodePos = _bp.Enclose(nodePos);
                    if (nodePos < 0)
                    {
                        return;
                    }

                    nodeId = _bp.ToNodeId(nodePos);
                }
            }
        }

        public void Match<T>(ReadOnlySpan<byte> utf8Text, MatchCallback<T> callback, ref T state)
        {
            int nodeId = 0;

            for (int index = 0; index < utf8Text.Length; index++)
            {
                long c = utf8Text[index];

                while (true)
                {
                    long nodeSparseIndex = _nodesPerCharacter * c + (uint)nodeId;
                    int nodePlainIndex = _nodeMap.Rank1(nodeSparseIndex);

                    if (nodePlainIndex != 0)
                    {
                        long foundNodeSparseIndex = _nodeMap.Select1Ex(nodePlainIndex - 1);

                        if (foundNodeSparseIndex > 0 && foundNodeSparseIndex == nodeSparseIndex)
                        {
                            nodeId = nodePlainIndex;

                            if (callback != null)
                            {
                                // Match full word.
                                if (_wordMap.Has(nodePlainIndex))
                                {
                                    int wordLength = _wordLengths[_wordMap.Rank1((uint)nodePlainIndex) - 1];
                                    int startIndex = index + 1 - wordLength;

                                    if (!callback(utf8Text, startIndex, index + 1, nodeId, ref state))
                                    {
                                        return;
                                    }
                                }

                                // If this is a phrase composed of multiple words, also match each sub-word.
                                while (_multiWordMap.Has(nodePlainIndex))
                                {
                                    nodePlainIndex = _multiWordIndices[_multiWordMap.Rank1((uint)nodePlainIndex) - 1];

                                    int wordLength = _wordMap.Has(nodePlainIndex) ? _wordLengths[_wordMap.Rank1(nodePlainIndex) - 1] : 0;
                                    int startIndex = index + 1 - wordLength;

                                    if (!callback(utf8Text, startIndex, index + 1, nodePlainIndex, ref state))
                                    {
                                        return;
                                    }
                                }
                            }

                            break;
                        }
                    }

                    if (nodeId == 0)
                    {
                        break;
                    }

                    int nodePos = _bp.ToPos(nodeId);
                    nodePos = _bp.Enclose(nodePos);
                    if (nodePos < 0)
                    {
                        return;
                    }

                    nodeId = _bp.ToNodeId(nodePos);
                }
            }
        }

        public string GetWordList(bool includeMultiWord = true)
        {
            // Storage must be large enough to fit the largest word in the dictionary.
            // Since this is only used for debugging, it's fine to increase the size manually if needed.
            StringBuilder sb = new();
            Span<byte> storage = new byte[1024];

            // Traverse trie from the root.
            GetWord(sb, storage, 0, 0, includeMultiWord);

            return sb.ToString();
        }

        private void GetWord(StringBuilder sb, Span<byte> storage, int storageOffset, int nodeId, bool includeMultiWord)
        {
            int characters = (int)((_nodeMap.RangeEndValue + _nodesPerCharacter - 1) / _nodesPerCharacter);

            for (int c = 0; c < characters; c++)
            {
                long nodeSparseIndex = _nodesPerCharacter * c + (uint)nodeId;
                int nodePlainIndex = _nodeMap.Rank1(nodeSparseIndex);

                if (nodePlainIndex != 0)
                {
                    long foundNodeSparseIndex = _nodeMap.Select1Ex(nodePlainIndex - 1);

                    if (foundNodeSparseIndex > 0 && foundNodeSparseIndex == nodeSparseIndex)
                    {
                        storage[storageOffset] = (byte)c;
                        int nextNodeId = nodePlainIndex;

                        if (_wordMap.Has(nodePlainIndex))
                        {
                            sb.AppendLine(Encoding.UTF8.GetString(storage[..(storageOffset + 1)]));

                            // Some basic validation to ensure we imported the dictionary properly.
                            int wordLength = _wordLengths[_wordMap.Rank1((uint)nodePlainIndex) - 1];

                            Debug.Assert(storageOffset + 1 == wordLength);
                        }

                        if (includeMultiWord)
                        {
                            int lastMultiWordIndex = 0;
                            string multiWord = "";

                            while (_multiWordMap.Has(nodePlainIndex))
                            {
                                nodePlainIndex = _multiWordIndices[_multiWordMap.Rank1((uint)nodePlainIndex) - 1];

                                int wordLength = _wordMap.Has(nodePlainIndex) ? _wordLengths[_wordMap.Rank1(nodePlainIndex) - 1] : 0;
                                int startIndex = storageOffset + 1 - wordLength;

                                multiWord += Encoding.UTF8.GetString(storage[lastMultiWordIndex..startIndex]) + " ";
                                lastMultiWordIndex = startIndex;
                            }

                            if (lastMultiWordIndex != 0)
                            {
                                multiWord += Encoding.UTF8.GetString(storage[lastMultiWordIndex..(storageOffset + 1)]);

                                sb.AppendLine(multiWord);
                            }
                        }

                        GetWord(sb, storage, storageOffset + 1, nextNodeId, includeMultiWord);
                    }
                }
            }
        }
    }
}