1 // Copyright 2010 The RE2 Authors.  All Rights Reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4 
5 #ifndef RE2_SET_H_
6 #define RE2_SET_H_
7 
8 #include <memory>
9 #include <string>
10 #include <utility>
11 #include <vector>
12 
13 #include "re2/re2.h"
14 
15 namespace re2 {
16 class Prog;
17 class Regexp;
18 }  // namespace re2
19 
20 namespace re2 {
21 
22 // An RE2::Set represents a collection of regexps that can
23 // be searched for simultaneously.
24 class RE2::Set {
25  public:
26   enum ErrorKind {
27     kNoError = 0,
28     kNotCompiled,   // The set is not compiled.
29     kOutOfMemory,   // The DFA ran out of memory.
30     kInconsistent,  // The result is inconsistent. This should never happen.
31   };
32 
33   struct ErrorInfo {
34     ErrorKind kind;
35   };
36 
37   Set(const RE2::Options& options, RE2::Anchor anchor);
38   ~Set();
39 
40   // Not copyable.
41   Set(const Set&) = delete;
42   Set& operator=(const Set&) = delete;
43   // Movable.
44   Set(Set&& other);
45   Set& operator=(Set&& other);
46 
47   // Adds pattern to the set using the options passed to the constructor.
48   // Returns the index that will identify the regexp in the output of Match(),
49   // or -1 if the regexp cannot be parsed.
50   // Indices are assigned in sequential order starting from 0.
51   // Errors do not increment the index; if error is not NULL, *error will hold
52   // the error message from the parser.
53   int Add(const StringPiece& pattern, std::string* error);
54 
55   // Compiles the set in preparation for matching.
56   // Returns false if the compiler runs out of memory.
57   // Add() must not be called again after Compile().
58   // Compile() must be called before Match().
59   bool Compile();
60 
61   // Returns true if text matches at least one of the regexps in the set.
62   // Fills v (if not NULL) with the indices of the matching regexps.
63   // Callers must not expect v to be sorted.
64   bool Match(const StringPiece& text, std::vector<int>* v) const;
65 
66   // As above, but populates error_info (if not NULL) when none of the regexps
67   // in the set matched. This can inform callers when DFA execution fails, for
68   // example, because they might wish to handle that case differently.
69   bool Match(const StringPiece& text, std::vector<int>* v,
70              ErrorInfo* error_info) const;
71 
72  private:
73   typedef std::pair<std::string, re2::Regexp*> Elem;
74 
75   RE2::Options options_;
76   RE2::Anchor anchor_;
77   std::vector<Elem> elem_;
78   bool compiled_;
79   int size_;
80   std::unique_ptr<re2::Prog> prog_;
81 };
82 
83 }  // namespace re2
84 
85 #endif  // RE2_SET_H_
86