aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/containers/comptrie/pattern_searcher.h
blob: caab51dc1c52d9ed183ce4c35f0493566ca34a47 (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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
#pragma once

#include "comptrie_builder.h"
#include "comptrie_trie.h"
#include "comptrie_impl.h"
#include <library/cpp/packers/packers.h>

#include <util/system/yassert.h>
#include <util/generic/vector.h>
#include <util/generic/deque.h>
#include <util/stream/str.h>

// Aho-Corasick algorithm implementation using CompactTrie implementation of Sedgewick's T-trie

namespace NCompactTrie {
    struct TSuffixLink {
        ui64 NextSuffixOffset;
        ui64 NextSuffixWithDataOffset;

        TSuffixLink(ui64 nextSuffixOffset = 0, ui64 nextSuffixWithDataOffset = 0)
            : NextSuffixOffset(nextSuffixOffset)
            , NextSuffixWithDataOffset(nextSuffixWithDataOffset)
        {
        }
    };

    const size_t FLAGS_SIZE = sizeof(char);
    const size_t SYMBOL_SIZE = sizeof(char);
};

template <class T = char, class D = ui64, class S = TCompactTriePacker<D>>
class TCompactPatternSearcherBuilder : protected TCompactTrieBuilder<T, D, S> {
public:
    typedef T TSymbol;
    typedef D TData;
    typedef S TPacker;

    typedef typename TCompactTrieKeySelector<TSymbol>::TKey TKey;
    typedef typename TCompactTrieKeySelector<TSymbol>::TKeyBuf TKeyBuf;

    typedef TCompactTrieBuilder<T, D, S> TBase;

public:
    TCompactPatternSearcherBuilder() {
        TBase::Impl = MakeHolder<TCompactPatternSearcherBuilderImpl>();
    }

    bool Add(const TSymbol* key, size_t keyLength, const TData& value) {
        return TBase::Impl->AddEntry(key, keyLength, value);
    }
    bool Add(const TKeyBuf& key, const TData& value) {
        return Add(key.data(), key.size(), value);
    }

    bool Find(const TSymbol* key, size_t keyLength, TData* value) const {
        return TBase::Impl->FindEntry(key, keyLength, value);
    }
    bool Find(const TKeyBuf& key, TData* value = nullptr) const {
        return Find(key.data(), key.size(), value);
    }

    size_t Save(IOutputStream& os) const {
        size_t trieSize = TBase::Impl->MeasureByteSize();
        TBufferOutput serializedTrie(trieSize);
        TBase::Impl->Save(serializedTrie);

        auto serializedTrieBuffer = serializedTrie.Buffer();
        CalculateSuffixLinks(
            serializedTrieBuffer.Data(),
            serializedTrieBuffer.Data() + serializedTrieBuffer.Size()
        );

        os.Write(serializedTrieBuffer.Data(), serializedTrieBuffer.Size());
        return trieSize;
    }

    TBlob Save() const {
        TBufferStream buffer;
        Save(buffer);
        return TBlob::FromStream(buffer);
    }

    size_t SaveToFile(const TString& fileName) const {
        TFileOutput out(fileName);
        return Save(out);
    }

    size_t MeasureByteSize() const {
        return TBase::Impl->MeasureByteSize();
    }

private:
    void CalculateSuffixLinks(char* trieStart, const char* trieEnd) const;

protected:
    class TCompactPatternSearcherBuilderImpl : public TBase::TCompactTrieBuilderImpl {
    public:
        typedef typename TBase::TCompactTrieBuilderImpl TImplBase;

        TCompactPatternSearcherBuilderImpl(
            TCompactTrieBuilderFlags flags = CTBF_NONE,
            TPacker packer = TPacker(),
            IAllocator* alloc = TDefaultAllocator::Instance()
        ) : TImplBase(flags, packer, alloc) {
        }

        ui64 ArcMeasure(
            const typename TImplBase::TArc* arc,
            size_t leftSize,
            size_t rightSize
        ) const override {
            using namespace NCompactTrie;

            size_t coreSize = SYMBOL_SIZE + FLAGS_SIZE +
                sizeof(TSuffixLink) +
                this->NodeMeasureLeafValue(arc->Node);
            size_t treeSize = this->NodeMeasureSubtree(arc->Node);

            if (arc->Label.Length() > 0)
                treeSize += (SYMBOL_SIZE + FLAGS_SIZE + sizeof(TSuffixLink)) *
                    (arc->Label.Length() - 1);

            // Triple measurements are needed because the space needed to store the offset
            // shall be added to the offset itself. Hence three iterations.
            size_t leftOffsetSize = 0;
            size_t rightOffsetSize = 0;
            for (size_t iteration = 0; iteration < 3; ++iteration) {
                leftOffsetSize = leftSize ? MeasureOffset(
                    coreSize + treeSize + leftOffsetSize + rightOffsetSize) : 0;
                rightOffsetSize = rightSize ? MeasureOffset(
                    coreSize + treeSize + leftSize + leftOffsetSize + rightOffsetSize) : 0;
            }

            coreSize += leftOffsetSize + rightOffsetSize;
            arc->LeftOffset = leftSize ? coreSize + treeSize : 0;
            arc->RightOffset = rightSize ? coreSize + treeSize + leftSize : 0;

            return coreSize + treeSize + leftSize + rightSize;
        }

        ui64 ArcSaveSelf(const typename TImplBase::TArc* arc, IOutputStream& os) const override {
            using namespace NCompactTrie;

            ui64 written = 0;

            size_t leftOffsetSize = MeasureOffset(arc->LeftOffset);
            size_t rightOffsetSize = MeasureOffset(arc->RightOffset);

            size_t labelLen = arc->Label.Length();

            for (size_t labelPos = 0; labelPos < labelLen; ++labelPos) {
                char flags = 0;

                if (labelPos == 0) {
                    flags |= (leftOffsetSize << MT_LEFTSHIFT);
                    flags |= (rightOffsetSize << MT_RIGHTSHIFT);
                }

                if (labelPos == labelLen - 1) {
                    if (arc->Node->IsFinal())
                        flags |= MT_FINAL;
                    if (!arc->Node->IsLast())
                        flags |= MT_NEXT;
                } else {
                    flags |= MT_NEXT;
                }

                os.Write(&flags, 1);
                os.Write(&arc->Label.AsCharPtr()[labelPos], 1);
                written += 2;

                TSuffixLink suffixlink;
                os.Write(&suffixlink, sizeof(TSuffixLink));
                written += sizeof(TSuffixLink);

                if (labelPos == 0) {
                    written += ArcSaveOffset(arc->LeftOffset, os);
                    written += ArcSaveOffset(arc->RightOffset, os);
                }
            }

            written += this->NodeSaveLeafValue(arc->Node, os);
            return written;
        }
    };
};


template <class T>
struct TPatternMatch {
    ui64 End;
    T Data;

    TPatternMatch(ui64 end, const T& data)
        : End(end)
        , Data(data)
    {
    }
};


template <class T = char, class D = ui64, class S = TCompactTriePacker<D>>
class TCompactPatternSearcher {
public:
    typedef T TSymbol;
    typedef D TData;
    typedef S TPacker;

    typedef typename TCompactTrieKeySelector<TSymbol>::TKey TKey;
    typedef typename TCompactTrieKeySelector<TSymbol>::TKeyBuf TKeyBuf;

    typedef TCompactTrie<TSymbol, TData, TPacker> TTrie;
public:
    TCompactPatternSearcher()
    {
    }

    explicit TCompactPatternSearcher(const TBlob& data)
        : Trie(data)
    {
    }

    TCompactPatternSearcher(const char* data, size_t size)
        : Trie(data, size)
    {
    }

    TVector<TPatternMatch<TData>> SearchMatches(const TSymbol* text, size_t textSize) const;
    TVector<TPatternMatch<TData>> SearchMatches(const TKeyBuf& text) const {
        return SearchMatches(text.data(), text.size());
    }
private:
    TTrie Trie;
};

////////////////////
// Implementation //
////////////////////

namespace {

template <class TData, class TPacker>
char ReadNode(
    char* nodeStart,
    char*& leftSibling,
    char*& rightSibling,
    char*& directChild,
    NCompactTrie::TSuffixLink*& suffixLink,
    TPacker packer = TPacker()
) {
    char* dataPos = nodeStart;
    char flags = *(dataPos++);

    Y_ASSERT(!NCompactTrie::IsEpsilonLink(flags)); // Epsilon links are not allowed

    char label = *(dataPos++);

    suffixLink = (NCompactTrie::TSuffixLink*)dataPos;
    dataPos += sizeof(NCompactTrie::TSuffixLink);

    { // Left branch
        size_t offsetLength = NCompactTrie::LeftOffsetLen(flags);
        size_t leftOffset = NCompactTrie::UnpackOffset(dataPos, offsetLength);
        leftSibling = leftOffset ? (nodeStart + leftOffset) : nullptr;

        dataPos += offsetLength;
    }


    { // Right branch
        size_t offsetLength = NCompactTrie::RightOffsetLen(flags);
        size_t rightOffset = NCompactTrie::UnpackOffset(dataPos, offsetLength);
        rightSibling = rightOffset ? (nodeStart + rightOffset) : nullptr;

        dataPos += offsetLength;
    }

    directChild = nullptr;
    if (flags & NCompactTrie::MT_NEXT) {
        directChild = dataPos;
        if (flags & NCompactTrie::MT_FINAL) {
            directChild += packer.SkipLeaf(directChild);
        }
    }

    return label;
}

template <class TData, class TPacker>
char ReadNodeConst(
    const char* nodeStart,
    const char*& leftSibling,
    const char*& rightSibling,
    const char*& directChild,
    const char*& data,
    NCompactTrie::TSuffixLink& suffixLink,
    TPacker packer = TPacker()
) {
    const char* dataPos = nodeStart;
    char flags = *(dataPos++);

    Y_ASSERT(!NCompactTrie::IsEpsilonLink(flags)); // Epsilon links are not allowed

    char label = *(dataPos++);

    suffixLink = *((NCompactTrie::TSuffixLink*)dataPos);
    dataPos += sizeof(NCompactTrie::TSuffixLink);

    { // Left branch
        size_t offsetLength = NCompactTrie::LeftOffsetLen(flags);
        size_t leftOffset = NCompactTrie::UnpackOffset(dataPos, offsetLength);
        leftSibling = leftOffset ? (nodeStart + leftOffset) : nullptr;

        dataPos += offsetLength;
    }


    { // Right branch
        size_t offsetLength = NCompactTrie::RightOffsetLen(flags);
        size_t rightOffset = NCompactTrie::UnpackOffset(dataPos, offsetLength);
        rightSibling = rightOffset ? (nodeStart + rightOffset) : nullptr;

        dataPos += offsetLength;
    }

    data = nullptr;
    if (flags & NCompactTrie::MT_FINAL) {
        data = dataPos;
    }
    directChild = nullptr;
    if (flags & NCompactTrie::MT_NEXT) {
        directChild = dataPos;
        if (flags & NCompactTrie::MT_FINAL) {
            directChild += packer.SkipLeaf(directChild);
        }
    }

    return label;
}

Y_FORCE_INLINE bool Advance(
    const char*& dataPos,
    const char* const dataEnd,
    char label
) {
    if (dataPos == nullptr) {
        return false;
    }

    while (dataPos < dataEnd) {
        size_t offsetLength, offset;
        const char* startPos = dataPos;
        char flags = *(dataPos++);
        char symbol = *(dataPos++);
        dataPos += sizeof(NCompactTrie::TSuffixLink);

        // Left branch
        offsetLength = NCompactTrie::LeftOffsetLen(flags);
        if ((unsigned char)label < (unsigned char)symbol) {
            offset = NCompactTrie::UnpackOffset(dataPos, offsetLength);
            if (!offset)
                break;

            dataPos = startPos + offset;
            continue;
        }

        dataPos += offsetLength;

        // Right branch
        offsetLength = NCompactTrie::RightOffsetLen(flags);
        if ((unsigned char)label > (unsigned char)symbol) {
            offset = NCompactTrie::UnpackOffset(dataPos, offsetLength);
            if (!offset)
                break;

            dataPos = startPos + offset;
            continue;
        }

        dataPos = startPos;
        return true;
    }

    // if we got here, we're past the dataend - bail out ASAP
    dataPos = nullptr;
    return false;
}

} // anonymous

template <class T, class D, class S>
void TCompactPatternSearcherBuilder<T, D, S>::CalculateSuffixLinks(
    char* trieStart,
    const char* trieEnd
) const {
    struct TBfsElement {
        char* Node;
        const char* Parent;

        TBfsElement(char* node, const char* parent)
            : Node(node)
            , Parent(parent)
        {
        }
    };

    TDeque<TBfsElement> bfsQueue;
    if (trieStart && trieStart != trieEnd) {
        bfsQueue.emplace_back(trieStart, nullptr);
    }

    while (!bfsQueue.empty()) {
        auto front = bfsQueue.front();
        char* node = front.Node;
        const char* parent = front.Parent;
        bfsQueue.pop_front();

        char* leftSibling;
        char* rightSibling;
        char* directChild;
        NCompactTrie::TSuffixLink* suffixLink;

        char label = ReadNode<TData, TPacker>(
            node,
            leftSibling,
            rightSibling,
            directChild,
            suffixLink
        );

        const char* suffix;

        if (parent == nullptr) {
            suffix = node;
        } else {
            const char* parentOfSuffix = parent;
            const char* temp;
            do {
                NCompactTrie::TSuffixLink parentOfSuffixSuffixLink;

                ReadNodeConst<TData, TPacker>(
                    parentOfSuffix,
                    /*left*/temp,
                    /*right*/temp,
                    /*direct*/temp,
                    /*data*/temp,
                    parentOfSuffixSuffixLink
                );
                if (parentOfSuffixSuffixLink.NextSuffixOffset == 0) {
                    suffix = trieStart;
                    if (!Advance(suffix, trieEnd, label)) {
                        suffix = node;
                    }
                    break;
                }
                parentOfSuffix += parentOfSuffixSuffixLink.NextSuffixOffset;

                NCompactTrie::TSuffixLink tempSuffixLink;
                ReadNodeConst<TData, TPacker>(
                    parentOfSuffix,
                    /*left*/temp,
                    /*right*/temp,
                    /*direct*/suffix,
                    /*data*/temp,
                    tempSuffixLink
                );

                if (suffix == nullptr) {
                    continue;
                }
            } while (!Advance(suffix, trieEnd, label));
        }

        suffixLink->NextSuffixOffset = suffix - node;

        NCompactTrie::TSuffixLink suffixSuffixLink;
        const char* suffixData;
        const char* temp;
        ReadNodeConst<TData, TPacker>(
            suffix,
            /*left*/temp,
            /*right*/temp,
            /*direct*/temp,
            suffixData,
            suffixSuffixLink
        );
        suffixLink->NextSuffixWithDataOffset = suffix - node;
        if (suffixData == nullptr) {
            suffixLink->NextSuffixWithDataOffset += suffixSuffixLink.NextSuffixWithDataOffset;
        }

        if (directChild) {
            bfsQueue.emplace_back(directChild, node);
        }

        if (leftSibling) {
            bfsQueue.emplace_front(leftSibling, parent);
        }

        if (rightSibling) {
            bfsQueue.emplace_front(rightSibling, parent);
        }
    }
}


template<class T, class D, class S>
TVector<TPatternMatch<D>> TCompactPatternSearcher<T, D, S>::SearchMatches(
    const TSymbol* text,
    size_t textSize
) const {
    const char* temp;
    NCompactTrie::TSuffixLink tempSuffixLink;

    const auto& trieData = Trie.Data();
    const char* trieStart = trieData.AsCharPtr();
    size_t dataSize = trieData.Length();
    const char* trieEnd = trieStart + dataSize;

    const char* lastNode = nullptr;
    const char* currentSubtree = trieStart;

    TVector<TPatternMatch<TData>> matches;

    for (const TSymbol* position = text; position < text + textSize; ++position) {
        TSymbol symbol = *position;
        for (i64 i = (i64)NCompactTrie::ExtraBits<TSymbol>(); i >= 0; i -= 8) {
            char label = (char)(symbol >> i);

            // Find first suffix extendable by label
            while (true) {
                const char* nextLastNode = currentSubtree;
                if (Advance(nextLastNode, trieEnd, label)) {
                    lastNode = nextLastNode;
                    ReadNodeConst<TData, TPacker>(
                        lastNode,
                        /*left*/temp,
                        /*right*/temp,
                        currentSubtree,
                        /*data*/temp,
                        tempSuffixLink
                    );
                    break;
                } else {
                    if (lastNode == nullptr) {
                        break;
                    }
                }

                NCompactTrie::TSuffixLink suffixLink;
                ReadNodeConst<TData, TPacker>(
                    lastNode,
                    /*left*/temp,
                    /*right*/temp,
                    /*direct*/temp,
                    /*data*/temp,
                    suffixLink
                );
                if (suffixLink.NextSuffixOffset == 0) {
                    lastNode = nullptr;
                    currentSubtree = trieStart;
                    continue;
                }
                lastNode += suffixLink.NextSuffixOffset;
                ReadNodeConst<TData, TPacker>(
                    lastNode,
                    /*left*/temp,
                    /*right*/temp,
                    currentSubtree,
                    /*data*/temp,
                    tempSuffixLink
                );
            }

            // Iterate through all suffixes
            const char* suffix = lastNode;
            while (suffix != nullptr) {
                const char* nodeData;
                NCompactTrie::TSuffixLink suffixLink;
                ReadNodeConst<TData, TPacker>(
                    suffix,
                    /*left*/temp,
                    /*right*/temp,
                    /*direct*/temp,
                    nodeData,
                    suffixLink
                );
                if (nodeData != nullptr) {
                    TData data;
                    Trie.GetPacker().UnpackLeaf(nodeData, data);
                    matches.emplace_back(
                        position - text,
                        data
                    );
                }
                if (suffixLink.NextSuffixOffset == 0) {
                    break;
                }
                suffix += suffixLink.NextSuffixWithDataOffset;
            }
        }
    }

    return matches;
}