Home | History | Annotate | Download | only in src
      1 // Copyright 2015 Google Inc. All rights reserved.
      2 //
      3 // Licensed under the Apache License, Version 2.0 (the "License");
      4 // you may not use this file except in compliance with the License.
      5 // You may obtain a copy of the License at
      6 //
      7 //     http://www.apache.org/licenses/LICENSE-2.0
      8 //
      9 // Unless required by applicable law or agreed to in writing, software
     10 // distributed under the License is distributed on an "AS IS" BASIS,
     11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     12 // See the License for the specific language governing permissions and
     13 // limitations under the License.
     14 
     15 #include "check.h"
     16 #include "re.h"
     17 
     18 namespace benchmark {
     19 
     20 Regex::Regex() : init_(false) { }
     21 
     22 bool Regex::Init(const std::string& spec, std::string* error) {
     23   int ec = regcomp(&re_, spec.c_str(), REG_EXTENDED | REG_NOSUB);
     24   if (ec != 0) {
     25     if (error) {
     26       size_t needed = regerror(ec, &re_, nullptr, 0);
     27       char* errbuf = new char[needed];
     28       regerror(ec, &re_, errbuf, needed);
     29 
     30       // regerror returns the number of bytes necessary to null terminate
     31       // the string, so we move that when assigning to error.
     32       CHECK_NE(needed, 0);
     33       error->assign(errbuf, needed - 1);
     34 
     35       delete[] errbuf;
     36     }
     37 
     38     return false;
     39   }
     40 
     41   init_ = true;
     42   return true;
     43 }
     44 
     45 Regex::~Regex() {
     46   if (init_) {
     47     regfree(&re_);
     48   }
     49 }
     50 
     51 bool Regex::Match(const std::string& str) {
     52   if (!init_) {
     53     return false;
     54   }
     55 
     56   return regexec(&re_, str.c_str(), 0, nullptr, 0) == 0;
     57 }
     58 
     59 }  // end namespace benchmark
     60