Coverage Report

Created: 2025-08-29 06:22

/src/sentencepiece/third_party/absl/strings/str_replace.h
Line
Count
Source (jump to first uncovered line)
1
//
2
// Copyright 2017 The Abseil Authors.
3
//
4
// Licensed under the Apache License, Version 2.0 (the "License");
5
// you may not use this file except in compliance with the License.
6
// You may obtain a copy of the License at
7
//
8
//      http://www.apache.org/licenses/LICENSE-2.0
9
//
10
// Unless required by applicable law or agreed to in writing, software
11
// distributed under the License is distributed on an "AS IS" BASIS,
12
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
// See the License for the specific language governing permissions and
14
// limitations under the License.
15
//
16
#ifndef ABSL_STRINGS_STR_REPLACE_H_
17
#define ABSL_STRINGS_STR_REPLACE_H_
18
19
#include <string>
20
21
#include "third_party/absl/strings/string_view.h"
22
23
namespace absl {
24
25
inline void StringReplace(absl::string_view s, absl::string_view oldsub,
26
                          absl::string_view newsub, bool replace_all,
27
0
                          std::string *res) {
28
0
  if (oldsub.empty()) {
29
0
    res->append(s.data(), s.size());
30
0
    return;
31
0
  }
32
33
0
  absl::string_view::size_type start_pos = 0;
34
0
  do {
35
0
    const absl::string_view::size_type pos = s.find(oldsub, start_pos);
36
0
    if (pos == absl::string_view::npos) {
37
0
      break;
38
0
    }
39
0
    res->append(s.data() + start_pos, pos - start_pos);
40
0
    res->append(newsub.data(), newsub.size());
41
0
    start_pos = pos + oldsub.size();
42
0
  } while (replace_all);
43
0
  res->append(s.data() + start_pos, s.size() - start_pos);
44
0
}
45
46
inline std::string StringReplace(absl::string_view s, absl::string_view oldsub,
47
0
                                 absl::string_view newsub, bool replace_all) {
48
0
  std::string ret;
49
0
  StringReplace(s, oldsub, newsub, replace_all, &ret);
50
0
  return ret;
51
0
}
52
53
inline std::string StrReplaceAll(
54
    absl::string_view s,
55
    const std::vector<std::pair<absl::string_view, absl::string_view>>
56
0
        &patterns) {
57
0
  std::string prev(s.data(), s.size());
58
0
  std::string result;
59
0
  for (const auto &it : patterns) {
60
0
    result.clear();
61
0
    StringReplace(prev, it.first, it.second, true, &result);
62
0
    prev = result;
63
0
  }
64
0
  return result;
65
0
}
66
67
}  // namespace absl
68
#endif  // ABSL_STRINGS_STR_REPLACE_H_