1 // Copyright 2018 The Fuchsia Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #include "trace-test-utils/squelch.h" 6 7 #include <fbl/string_buffer.h> 8 9 namespace trace_testing { 10 Create(const char * regex_str)11std::unique_ptr<Squelcher> Squelcher::Create(const char* regex_str) { 12 // We don't make any assumptions about the copyability of |regex_t|. 13 // Therefore we construct it in place. 14 auto squelcher = new Squelcher; 15 if (regcomp(&squelcher->regex_, regex_str, REG_EXTENDED | REG_NEWLINE) != 0) { 16 return nullptr; 17 } 18 return std::unique_ptr<Squelcher>(squelcher); 19 } 20 ~Squelcher()21Squelcher::~Squelcher() { 22 regfree(®ex_); 23 } 24 Squelch(const char * str)25fbl::String Squelcher::Squelch(const char* str) { 26 fbl::StringBuffer<1024u> buf; 27 const char* cur = str; 28 const char* end = str + strlen(str); 29 30 while (*cur) { 31 // size must be 1 + number of parenthesized subexpressions 32 size_t match_count = regex_.re_nsub + 1; 33 regmatch_t match[match_count]; 34 if (regexec(®ex_, cur, match_count, match, 0) != 0) { 35 buf.Append(cur, end - cur); 36 break; 37 } 38 size_t offset = 0u; 39 for (size_t i = 1; i < match_count; i++) { 40 if (match[i].rm_so == -1) 41 continue; 42 buf.Append(cur, match[i].rm_so - offset); 43 buf.Append("<>"); 44 cur += match[i].rm_eo - offset; 45 offset = match[i].rm_eo; 46 } 47 } 48 49 return buf; 50 } 51 52 } // namespace trace_testing 53