Replace StringPiece with std::string_view
StringPiece was almost an identical copy of std::string_view,
probably added before kati was compiled with C++17. Replace
it with std::string_view now that we're on C++17.
Some of the differences between StringPiece and std::string_view are:
- myStringPiece.AppendToString(myString) becomes
myString.append(myStringView)
- myStringPiece.as_string() becomes std::string(myStringView)
- string_view doesn't have .clear(), replaced with initializing a new
string_view
- myStringPiece.get(0) becomes myStringView.at(0), with added bounds
checking because string_view will throw if it's out of bounds while
StringPiece will return 0 instead.
- StringPiece's substr() will prevent both the starting and ending
indexes of the substring from going past the end of the StringPiece,
but string_view will only do that for the ending index, and throw
on out of bounds starting indicies.
- StringPiece could be initialized from a null char*, but string_view
will crash when given null.
The tests caught some of the runtime issues, but more were
caught by testing a locally compiled ckati in the android source tree.
diff --git a/.github/workflows/cpp-ci.yml b/.github/workflows/cpp-ci.yml
index 22dbc66..0e6dfdc 100644
--- a/.github/workflows/cpp-ci.yml
+++ b/.github/workflows/cpp-ci.yml
@@ -50,8 +50,6 @@
run: go test --ckati --ninja --all
- name: run ninja unit tests
run: ./ninja_test
- - name: run stringpiece unit tests
- run: ./string_piece_test
- name: run strutil unit tests
run: ./strutil_test
- name: run find unit tests
diff --git a/Makefile.ckati b/Makefile.ckati
index e86f15f..322d747 100644
--- a/Makefile.ckati
+++ b/Makefile.ckati
@@ -43,7 +43,6 @@
rule.cc \
stats.cc \
stmt.cc \
- string_piece.cc \
stringprintf.cc \
strutil.cc \
symtab.cc \
diff --git a/src/Android.bp b/src/Android.bp
index 0fa4159..99c3c69 100644
--- a/src/Android.bp
+++ b/src/Android.bp
@@ -52,7 +52,6 @@
"rule.cc",
"stats.cc",
"stmt.cc",
- "string_piece.cc",
"stringprintf.cc",
"strutil.cc",
"symtab.cc",
@@ -88,7 +87,6 @@
srcs: [
"find_test.cc",
"ninja_test.cc",
- "string_piece_test.cc",
"strutil_bench.cc",
"strutil_test.cc",
],
diff --git a/src/command.cc b/src/command.cc
index 6bed3e1..cc58616 100644
--- a/src/command.cc
+++ b/src/command.cc
@@ -36,7 +36,7 @@
virtual void AppendVar(Evaluator*, Value*) override { CHECK(false); }
- virtual StringPiece String() const override {
+ virtual std::string_view String() const override {
ERROR("$(value %s) is not implemented yet", sym_);
return "";
}
@@ -104,7 +104,7 @@
}
void AutoHatVar::Eval(Evaluator*, std::string* s) const {
- std::unordered_set<StringPiece> seen;
+ std::unordered_set<std::string_view> seen;
WordWriter ww(s);
for (Symbol ai : ce_->current_dep_node()->actual_inputs) {
if (seen.insert(ai.str()).second)
@@ -124,11 +124,11 @@
if (!n->output_pattern.IsValid())
return;
Pattern pat(n->output_pattern.str());
- pat.Stem(n->output.str()).AppendToString(s);
+ s->append(pat.Stem(n->output.str()));
}
void AutoQuestionVar::Eval(Evaluator* ev, std::string* s) const {
- std::unordered_set<StringPiece> seen;
+ std::unordered_set<std::string_view> seen;
if (ev->avoid_io()) {
// Check timestamps using the shell at the start of rule execution
@@ -171,7 +171,7 @@
std::string buf;
wrapped_->Eval(ev, &buf);
WordWriter ww(s);
- for (StringPiece tok : WordScanner(buf)) {
+ for (std::string_view tok : WordScanner(buf)) {
ww.Write(Dirname(tok));
}
}
@@ -180,15 +180,15 @@
std::string buf;
wrapped_->Eval(ev, &buf);
WordWriter ww(s);
- for (StringPiece tok : WordScanner(buf)) {
+ for (std::string_view tok : WordScanner(buf)) {
ww.Write(Basename(tok));
}
}
-void ParseCommandPrefixes(StringPiece* s, bool* echo, bool* ignore_error) {
+void ParseCommandPrefixes(std::string_view* s, bool* echo, bool* ignore_error) {
*s = TrimLeftSpace(*s);
while (true) {
- char c = s->get(0);
+ char c = s->empty() ? 0 : s->front();
if (c == '@') {
*echo = false;
} else if (c == '-') {
@@ -233,7 +233,7 @@
for (Value* v : n.cmds) {
ev_->set_loc(v->Location());
const std::string&& cmds_buf = v->Eval(ev_);
- StringPiece cmds = cmds_buf;
+ std::string_view cmds = cmds_buf;
bool global_echo = !g_flags.is_silent_mode;
bool global_ignore_error = false;
ParseCommandPrefixes(&cmds, &global_echo, &global_ignore_error);
@@ -244,7 +244,7 @@
size_t index = FindEndOfLine(cmds, 0, &lf_cnt);
if (index == cmds.size())
index = std::string::npos;
- StringPiece cmd = TrimLeftSpace(cmds.substr(0, index));
+ std::string_view cmd = TrimLeftSpace(cmds.substr(0, index));
cmds = cmds.substr(index + 1);
bool echo = global_echo;
@@ -253,7 +253,7 @@
if (!cmd.empty()) {
Command& command = result.emplace_back(n.output);
- command.cmd = cmd.as_string();
+ command.cmd = std::string(cmd);
command.echo = echo;
command.ignore_error = ignore_error;
}
diff --git a/src/dep.cc b/src/dep.cc
index 481711e..5ba59fe 100644
--- a/src/dep.cc
+++ b/src/dep.cc
@@ -73,9 +73,9 @@
class RuleTrie {
struct Entry {
- Entry(const Rule* r, StringPiece s) : rule(r), suffix(s) {}
+ Entry(const Rule* r, std::string_view s) : rule(r), suffix(s) {}
const Rule* rule;
- StringPiece suffix;
+ std::string_view suffix;
};
public:
@@ -85,7 +85,7 @@
delete p.second;
}
- void Add(StringPiece name, const Rule* rule) {
+ void Add(std::string_view name, const Rule* rule) {
if (name.empty() || name[0] == '%') {
rules_.push_back(Entry(rule, name));
return;
@@ -98,7 +98,7 @@
p.first->second->Add(name.substr(1), rule);
}
- void Get(StringPiece name, std::vector<const Rule*>* rules) const {
+ void Get(std::string_view name, std::vector<const Rule*>* rules) const {
for (const Entry& ent : rules_) {
if ((ent.suffix.empty() && name.empty()) ||
HasSuffix(name, ent.suffix.substr(1))) {
@@ -128,7 +128,7 @@
bool IsSuffixRule(Symbol output) {
if (output.empty() || !IsSpecialTarget(output))
return false;
- const StringPiece rest = StringPiece(output.str()).substr(1);
+ const std::string_view rest = std::string_view(output.str()).substr(1);
size_t dot_index = rest.find('.');
// If there is only a single dot or the third dot, this is not a
// suffix rule.
@@ -438,7 +438,7 @@
std::string implicit_outputs;
var->Eval(ev_, &implicit_outputs);
- for (StringPiece output : WordScanner(implicit_outputs)) {
+ for (std::string_view output : WordScanner(implicit_outputs)) {
Symbol sym = Intern(TrimLeadingCurdir(output));
rules_[sym].SetImplicitOutput(sym, p.first, &p.second);
p.second.AddImplicitOutput(sym, &rules_[sym]);
@@ -450,7 +450,7 @@
std::string validations;
var->Eval(ev_, &validations);
- for (StringPiece validation : WordScanner(validations)) {
+ for (std::string_view validation : WordScanner(validations)) {
Symbol sym = Intern(TrimLeadingCurdir(validation));
p.second.AddValidation(sym);
}
@@ -461,7 +461,7 @@
std::string symlink_outputs;
var->Eval(ev_, &symlink_outputs);
- for (StringPiece output : WordScanner(symlink_outputs)) {
+ for (std::string_view output : WordScanner(symlink_outputs)) {
Symbol sym = Intern(TrimLeadingCurdir(output));
p.second.AddSymlinkOutput(sym);
}
@@ -480,11 +480,11 @@
output.c_str());
}
- const StringPiece rest = StringPiece(output.str()).substr(1);
+ const std::string_view rest = std::string_view(output.str()).substr(1);
size_t dot_index = rest.find('.');
- StringPiece input_suffix = rest.substr(0, dot_index);
- StringPiece output_suffix = rest.substr(dot_index + 1);
+ std::string_view input_suffix = rest.substr(0, dot_index);
+ std::string_view output_suffix = rest.substr(dot_index + 1);
std::shared_ptr<Rule> r = std::make_shared<Rule>(*rule);
r->inputs.clear();
r->inputs.push_back(Intern(input_suffix));
@@ -638,8 +638,8 @@
return true;
}
- StringPiece output_suffix = GetExt(output.str());
- if (output_suffix.get(0) != '.')
+ std::string_view output_suffix = GetExt(output.str());
+ if (output_suffix.empty() || output_suffix.front() != '.')
return rule_merger != nullptr;
output_suffix = output_suffix.substr(1);
@@ -760,7 +760,7 @@
if (!g_flags.writable.empty() && !n->is_phony) {
bool found = false;
for (const auto& w : g_flags.writable) {
- if (StringPiece(output.str()).starts_with(w)) {
+ if (HasPrefix(output.str(), w)) {
found = true;
break;
}
@@ -797,7 +797,7 @@
if (!g_flags.writable.empty() && !n->is_phony) {
bool found = false;
for (const auto& w : g_flags.writable) {
- if (StringPiece(output.str()).starts_with(w)) {
+ if (HasPrefix(output.str(), w)) {
found = true;
break;
}
@@ -928,7 +928,8 @@
std::unique_ptr<Vars> cur_rule_vars_;
std::unique_ptr<RuleTrie> implicit_rules_;
- typedef std::unordered_map<StringPiece, std::vector<std::shared_ptr<Rule>>>
+ typedef std::unordered_map<std::string_view,
+ std::vector<std::shared_ptr<Rule>>>
SuffixRuleMap;
SuffixRuleMap suffix_rules_;
diff --git a/src/dep.h b/src/dep.h
index aff8d94..f801ef2 100644
--- a/src/dep.h
+++ b/src/dep.h
@@ -16,11 +16,11 @@
#define DEP_H_
#include <string>
+#include <string_view>
#include <unordered_map>
#include <vector>
#include "loc.h"
-#include "string_piece.h"
#include "symtab.h"
class Evaluator;
diff --git a/src/eval.cc b/src/eval.cc
index 7dad261..84de857 100644
--- a/src/eval.cc
+++ b/src/eval.cc
@@ -237,7 +237,7 @@
Var* Evaluator::EvalRHS(Symbol lhs,
Value* rhs_v,
- StringPiece orig_rhs,
+ std::string_view orig_rhs,
AssignOp op,
bool is_override,
bool* needs_assign) {
@@ -320,8 +320,8 @@
for (auto const& name : WordScanner(rhs)) {
Var* var = Intern(name).GetGlobalVar();
if (!var->IsDefined()) {
- Error(
- StringPrintf("*** unknown variable: %s", name.as_string().c_str()));
+ Error(StringPrintf("*** unknown variable: %s",
+ std::string(name).c_str()));
}
var->SetReadOnly();
}
@@ -352,18 +352,18 @@
// <before_term> <term> <after_term>
// parses <before_term> into Symbol instances until encountering ':'
// Returns the remainder of <before_term>.
-static StringPiece ParseRuleTargets(const Loc& loc,
- const StringPiece& before_term,
- std::vector<Symbol>* targets,
- bool* is_pattern_rule) {
+static std::string_view ParseRuleTargets(const Loc& loc,
+ const std::string_view& before_term,
+ std::vector<Symbol>* targets,
+ bool* is_pattern_rule) {
size_t pos = before_term.find(':');
if (pos == std::string::npos) {
ERROR_LOC(loc, "*** missing separator.");
}
- StringPiece targets_string = before_term.substr(0, pos);
+ std::string_view targets_string = before_term.substr(0, pos);
size_t pattern_rule_count = 0;
for (auto const& word : WordScanner(targets_string)) {
- StringPiece target = TrimLeadingCurdir(word);
+ std::string_view target = TrimLeadingCurdir(word);
targets->push_back(Intern(target));
if (Rule::IsPatternRule(target)) {
++pattern_rule_count;
@@ -401,7 +401,8 @@
for (auto const& name : WordScanner(vars_list_string)) {
Var* var = current_scope_->Lookup(Intern(name));
if (!var->IsDefined()) {
- Error(StringPrintf("*** unknown variable: %s", name.as_string().c_str()));
+ Error(
+ StringPrintf("*** unknown variable: %s", std::string(name).c_str()));
}
var->SetReadOnly();
}
@@ -409,10 +410,10 @@
void Evaluator::EvalRuleSpecificAssign(const std::vector<Symbol>& targets,
const RuleStmt* stmt,
- const StringPiece& after_targets,
+ const std::string_view& after_targets,
size_t separator_pos) {
- StringPiece var_name;
- StringPiece rhs_string;
+ std::string_view var_name;
+ std::string_view rhs_string;
AssignOp assign_op;
ParseAssignStatement(after_targets, separator_pos, &var_name, &rhs_string,
&assign_op);
@@ -428,7 +429,8 @@
if (rhs_string.empty()) {
rhs = stmt->rhs;
} else if (stmt->rhs) {
- StringPiece sep(stmt->sep == RuleStmt::SEP_SEMICOLON ? " ; " : " = ");
+ std::string_view sep(stmt->sep == RuleStmt::SEP_SEMICOLON ? " ; "
+ : " = ");
rhs = Value::NewExpr(loc_, Value::NewLiteral(rhs_string),
Value::NewLiteral(sep), stmt->rhs);
} else {
@@ -440,8 +442,8 @@
MarkVarsReadonly(rhs);
} else {
bool needs_assign;
- Var* rhs_var = EvalRHS(var_sym, rhs, StringPiece("*TODO*"), assign_op,
- false, &needs_assign);
+ Var* rhs_var = EvalRHS(var_sym, rhs, std::string_view("*TODO*"),
+ assign_op, false, &needs_assign);
if (needs_assign) {
bool readonly;
rhs_var->SetAssignOp(assign_op);
@@ -473,7 +475,7 @@
std::vector<Symbol> targets;
bool is_pattern_rule;
- StringPiece after_targets =
+ std::string_view after_targets =
ParseRuleTargets(loc_, before_term, &targets, &is_pattern_rule);
bool is_double_colon = (after_targets[0] == ':');
if (is_double_colon) {
@@ -634,7 +636,7 @@
last_rule_ = NULL;
const std::string&& pats = stmt->expr->Eval(this);
- for (StringPiece pat : WordScanner(pats)) {
+ for (std::string_view pat : WordScanner(pats)) {
ScopedTerminator st(pat);
const auto& files = Glob(pat.data());
@@ -667,9 +669,9 @@
last_rule_ = NULL;
const std::string&& exports = stmt->expr->Eval(this);
- for (StringPiece tok : WordScanner(exports)) {
+ for (std::string_view tok : WordScanner(exports)) {
size_t equal_index = tok.find('=');
- StringPiece lhs;
+ std::string_view lhs;
if (equal_index == std::string::npos) {
lhs = tok;
} else if (equal_index == 0 ||
@@ -678,7 +680,7 @@
// Do not export tokens after an assignment.
break;
} else {
- StringPiece rhs;
+ std::string_view rhs;
AssignOp op;
ParseAssignStatement(tok, equal_index, &lhs, &rhs, &op);
}
diff --git a/src/eval.h b/src/eval.h
index 03370ec..6c4199f 100644
--- a/src/eval.h
+++ b/src/eval.h
@@ -18,13 +18,13 @@
#include <map>
#include <memory>
#include <set>
+#include <string_view>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "loc.h"
#include "stmt.h"
-#include "string_piece.h"
#include "symtab.h"
class Makefile;
@@ -204,16 +204,16 @@
bool ExportDeprecated() const { return export_message_ && !export_error_; };
bool ExportObsolete() const { return export_error_; };
- void SetExportDeprecated(StringPiece msg) {
- export_message_.reset(new std::string(msg.as_string()));
+ void SetExportDeprecated(std::string_view msg) {
+ export_message_.reset(new std::string(msg));
}
- void SetExportObsolete(StringPiece msg) {
- export_message_.reset(new std::string(msg.as_string()));
+ void SetExportObsolete(std::string_view msg) {
+ export_message_.reset(new std::string(msg));
export_error_ = true;
}
- void ProfileMakefile(StringPiece mk) {
- profiled_files_.emplace_back(mk.as_string());
+ void ProfileMakefile(std::string_view mk) {
+ profiled_files_.emplace_back(std::string(mk));
}
bool IsEvaluatingCommand() const;
@@ -222,7 +222,7 @@
private:
Var* EvalRHS(Symbol lhs,
Value* rhs,
- StringPiece orig_rhs,
+ std::string_view orig_rhs,
AssignOp op,
bool is_override,
bool* needs_assign);
@@ -240,7 +240,7 @@
void EvalRuleSpecificAssign(const std::vector<Symbol>& targets,
const RuleStmt* stmt,
- const StringPiece& lhs_string,
+ const std::string_view& lhs_string,
size_t separator_pos);
std::unordered_map<Symbol, Vars*> rule_vars_;
diff --git a/src/exec.cc b/src/exec.cc
index be82593..000caa2 100644
--- a/src/exec.cc
+++ b/src/exec.cc
@@ -21,6 +21,7 @@
#include <sys/wait.h>
#include <memory>
+#include <string_view>
#include <unordered_map>
#include <utility>
#include <vector>
@@ -32,7 +33,6 @@
#include "fileutil.h"
#include "flags.h"
#include "log.h"
-#include "string_piece.h"
#include "strutil.h"
#include "symtab.h"
#include "var.h"
diff --git a/src/expr.cc b/src/expr.cc
index a3fdf62..41b60bb 100644
--- a/src/expr.cc
+++ b/src/expr.cc
@@ -45,9 +45,9 @@
class Literal : public Value {
public:
- explicit Literal(StringPiece s) : Value(Loc()), s_(s) {}
+ explicit Literal(std::string_view s) : Value(Loc()), s_(s) {}
- StringPiece val() const { return s_; }
+ std::string_view val() const { return s_; }
virtual bool IsFunc(Evaluator*) const override { return false; }
@@ -57,12 +57,12 @@
}
virtual bool IsLiteral() const override { return true; }
- virtual StringPiece GetLiteralValueUnsafe() const override { return s_; }
+ virtual std::string_view GetLiteralValueUnsafe() const override { return s_; }
- virtual std::string DebugString_() const override { return s_.as_string(); }
+ virtual std::string DebugString_() const override { return std::string(s_); }
private:
- StringPiece s_;
+ std::string_view s_;
};
class ValueList : public Value {
@@ -214,7 +214,7 @@
const std::string&& value = v->Eval(ev);
WordWriter ww(s);
Pattern pat(pat_str);
- for (StringPiece tok : WordScanner(value)) {
+ for (std::string_view tok : WordScanner(value)) {
ww.MaybeAddWhitespace();
pat.AppendSubstRef(tok, subst, s);
}
@@ -280,7 +280,7 @@
return 0;
}
-static size_t SkipSpaces(Loc* loc, StringPiece s, const char* terms) {
+static size_t SkipSpaces(Loc* loc, std::string_view s, const char* terms) {
for (size_t i = 0; i < s.size(); i++) {
char c = s[i];
if (strchr(terms, c)) {
@@ -292,7 +292,7 @@
return i;
}
- char n = s.get(i + 1);
+ char n = i + 1 < s.size() ? s[i + 1] : 0;
if (n != '\r' && n != '\n') {
return i;
}
@@ -320,7 +320,7 @@
return new ValueList(loc, values);
}
-Value* Value::NewLiteral(StringPiece s) {
+Value* Value::NewLiteral(std::string_view s) {
return new Literal(s);
}
@@ -330,7 +330,7 @@
void ParseFunc(Loc* loc,
Func* f,
- StringPiece s,
+ std::string_view s,
size_t i,
char* terms,
size_t* index_out) {
@@ -356,7 +356,7 @@
}
if (s[i] == '\\') {
- char c = s.get(i + 1);
+ char c = i + 1 < s.size() ? s[i + 1] : 0;
if (c == '\r' || c == '\n') {
loc->lineno++;
continue;
@@ -401,7 +401,7 @@
return;
}
-Value* ParseDollar(Loc* loc, StringPiece s, size_t* index_out) {
+Value* ParseDollar(Loc* loc, std::string_view s, size_t* index_out) {
CHECK(s.size() >= 2);
CHECK(s[0] == '$');
CHECK(s[1] != '$');
@@ -500,14 +500,14 @@
}
Value* ParseExprImpl(Loc* loc,
- StringPiece s,
+ std::string_view s,
const char* terms,
ParseExprOpt opt,
size_t* index_out,
bool trim_right_space) {
Loc list_loc = *loc;
- if (s.get(s.size() - 1) == '\r')
+ if (!s.empty() && s.back() == '\r')
s.remove_suffix(1);
size_t b = 0;
@@ -544,14 +544,14 @@
list.push_back(new Literal(s.substr(b, i - b)));
if (s[i + 1] == '$') {
- list.push_back(new Literal(StringPiece("$")));
+ list.push_back(new Literal(std::string_view("$")));
i += 1;
b = i + 1;
continue;
}
if (terms && strchr(terms, s[i + 1])) {
- list.push_back(new Literal(StringPiece("$")));
+ list.push_back(new Literal(std::string_view("$")));
*index_out = i + 1;
return Value::NewExpr(item_loc, &list);
}
@@ -604,15 +604,16 @@
if (i > b) {
list.push_back(new Literal(TrimRightSpace(s.substr(b, i - b))));
}
- list.push_back(new Literal(StringPiece(" ")));
+ list.push_back(new Literal(std::string_view(" ")));
// Skip the current escaped newline
i += 2;
- if (n == '\r' && s.get(i) == '\n') {
+ if (n == '\r' && i < s.size() && s[i] == '\n') {
i++;
}
// Then continue skipping escaped newlines, spaces, and tabs
for (; i < s.size(); i++) {
- if (s[i] == '\\' && (s.get(i + 1) == '\r' || s.get(i + 1) == '\n')) {
+ if (s[i] == '\\' && i + 1 < s.size() &&
+ (s[i + 1] == '\r' || s[i + 1] == '\n')) {
loc->lineno++;
i++;
continue;
@@ -628,7 +629,7 @@
}
if (i > b) {
- StringPiece rest = s.substr(b, i - b);
+ std::string_view rest = s.substr(b, i - b);
if (trim_right_space)
rest = TrimRightSpace(rest);
if (!rest.empty())
@@ -638,7 +639,7 @@
return Value::NewExpr(list_loc, &list);
}
-Value* ParseExpr(Loc* loc, StringPiece s, ParseExprOpt opt) {
+Value* ParseExpr(Loc* loc, std::string_view s, ParseExprOpt opt) {
size_t n;
return ParseExprImpl(loc, s, NULL, opt, &n);
}
diff --git a/src/expr.h b/src/expr.h
index f64278d..b57018f 100644
--- a/src/expr.h
+++ b/src/expr.h
@@ -16,10 +16,10 @@
#define EXPR_H_
#include <string>
+#include <string_view>
#include <vector>
#include "loc.h"
-#include "string_piece.h"
class Evaluator;
@@ -55,11 +55,11 @@
static Value* NewExpr(const Loc& loc, Value* v1, Value* v2, Value* v3);
static Value* NewExpr(const Loc& loc, std::vector<Value*>* values);
- static Value* NewLiteral(StringPiece s);
+ static Value* NewLiteral(std::string_view s);
virtual ~Value();
virtual bool IsLiteral() const { return false; }
// Only safe after IsLiteral() returns true.
- virtual StringPiece GetLiteralValueUnsafe() const { return ""; }
+ virtual std::string_view GetLiteralValueUnsafe() const { return ""; }
static std::string DebugString(const Value*);
@@ -76,13 +76,13 @@
};
Value* ParseExprImpl(Loc* loc,
- StringPiece s,
+ std::string_view s,
const char* terms,
ParseExprOpt opt,
size_t* index_out,
bool trim_right_space = false);
Value* ParseExpr(Loc* loc,
- StringPiece s,
+ std::string_view s,
ParseExprOpt opt = ParseExprOpt::NORMAL);
std::string JoinValues(const std::vector<Value*>& vals, const char* sep);
diff --git a/src/fileutil.cc b/src/fileutil.cc
index f70d44a..e6518ef 100644
--- a/src/fileutil.cc
+++ b/src/fileutil.cc
@@ -37,10 +37,10 @@
extern char** environ;
-bool Exists(StringPiece filename) {
+bool Exists(std::string_view filename) {
CHECK(filename.size() < PATH_MAX);
struct stat st;
- if (stat(filename.as_string().c_str(), &st) < 0) {
+ if (stat(std::string(filename).c_str(), &st) < 0) {
return false;
}
return true;
@@ -54,10 +54,10 @@
#endif
}
-double GetTimestamp(StringPiece filename) {
+double GetTimestamp(std::string_view filename) {
CHECK(filename.size() < PATH_MAX);
struct stat st;
- if (stat(filename.as_string().c_str(), &st) < 0) {
+ if (stat(std::string(filename).c_str(), &st) < 0) {
return -2.0;
}
return GetTimestampFromStat(st);
diff --git a/src/fileutil.h b/src/fileutil.h
index 47751eb..6f4f067 100644
--- a/src/fileutil.h
+++ b/src/fileutil.h
@@ -19,14 +19,13 @@
#include <memory>
#include <string>
+#include <string_view>
#include <unordered_map>
#include <vector>
-#include "string_piece.h"
-
-bool Exists(StringPiece f);
+bool Exists(std::string_view f);
double GetTimestampFromStat(const struct stat& st);
-double GetTimestamp(StringPiece f);
+double GetTimestamp(std::string_view f);
enum struct RedirectStderr {
NONE,
diff --git a/src/find.cc b/src/find.cc
index 51a6276..4e81851 100644
--- a/src/find.cc
+++ b/src/find.cc
@@ -25,6 +25,7 @@
#include <algorithm>
#include <memory>
+#include <string_view>
#include <vector>
//#undef NOLOG
@@ -32,7 +33,6 @@
#include "fileutil.h"
#include "log.h"
#include "stats.h"
-#include "string_piece.h"
#include "strutil.h"
#include "timeutil.h"
@@ -144,12 +144,12 @@
public:
virtual ~DirentNode() = default;
- virtual const DirentNode* FindDir(StringPiece) const { return NULL; }
+ virtual const DirentNode* FindDir(std::string_view) const { return NULL; }
virtual bool FindNodes(
const FindCommand&,
std::vector<std::pair<std::string, const DirentNode*>>&,
std::string*,
- StringPiece) const {
+ std::string_view) const {
return true;
}
virtual bool RunFind(
@@ -166,7 +166,7 @@
protected:
explicit DirentNode(const std::string& name) {
- base_ = Basename(name).as_string();
+ base_ = std::string(Basename(name));
}
void PrintIfNecessary(const FindCommand& fc,
@@ -245,7 +245,7 @@
}
}
- virtual const DirentNode* FindDir(StringPiece d) const override {
+ virtual const DirentNode* FindDir(std::string_view d) const override {
if (!is_initialized_) {
initialize();
}
@@ -256,7 +256,7 @@
return parent_;
size_t index = d.find('/');
- const std::string& p = d.substr(0, index).as_string();
+ std::string_view p = d.substr(0, index);
if (p.empty() || p == ".")
return FindDir(d.substr(index + 1));
if (p == "..") {
@@ -269,7 +269,7 @@
if (p == child.first) {
if (index == std::string::npos)
return child.second;
- StringPiece nd = d.substr(index + 1);
+ std::string_view nd = d.substr(index + 1);
return child.second->FindDir(nd);
}
}
@@ -280,7 +280,7 @@
const FindCommand& fc,
std::vector<std::pair<std::string, const DirentNode*>>& results,
std::string* path,
- StringPiece d) const override {
+ std::string_view d) const override {
if (!is_initialized_) {
initialize();
}
@@ -291,7 +291,7 @@
size_t orig_path_size = path->size();
size_t index = d.find('/');
- const std::string& p = d.substr(0, index).as_string();
+ const std::string p{d.substr(0, index)};
if (p.empty() || p == ".") {
path->append(p);
@@ -481,7 +481,7 @@
const std::string& name)
: DirentNode(name), name_(name), parent_(parent) {}
- virtual const DirentNode* FindDir(StringPiece d) const override {
+ virtual const DirentNode* FindDir(std::string_view d) const override {
if (!is_initialized_) {
initialize();
}
@@ -494,7 +494,7 @@
const FindCommand& fc,
std::vector<std::pair<std::string, const DirentNode*>>& results,
std::string* path,
- StringPiece d) const override {
+ std::string_view d) const override {
if (!is_initialized_) {
initialize();
}
@@ -638,7 +638,7 @@
class FindCommandParser {
public:
- FindCommandParser(StringPiece cmd, FindCommand* fc)
+ FindCommandParser(std::string_view cmd, FindCommand* fc)
: cmd_(cmd), fc_(fc), has_if_(false) {}
bool Parse() {
@@ -652,10 +652,10 @@
}
private:
- bool GetNextToken(StringPiece* tok) {
+ bool GetNextToken(std::string_view* tok) {
if (!unget_tok_.empty()) {
*tok = unget_tok_;
- unget_tok_.clear();
+ unget_tok_ = std::string_view();
return true;
}
@@ -667,7 +667,7 @@
return true;
}
if (cur_[0] == '&') {
- if (cur_.get(1) != '&') {
+ if (cur_.size() < 2 || cur_[1] != '&') {
return false;
}
*tok = cur_.substr(0, 2);
@@ -684,9 +684,9 @@
*tok = cur_.substr(0, i);
cur_ = cur_.substr(i);
- const char c = tok->get(0);
+ const char c = tok->empty() ? 0 : tok->front();
if (c == '\'' || c == '"') {
- if (tok->size() < 2 || (*tok)[tok->size() - 1] != c)
+ if (tok->size() < 2 || tok->back() != c)
return false;
*tok = tok->substr(1, tok->size() - 2);
return true;
@@ -705,7 +705,7 @@
return true;
}
- void UngetToken(StringPiece tok) {
+ void UngetToken(std::string_view tok) {
CHECK(unget_tok_.empty());
if (!tok.empty())
unget_tok_ = tok;
@@ -714,16 +714,16 @@
bool ParseTest() {
if (has_if_ || !fc_->testdir.empty())
return false;
- StringPiece tok;
+ std::string_view tok;
if (!GetNextToken(&tok) || tok != "-d")
return false;
if (!GetNextToken(&tok) || tok.empty())
return false;
- fc_->testdir = tok.as_string();
+ fc_->testdir = std::string(tok);
return true;
}
- FindCond* ParseFact(StringPiece tok) {
+ FindCond* ParseFact(std::string_view tok) {
if (tok == "-not" || tok == "!") {
if (!GetNextToken(&tok) || tok.empty())
return NULL;
@@ -742,7 +742,7 @@
} else if (tok == "-name") {
if (!GetNextToken(&tok) || tok.empty())
return NULL;
- return new NameCond(tok.as_string());
+ return new NameCond(std::string(tok));
} else if (tok == "-type") {
if (!GetNextToken(&tok) || tok.empty())
return NULL;
@@ -770,7 +770,7 @@
}
}
- FindCond* ParseTerm(StringPiece tok) {
+ FindCond* ParseTerm(std::string_view tok) {
std::unique_ptr<FindCond> c(ParseFact(tok));
if (!c.get())
return NULL;
@@ -795,7 +795,7 @@
}
}
- FindCond* ParseExpr(StringPiece tok) {
+ FindCond* ParseExpr(std::string_view tok) {
std::unique_ptr<FindCond> c(ParseTerm(tok));
if (!c.get())
return NULL;
@@ -826,11 +826,11 @@
// <name> ::= '-name' NAME
// <type> ::= '-type' TYPE
// <maxdepth> ::= '-maxdepth' MAXDEPTH
- FindCond* ParseFindCond(StringPiece tok) { return ParseExpr(tok); }
+ FindCond* ParseFindCond(std::string_view tok) { return ParseExpr(tok); }
bool ParseFind() {
fc_->type = FindCommandType::FIND;
- StringPiece tok;
+ std::string_view tok;
while (true) {
if (!GetNextToken(&tok))
return false;
@@ -852,7 +852,7 @@
} else if (tok == "-maxdepth") {
if (!GetNextToken(&tok) || tok.empty())
return false;
- const std::string& depth_str = tok.as_string();
+ const std::string& depth_str = std::string(tok);
char* endptr;
long d = strtol(depth_str.c_str(), &endptr, 10);
if (endptr != depth_str.data() + depth_str.size() || d < 0 ||
@@ -875,7 +875,7 @@
} else if (tok.find_first_of("|;&><'\"") != std::string::npos) {
return false;
} else {
- fc_->finddirs.push_back(tok.as_string());
+ fc_->finddirs.push_back(std::string(tok));
}
}
}
@@ -883,7 +883,7 @@
bool ParseFindLeaves() {
fc_->type = FindCommandType::FINDLEAVES;
fc_->follows_symlinks = true;
- StringPiece tok;
+ std::string_view tok;
std::vector<std::string> findfiles;
while (true) {
if (!GetNextToken(&tok))
@@ -913,15 +913,14 @@
if (HasPrefix(tok, "--prune=")) {
FindCond* cond =
- new NameCond(tok.substr(strlen("--prune=")).as_string());
+ new NameCond(std::string(tok.substr(strlen("--prune="))));
if (fc_->prune_cond.get()) {
cond = new OrCond(fc_->prune_cond.release(), cond);
}
CHECK(!fc_->prune_cond.get());
fc_->prune_cond.reset(cond);
} else if (HasPrefix(tok, "--mindepth=")) {
- std::string mindepth_str =
- tok.substr(strlen("--mindepth=")).as_string();
+ std::string mindepth_str{tok.substr(strlen("--mindepth="))};
char* endptr;
long d = strtol(mindepth_str.c_str(), &endptr, 10);
if (endptr != mindepth_str.data() + mindepth_str.size() ||
@@ -930,8 +929,8 @@
}
fc_->mindepth = d;
} else if (HasPrefix(tok, "--dir=")) {
- StringPiece dir = tok.substr(strlen("--dir="));
- fc_->finddirs.push_back(dir.as_string());
+ std::string_view dir = tok.substr(strlen("--dir="));
+ fc_->finddirs.emplace_back(dir);
} else if (HasPrefix(tok, "--")) {
if (g_flags.werror_find_emulator) {
ERROR("Unknown flag in findleaves.py: %.*s", SPF(tok));
@@ -940,14 +939,14 @@
}
return false;
} else {
- findfiles.push_back(tok.as_string());
+ findfiles.push_back(std::string(tok));
}
}
}
bool ParseImpl() {
while (true) {
- StringPiece tok;
+ std::string_view tok;
if (!GetNextToken(&tok))
return false;
@@ -959,7 +958,7 @@
return false;
if (tok.find_first_of("?*[") != std::string::npos)
return false;
- fc_->chdir = tok.as_string();
+ fc_->chdir = std::string(tok);
if (!GetNextToken(&tok) || (tok != ";" && tok != "&&"))
return false;
} else if (tok == "if") {
@@ -1002,11 +1001,11 @@
}
}
- StringPiece cmd_;
- StringPiece cur_;
+ std::string_view cmd_;
+ std::string_view cur_;
FindCommand* fc_;
bool has_if_;
- StringPiece unget_tok_;
+ std::string_view unget_tok_;
};
static FindEmulator* g_instance;
@@ -1017,12 +1016,12 @@
virtual ~FindEmulatorImpl() = default;
- bool CanHandle(StringPiece s) const {
+ bool CanHandle(std::string_view s) const {
return (!HasPrefix(s, "/") && !HasPrefix(s, ".repo") &&
!HasPrefix(s, ".git"));
}
- const DirentNode* FindDir(StringPiece d, bool* should_fallback) {
+ const DirentNode* FindDir(std::string_view d, bool* should_fallback) {
const DirentNode* r = root_->FindDir(d);
if (!r) {
*should_fallback = Exists(d);
diff --git a/src/find.h b/src/find.h
index 24407e9..4caaef6 100644
--- a/src/find.h
+++ b/src/find.h
@@ -17,11 +17,11 @@
#include <memory>
#include <string>
+#include <string_view>
#include <unordered_set>
#include <vector>
#include "loc.h"
-#include "string_piece.h"
class FindCond;
diff --git a/src/find_test.cc b/src/find_test.cc
index b8502f9..b901e4e 100644
--- a/src/find_test.cc
+++ b/src/find_test.cc
@@ -22,6 +22,7 @@
#include <string>
#include "fileutil.h"
+#include "log.h"
#include "strutil.h"
int FindUnitTests();
@@ -49,7 +50,7 @@
return 1;
}
- for (StringPiece tok : WordScanner(out)) {
+ for (std::string_view tok : WordScanner(out)) {
printf("%.*s\n", SPF(tok));
}
}
@@ -82,8 +83,8 @@
exit(1);
}
- std::vector<StringPiece> nativeWords;
- std::vector<StringPiece> emulatedWords;
+ std::vector<std::string_view> nativeWords;
+ std::vector<std::string_view> emulatedWords;
WordScanner(native).Split(&nativeWords);
WordScanner(emulated).Split(&emulatedWords);
@@ -99,10 +100,10 @@
fprintf(stderr, " %-20s %-20s\n",
(nativeIter == nativeWords.end())
? ""
- : (*nativeIter++).as_string().c_str(),
+ : std::string(*nativeIter++).c_str(),
(emulatedIter == emulatedWords.end())
? ""
- : (*emulatedIter++).as_string().c_str());
+ : std::string(*emulatedIter++).c_str());
}
fprintf(stderr, "------------------------------------------\n");
unit_test_failed = true;
diff --git a/src/flags.cc b/src/flags.cc
index ea2a663..37f08f4 100644
--- a/src/flags.cc
+++ b/src/flags.cc
@@ -24,7 +24,7 @@
Flags g_flags;
-static bool ParseCommandLineOptionWithArg(StringPiece option,
+static bool ParseCommandLineOptionWithArg(std::string_view option,
char* argv[],
int* index,
const char** out_arg) {
@@ -56,7 +56,7 @@
const char* variable_assignment_trace_filter;
if (const char* makeflags = getenv("MAKEFLAGS")) {
- for (StringPiece tok : WordScanner(makeflags)) {
+ for (std::string_view tok : WordScanner(makeflags)) {
if (!HasPrefix(tok, "-") && tok.find('=') != std::string::npos)
cl_vars.push_back(tok);
}
@@ -158,7 +158,8 @@
} else if (ParseCommandLineOptionWithArg(
"--variable_assignment_trace_filter", argv, &i,
&variable_assignment_trace_filter)) {
- for (StringPiece pat : WordScanner(variable_assignment_trace_filter)) {
+ for (std::string_view pat :
+ WordScanner(variable_assignment_trace_filter)) {
traced_variables_pattern.push_back(Pattern(pat));
}
} else if (ParseCommandLineOptionWithArg("-j", argv, &i, &num_jobs_str)) {
diff --git a/src/flags.h b/src/flags.h
index 83bbe78..5b36518 100644
--- a/src/flags.h
+++ b/src/flags.h
@@ -16,9 +16,9 @@
#define FLAGS_H_
#include <string>
+#include <string_view>
#include <vector>
-#include "string_piece.h"
#include "strutil.h"
#include "symtab.h"
@@ -77,7 +77,7 @@
int remote_num_jobs;
std::vector<const char*> subkati_args;
std::vector<Symbol> targets;
- std::vector<StringPiece> cl_vars;
+ std::vector<std::string_view> cl_vars;
std::vector<std::string> writable;
std::vector<Pattern> traced_variables_pattern;
diff --git a/src/func.cc b/src/func.cc
index 1171deb..4af6662 100644
--- a/src/func.cc
+++ b/src/func.cc
@@ -106,7 +106,7 @@
const std::string&& str = args[2]->Eval(ev);
WordWriter ww(s);
Pattern pat(pat_str);
- for (StringPiece tok : WordScanner(str)) {
+ for (std::string_view tok : WordScanner(str)) {
ww.MaybeAddWhitespace();
pat.AppendSubst(tok, repl, s);
}
@@ -115,7 +115,7 @@
void StripFunc(const std::vector<Value*>& args, Evaluator* ev, std::string* s) {
const std::string&& str = args[0]->Eval(ev);
WordWriter ww(s);
- for (StringPiece tok : WordScanner(str)) {
+ for (std::string_view tok : WordScanner(str)) {
ww.Write(tok);
}
}
@@ -134,11 +134,11 @@
size_t found = str.find(pat, index);
if (found == std::string::npos)
break;
- AppendString(StringPiece(str).substr(index, found - index), s);
+ AppendString(std::string_view(str).substr(index, found - index), s);
AppendString(repl, s);
index = found + pat.size();
}
- AppendString(StringPiece(str).substr(index), s);
+ AppendString(std::string_view(str).substr(index), s);
}
void FindstringFunc(const std::vector<Value*>& args,
@@ -156,11 +156,11 @@
const std::string&& pat_buf = args[0]->Eval(ev);
const std::string&& text = args[1]->Eval(ev);
std::vector<Pattern> pats;
- for (StringPiece pat : WordScanner(pat_buf)) {
+ for (std::string_view pat : WordScanner(pat_buf)) {
pats.push_back(Pattern(pat));
}
WordWriter ww(s);
- for (StringPiece tok : WordScanner(text)) {
+ for (std::string_view tok : WordScanner(text)) {
for (const Pattern& pat : pats) {
if (pat.Match(tok)) {
ww.Write(tok);
@@ -176,11 +176,11 @@
const std::string&& pat_buf = args[0]->Eval(ev);
const std::string&& text = args[1]->Eval(ev);
std::vector<Pattern> pats;
- for (StringPiece pat : WordScanner(pat_buf)) {
+ for (std::string_view pat : WordScanner(pat_buf)) {
pats.push_back(Pattern(pat));
}
WordWriter ww(s);
- for (StringPiece tok : WordScanner(text)) {
+ for (std::string_view tok : WordScanner(text)) {
bool matched = false;
for (const Pattern& pat : pats) {
if (pat.Match(tok)) {
@@ -199,12 +199,12 @@
COLLECT_STATS("func sort time");
// TODO(hamaji): Probably we could use a faster string-specific sort
// algorithm.
- std::vector<StringPiece> toks;
+ std::vector<std::string_view> toks;
WordScanner(list).Split(&toks);
stable_sort(toks.begin(), toks.end());
WordWriter ww(s);
- StringPiece prev;
- for (StringPiece tok : toks) {
+ std::string_view prev;
+ for (std::string_view tok : toks) {
if (prev != tok) {
ww.Write(tok);
prev = tok;
@@ -213,7 +213,7 @@
}
static int GetNumericValueForFunc(const std::string& buf) {
- StringPiece s = TrimLeftSpace(buf);
+ std::string_view s = TrimLeftSpace(buf);
char* end;
long n = strtol(s.data(), &end, 10);
if (n < 0 || n == LONG_MAX || s.data() + s.size() != end) {
@@ -235,7 +235,7 @@
}
const std::string&& text = args[1]->Eval(ev);
- for (StringPiece tok : WordScanner(text)) {
+ for (std::string_view tok : WordScanner(text)) {
n--;
if (n == 0) {
AppendString(tok, s);
@@ -271,7 +271,7 @@
const std::string&& text = args[2]->Eval(ev);
int i = 0;
WordWriter ww(s);
- for (StringPiece tok : WordScanner(text)) {
+ for (std::string_view tok : WordScanner(text)) {
i++;
if (si <= i && i <= ei) {
ww.Write(tok);
@@ -305,8 +305,8 @@
Evaluator* ev,
std::string* s) {
const std::string&& text = args[0]->Eval(ev);
- StringPiece last;
- for (StringPiece tok : WordScanner(text)) {
+ std::string_view last;
+ for (std::string_view tok : WordScanner(text)) {
last = tok;
}
AppendString(last, s);
@@ -339,7 +339,7 @@
// Note GNU make does not delay the execution of $(wildcard) so we
// do not need to check avoid_io here.
WordWriter ww(s);
- for (StringPiece tok : WordScanner(pat)) {
+ for (std::string_view tok : WordScanner(pat)) {
ScopedTerminator st(tok);
const auto& files = Glob(tok.data());
for (const std::string& file : files) {
@@ -351,7 +351,7 @@
void DirFunc(const std::vector<Value*>& args, Evaluator* ev, std::string* s) {
const std::string&& text = args[0]->Eval(ev);
WordWriter ww(s);
- for (StringPiece tok : WordScanner(text)) {
+ for (std::string_view tok : WordScanner(text)) {
ww.Write(Dirname(tok));
s->push_back('/');
}
@@ -362,9 +362,9 @@
std::string* s) {
const std::string&& text = args[0]->Eval(ev);
WordWriter ww(s);
- for (StringPiece tok : WordScanner(text)) {
+ for (std::string_view tok : WordScanner(text)) {
if (tok == "/") {
- ww.Write(StringPiece(""));
+ ww.Write(std::string_view(""));
} else {
ww.Write(Basename(tok));
}
@@ -376,8 +376,8 @@
std::string* s) {
const std::string&& text = args[0]->Eval(ev);
WordWriter ww(s);
- for (StringPiece tok : WordScanner(text)) {
- StringPiece suf = GetExt(tok);
+ for (std::string_view tok : WordScanner(text)) {
+ std::string_view suf = GetExt(tok);
if (!suf.empty())
ww.Write(suf);
}
@@ -388,7 +388,7 @@
std::string* s) {
const std::string&& text = args[0]->Eval(ev);
WordWriter ww(s);
- for (StringPiece tok : WordScanner(text)) {
+ for (std::string_view tok : WordScanner(text)) {
ww.Write(StripExt(tok));
}
}
@@ -399,7 +399,7 @@
const std::string&& suf = args[0]->Eval(ev);
const std::string&& text = args[1]->Eval(ev);
WordWriter ww(s);
- for (StringPiece tok : WordScanner(text)) {
+ for (std::string_view tok : WordScanner(text)) {
ww.Write(tok);
*s += suf;
}
@@ -411,7 +411,7 @@
const std::string&& pre = args[0]->Eval(ev);
const std::string&& text = args[1]->Eval(ev);
WordWriter ww(s);
- for (StringPiece tok : WordScanner(text)) {
+ for (std::string_view tok : WordScanner(text)) {
ww.Write(pre);
AppendString(tok, s);
}
@@ -431,7 +431,7 @@
}
WordWriter ww(s);
- for (StringPiece tok : WordScanner(text)) {
+ for (std::string_view tok : WordScanner(text)) {
ScopedTerminator st(tok);
char buf[PATH_MAX];
if (realpath(tok.data(), buf))
@@ -445,7 +445,7 @@
const std::string&& text = args[0]->Eval(ev);
WordWriter ww(s);
std::string buf;
- for (StringPiece tok : WordScanner(text)) {
+ for (std::string_view tok : WordScanner(text)) {
AbsPath(tok, &buf);
ww.Write(buf);
}
@@ -486,7 +486,7 @@
void ValueFunc(const std::vector<Value*>& args, Evaluator* ev, std::string* s) {
const std::string&& var_name = args[0]->Eval(ev);
Var* var = ev->LookupVar(Intern(var_name));
- AppendString(var->String().as_string(), s);
+ AppendString(std::string(var->String()), s);
}
void EvalFunc(const std::vector<Value*>& args, Evaluator* ev, std::string*) {
@@ -574,15 +574,16 @@
static std::vector<CommandResult*> g_command_results;
-bool ShouldStoreCommandResult(StringPiece cmd) {
+bool ShouldStoreCommandResult(std::string_view cmd) {
// We really just want to ignore this one, or remove BUILD_DATETIME from
// Android completely
if (cmd == "date +%s")
return false;
- Pattern pat(g_flags.ignore_dirty_pattern);
- Pattern nopat(g_flags.no_ignore_dirty_pattern);
- for (StringPiece tok : WordScanner(cmd)) {
+ Pattern pat(g_flags.ignore_dirty_pattern ? g_flags.ignore_dirty_pattern : "");
+ Pattern nopat(
+ g_flags.no_ignore_dirty_pattern ? g_flags.no_ignore_dirty_pattern : "");
+ for (std::string_view tok : WordScanner(cmd)) {
if (pat.Match(tok) && !nopat.Match(tok)) {
return false;
}
@@ -689,9 +690,9 @@
const std::string&& list = args[1]->Eval(ev);
ev->DecrementEvalDepth();
WordWriter ww(s);
- for (StringPiece tok : WordScanner(list)) {
+ for (std::string_view tok : WordScanner(list)) {
std::unique_ptr<SimpleVar> v(
- new SimpleVar(tok.as_string(), VarOrigin::AUTOMATIC, nullptr, Loc()));
+ new SimpleVar(std::string(tok), VarOrigin::AUTOMATIC, nullptr, Loc()));
ScopedGlobalVar sv(Intern(varname), v.get());
ww.MaybeAddWhitespace();
args[2]->Eval(ev, s);
@@ -830,7 +831,7 @@
}
std::string arg = args[0]->Eval(ev);
- StringPiece filename = TrimSpace(arg);
+ std::string_view filename = TrimSpace(arg);
if (filename.size() <= 1) {
ev->Error("*** Missing filename");
@@ -845,7 +846,7 @@
ev->Error("*** invalid argument");
}
- FileReadFunc(ev, filename.as_string(), s);
+ FileReadFunc(ev, std::string(filename), s);
} else if (filename[0] == '>') {
bool append = false;
if (filename[1] == '>') {
@@ -867,10 +868,10 @@
}
}
- FileWriteFunc(ev, filename.as_string(), append, text);
+ FileWriteFunc(ev, std::string(filename), append, text);
} else {
ev->Error(StringPrintf("*** Invalid file operation: %s. Stop.",
- filename.as_string().c_str()));
+ std::string(filename).c_str()));
}
}
@@ -888,7 +889,7 @@
ev->Error("*** $(KATI_deprecated_var ...) is not supported in rules.");
}
- for (StringPiece var : WordScanner(vars_str)) {
+ for (std::string_view var : WordScanner(vars_str)) {
Symbol sym = Intern(var);
Var* v = ev->PeekVar(sym);
if (!v->IsDefined()) {
@@ -926,7 +927,7 @@
ev->Error("*** $(KATI_obsolete_var ...) is not supported in rules.");
}
- for (StringPiece var : WordScanner(vars_str)) {
+ for (std::string_view var : WordScanner(vars_str)) {
Symbol sym = Intern(var);
Var* v = ev->PeekVar(sym);
if (!v->IsDefined()) {
@@ -986,7 +987,7 @@
void ProfileFunc(const std::vector<Value*>& args, Evaluator* ev, std::string*) {
for (auto arg : args) {
std::string files = arg->Eval(ev);
- for (StringPiece file : WordScanner(files)) {
+ for (std::string_view file : WordScanner(files)) {
ev->ProfileMakefile(file);
}
}
@@ -997,7 +998,7 @@
std::string* s) {
std::string arg = args[0]->Eval(ev);
WordWriter ww(s);
- for (StringPiece var : WordScanner(arg)) {
+ for (std::string_view var : WordScanner(arg)) {
Symbol sym = Intern(var);
Var* v = ev->PeekVar(sym);
const Loc& loc = v->Location();
@@ -1012,7 +1013,7 @@
name, { name, args } \
}
-static const std::unordered_map<StringPiece, FuncInfo> g_func_info_map = {
+static const std::unordered_map<std::string_view, FuncInfo> g_func_info_map = {
ENTRY("patsubst", &PatsubstFunc, 3, 3, false, false),
ENTRY("strip", &StripFunc, 1, 1, false, false),
@@ -1069,7 +1070,7 @@
} // namespace
-const FuncInfo* GetFuncInfo(StringPiece name) {
+const FuncInfo* GetFuncInfo(std::string_view name) {
auto found = g_func_info_map.find(name);
if (found == g_func_info_map.end())
return nullptr;
diff --git a/src/func.h b/src/func.h
index f6287f5..efa5793 100644
--- a/src/func.h
+++ b/src/func.h
@@ -33,7 +33,7 @@
bool trim_right_space_1st;
};
-const FuncInfo* GetFuncInfo(StringPiece name);
+const FuncInfo* GetFuncInfo(std::string_view name);
struct FindCommand;
diff --git a/src/io.cc b/src/io.cc
index 75d8940..d2ee850 100644
--- a/src/io.cc
+++ b/src/io.cc
@@ -23,7 +23,7 @@
CHECK(r == 1);
}
-void DumpString(FILE* fp, StringPiece s) {
+void DumpString(FILE* fp, std::string_view s) {
DumpInt(fp, s.size());
size_t r = fwrite(s.data(), 1, s.size(), fp);
CHECK(r == s.size());
diff --git a/src/io.h b/src/io.h
index eb84910..6f176a3 100644
--- a/src/io.h
+++ b/src/io.h
@@ -18,11 +18,10 @@
#include <stdio.h>
#include <string>
-
-#include "string_piece.h"
+#include <string_view>
void DumpInt(FILE* fp, int v);
-void DumpString(FILE* fp, StringPiece s);
+void DumpString(FILE* fp, std::string_view s);
int LoadInt(FILE* fp);
bool LoadString(FILE* fp, std::string* s);
diff --git a/src/log.cc b/src/log.cc
index 2b19018..90c17c5 100644
--- a/src/log.cc
+++ b/src/log.cc
@@ -31,10 +31,10 @@
}
if (g_flags.color_warnings) {
- StringPiece filtered = TrimPrefix(msg, "*** ");
+ std::string_view filtered = TrimPrefix(msg, "*** ");
ERROR(BOLD "%s:%d: " RED "error: " RESET BOLD "%s" RESET, file, line,
- filtered.as_string().c_str());
+ std::string(filtered).c_str());
} else {
ERROR("%s:%d: %s", file, line, msg);
}
@@ -47,12 +47,12 @@
}
if (g_flags.color_warnings) {
- StringPiece filtered = TrimPrefix(msg, "*warning*: ");
+ std::string_view filtered = TrimPrefix(msg, "*warning*: ");
filtered = TrimPrefix(filtered, "warning: ");
fprintf(stderr,
BOLD "%s:%d: " MAGENTA "warning: " RESET BOLD "%s" RESET "\n", file,
- line, filtered.as_string().c_str());
+ line, std::string(filtered).c_str());
} else {
fprintf(stderr, "%s:%d: %s\n", file, line, msg);
}
diff --git a/src/log.h b/src/log.h
index 80aef86..982f477 100644
--- a/src/log.h
+++ b/src/log.h
@@ -27,6 +27,8 @@
extern bool g_log_no_exit;
extern std::string* g_last_error;
+#define SPF(s) static_cast<int>((s).size()), (s).data()
+
// Useful for logging-only arguments.
#define UNUSED __attribute__((unused))
diff --git a/src/main.cc b/src/main.cc
index 609aaea..a32d013 100644
--- a/src/main.cc
+++ b/src/main.cc
@@ -22,6 +22,8 @@
#include <time.h>
#include <unistd.h>
+#include <string_view>
+
#include "affinity.h"
#include "eval.h"
#include "exec.h"
@@ -37,7 +39,6 @@
#include "regen.h"
#include "stats.h"
#include "stmt.h"
-#include "string_piece.h"
#include "stringprintf.h"
#include "strutil.h"
#include "symtab.h"
@@ -98,14 +99,14 @@
Parse(Intern(bootstrap).str(), Loc("*bootstrap*", 0), stmts);
}
-static void SetVar(StringPiece l,
+static void SetVar(std::string_view l,
VarOrigin origin,
Frame* definition,
Loc loc) {
size_t found = l.find('=');
CHECK(found != std::string::npos);
Symbol lhs = Intern(l.substr(0, found));
- StringPiece rhs = l.substr(found + 1);
+ std::string_view rhs = l.substr(found + 1);
lhs.SetGlobalVar(new RecursiveVar(Value::NewLiteral(rhs.data()), origin,
definition, loc, rhs.data()));
}
@@ -204,7 +205,7 @@
}
static int Run(const std::vector<Symbol>& targets,
- const std::vector<StringPiece>& cl_vars,
+ const std::vector<std::string_view>& cl_vars,
const std::string& orig_args) {
double start_time = GetTime();
@@ -251,7 +252,7 @@
{
ScopedFrame frame(ev.Enter(FrameType::PHASE, "*command line*", Loc()));
ev.in_command_line();
- for (StringPiece l : cl_vars) {
+ for (std::string_view l : cl_vars) {
std::vector<Stmt*> asts;
Parse(Intern(l).str(), Loc("*bootstrap*", 0), &asts);
CHECK(asts.size() == 1);
diff --git a/src/ninja.cc b/src/ninja.cc
index e29e965..469c89c 100644
--- a/src/ninja.cc
+++ b/src/ninja.cc
@@ -26,6 +26,7 @@
#include <ostream>
#include <sstream>
#include <string>
+#include <string_view>
#include <unordered_map>
#include <unordered_set>
@@ -40,27 +41,26 @@
#include "io.h"
#include "log.h"
#include "stats.h"
-#include "string_piece.h"
#include "stringprintf.h"
#include "strutil.h"
#include "timeutil.h"
#include "var.h"
#include "version.h"
-static size_t FindCommandLineFlag(StringPiece cmd, StringPiece name) {
+static size_t FindCommandLineFlag(std::string_view cmd, std::string_view name) {
const size_t found = cmd.find(name);
if (found == std::string::npos || found == 0)
return std::string::npos;
return found;
}
-static StringPiece FindCommandLineFlagWithArg(StringPiece cmd,
- StringPiece name) {
+static std::string_view FindCommandLineFlagWithArg(std::string_view cmd,
+ std::string_view name) {
size_t index = FindCommandLineFlag(cmd, name);
if (index == std::string::npos)
- return StringPiece();
+ return std::string_view();
- StringPiece val = TrimLeftSpace(cmd.substr(index + name.size()));
+ std::string_view val = TrimLeftSpace(cmd.substr(index + name.size()));
index = val.find(name);
while (index != std::string::npos) {
val = TrimLeftSpace(val.substr(index + name.size()));
@@ -71,18 +71,18 @@
return val.substr(0, index);
}
-static bool StripPrefix(StringPiece p, StringPiece* s) {
+static bool StripPrefix(std::string_view p, std::string_view* s) {
if (!HasPrefix(*s, p))
return false;
*s = s->substr(p.size());
return true;
}
-size_t GetGomaccPosForAndroidCompileCommand(StringPiece cmdline) {
+size_t GetGomaccPosForAndroidCompileCommand(std::string_view cmdline) {
size_t index = cmdline.find(' ');
if (index == std::string::npos)
return std::string::npos;
- StringPiece cmd = cmdline.substr(0, index);
+ std::string_view cmd = cmdline.substr(0, index);
if (HasSuffix(cmd, "ccache")) {
index++;
size_t pos = GetGomaccPosForAndroidCompileCommand(cmdline.substr(index));
@@ -97,30 +97,30 @@
return std::string::npos;
}
- StringPiece rest = cmdline.substr(index);
+ std::string_view rest = cmdline.substr(index);
return rest.find(" -c ") != std::string::npos ? 0 : std::string::npos;
}
-static bool GetDepfileFromCommandImpl(StringPiece cmd, std::string* out) {
+static bool GetDepfileFromCommandImpl(std::string_view cmd, std::string* out) {
if ((FindCommandLineFlag(cmd, " -MD") == std::string::npos &&
FindCommandLineFlag(cmd, " -MMD") == std::string::npos) ||
FindCommandLineFlag(cmd, " -c") == std::string::npos) {
return false;
}
- StringPiece mf = FindCommandLineFlagWithArg(cmd, " -MF");
+ std::string_view mf = FindCommandLineFlagWithArg(cmd, " -MF");
if (!mf.empty()) {
- mf.AppendToString(out);
+ out->append(mf);
return true;
}
- StringPiece o = FindCommandLineFlagWithArg(cmd, " -o");
+ std::string_view o = FindCommandLineFlagWithArg(cmd, " -o");
if (o.empty()) {
- ERROR("Cannot find the depfile in %s", cmd.as_string().c_str());
+ ERROR("Cannot find the depfile in %s", std::string(cmd).c_str());
return false;
}
- StripExt(o).AppendToString(out);
+ out->append(StripExt(o));
*out += ".d";
return true;
}
@@ -138,8 +138,7 @@
// TODO: A hack for Makefiles generated by automake.
// A hack for Android to get .P files instead of .d.
- std::string p;
- StripExt(*out).AppendToString(&p);
+ std::string p{StripExt(*out)};
p += ".P";
if (cmd->find(p) != std::string::npos) {
const std::string rm_f = "; rm -f " + *out;
@@ -154,7 +153,7 @@
// A hack for Android. For .s files, GCC does not use C
// preprocessor, so it ignores -MF flag.
std::string as = "/";
- StripExt(Basename(*out)).AppendToString(&as);
+ as.append(StripExt(Basename(*out)));
as += ".s";
if (cmd->find(as) != std::string::npos) {
return false;
@@ -257,7 +256,7 @@
}
}
- StringPiece TranslateCommand(const char* in, std::string* cmd_buf) {
+ std::string_view TranslateCommand(const char* in, std::string* cmd_buf) {
const size_t orig_size = cmd_buf->size();
bool prev_backslash = false;
// Set space as an initial value so the leading comment will be
@@ -327,27 +326,27 @@
cmd_buf->resize(cmd_buf->size() - 1);
}
- return StringPiece(cmd_buf->data() + orig_size,
- cmd_buf->size() - orig_size);
+ return std::string_view(cmd_buf->data() + orig_size,
+ cmd_buf->size() - orig_size);
}
- bool IsOutputMkdir(const char* name, StringPiece cmd) {
+ bool IsOutputMkdir(const char* name, std::string_view cmd) {
if (!HasPrefix(cmd, "mkdir -p ")) {
return false;
}
cmd = cmd.substr(9, cmd.size());
- if (cmd.get(cmd.size() - 1) == '/') {
- cmd = cmd.substr(0, cmd.size() - 1);
+ if (!cmd.empty() && cmd.back() == '/') {
+ cmd.remove_suffix(1);
}
- StringPiece dir = Dirname(name);
+ std::string_view dir = Dirname(name);
if (cmd == dir) {
return true;
}
return false;
}
- bool GetDescriptionFromCommand(StringPiece cmd, std::string* out) {
+ bool GetDescriptionFromCommand(std::string_view cmd, std::string* out) {
if (!HasPrefix(cmd, "echo ")) {
return false;
}
@@ -358,7 +357,7 @@
std::string out_buf;
// Strip outer quotes, and fail if it is not a single echo command
- for (StringPiece::iterator in = cmd.begin(); in != cmd.end(); in++) {
+ for (std::string_view::iterator in = cmd.begin(); in != cmd.end(); in++) {
if (prev_backslash) {
prev_backslash = false;
out_buf += *in;
@@ -421,13 +420,13 @@
*cmd_buf += '(';
size_t cmd_start = cmd_buf->size();
- StringPiece translated = TranslateCommand(in, cmd_buf);
+ std::string_view translated = TranslateCommand(in, cmd_buf);
if (g_flags.detect_android_echo && !got_descritpion && !c.echo &&
GetDescriptionFromCommand(translated, description)) {
got_descritpion = true;
- translated.clear();
+ translated = std::string_view();
} else if (IsOutputMkdir(name, translated) && !c.echo && cmd_begin == 0) {
- translated.clear();
+ translated = std::string_view();
}
if (translated.empty()) {
cmd_buf->resize(cmd_begin);
@@ -666,8 +665,8 @@
// PATH changes $(shell).
used_env_vars.insert(Intern("PATH"));
for (Symbol e : used_env_vars) {
- StringPiece val(getenv(e.c_str()));
- used_envs_.emplace(e.str(), val.as_string());
+ std::string_view val(getenv(e.c_str()));
+ used_envs_.emplace(e.str(), std::string(val));
}
}
@@ -771,7 +770,7 @@
if (cr->op == CommandOp::FIND) {
std::vector<std::string> missing_dirs;
- for (StringPiece fd : cr->find->finddirs) {
+ for (std::string_view fd : cr->find->finddirs) {
const std::string& d = ConcatDir(cr->find->chdir, fd);
if (!Exists(d))
missing_dirs.push_back(d);
@@ -782,12 +781,12 @@
}
DumpInt(fp, cr->find->found_files->size());
- for (StringPiece s : *cr->find->found_files) {
+ for (std::string_view s : *cr->find->found_files) {
DumpString(fp, ConcatDir(cr->find->chdir, s));
}
DumpInt(fp, cr->find->read_dirs->size());
- for (StringPiece s : *cr->find->read_dirs) {
+ for (std::string_view s : *cr->find->read_dirs) {
DumpString(fp, ConcatDir(cr->find->chdir, s));
}
}
diff --git a/src/ninja.h b/src/ninja.h
index 932d186..521ad4c 100644
--- a/src/ninja.h
+++ b/src/ninja.h
@@ -18,10 +18,10 @@
#include <time.h>
#include <string>
+#include <string_view>
#include <vector>
#include "dep.h"
-#include "string_piece.h"
class Evaluator;
@@ -36,6 +36,6 @@
// Exposed only for test.
bool GetDepfileFromCommand(std::string* cmd, std::string* out);
-size_t GetGomaccPosForAndroidCompileCommand(StringPiece cmdline);
+size_t GetGomaccPosForAndroidCompileCommand(std::string_view cmdline);
#endif // NINJA_H_
diff --git a/src/parser.cc b/src/parser.cc
index 323d9f6..11da3c7 100644
--- a/src/parser.cc
+++ b/src/parser.cc
@@ -17,6 +17,7 @@
#include "parser.h"
#include <stack>
+#include <string_view>
#include <unordered_map>
#include "expr.h"
@@ -25,7 +26,6 @@
#include "log.h"
#include "stats.h"
#include "stmt.h"
-#include "string_piece.h"
#include "strutil.h"
enum struct ParserState {
@@ -41,12 +41,12 @@
int num_nest;
};
- typedef void (Parser::*DirectiveHandler)(StringPiece line,
- StringPiece directive);
- typedef std::unordered_map<StringPiece, DirectiveHandler> DirectiveMap;
+ typedef void (Parser::*DirectiveHandler)(std::string_view line,
+ std::string_view directive);
+ typedef std::unordered_map<std::string_view, DirectiveHandler> DirectiveMap;
public:
- Parser(StringPiece buf, const char* filename, std::vector<Stmt*>* stmts)
+ Parser(std::string_view buf, const char* filename, std::vector<Stmt*>* stmts)
: buf_(buf),
state_(ParserState::NOT_AFTER_RULE),
stmts_(stmts),
@@ -56,7 +56,7 @@
loc_(filename, 0),
fixed_lineno_(false) {}
- Parser(StringPiece buf, const Loc& loc, std::vector<Stmt*>* stmts)
+ Parser(std::string_view buf, const Loc& loc, std::vector<Stmt*>* stmts)
: buf_(buf),
state_(ParserState::NOT_AFTER_RULE),
stmts_(stmts),
@@ -73,8 +73,8 @@
size_t e = FindEndOfLine(&lf_cnt);
if (!fixed_lineno_)
loc_.lineno++;
- StringPiece line(buf_.data() + l_, e - l_);
- if (line.get(line.size() - 1) == '\r')
+ std::string_view line(buf_.data() + l_, e - l_);
+ if (!line.empty() && line.back() == '\r')
line.remove_suffix(1);
orig_line_with_directives_ = line;
ParseLine(line);
@@ -111,12 +111,12 @@
}
Value* ParseExpr(Loc* loc,
- StringPiece s,
+ std::string_view s,
ParseExprOpt opt = ParseExprOpt::NORMAL) {
return ::ParseExpr(loc, s, opt);
}
- void ParseLine(StringPiece line) {
+ void ParseLine(std::string_view line) {
if (!define_name_.empty()) {
ParseInsideDefine(line);
return;
@@ -150,13 +150,13 @@
ParseRuleOrAssign(line);
}
- void ParseRuleOrAssign(StringPiece line) {
+ void ParseRuleOrAssign(std::string_view line) {
size_t sep = FindThreeOutsideParen(line, ':', '=', ';');
if (sep == std::string::npos || line[sep] == ';') {
ParseRule(line, std::string::npos);
} else if (line[sep] == '=') {
ParseAssign(line, sep);
- } else if (line.get(sep + 1) == '=') {
+ } else if (sep + 1 < line.size() && line[sep + 1] == '=') {
ParseAssign(line, sep + 1);
} else if (line[sep] == ':') {
ParseRule(line, sep);
@@ -165,7 +165,7 @@
}
}
- void ParseRule(StringPiece line, size_t sep) {
+ void ParseRule(std::string_view line, size_t sep) {
if (current_directive_ != AssignDirective::NONE) {
if (IsInExport())
return;
@@ -219,13 +219,13 @@
state_ = is_rule ? ParserState::AFTER_RULE : ParserState::MAYBE_AFTER_RULE;
}
- void ParseAssign(StringPiece line, size_t separator_pos) {
+ void ParseAssign(std::string_view line, size_t separator_pos) {
if (separator_pos == 0) {
Error("*** empty variable name ***");
return;
}
- StringPiece lhs;
- StringPiece rhs;
+ std::string_view lhs;
+ std::string_view rhs;
AssignOp op;
ParseAssignStatement(line, separator_pos, &lhs, &rhs, &op);
@@ -252,7 +252,7 @@
state_ = ParserState::NOT_AFTER_RULE;
}
- void ParseInclude(StringPiece line, StringPiece directive) {
+ void ParseInclude(std::string_view line, std::string_view directive) {
IncludeStmt* stmt = new IncludeStmt();
stmt->set_loc(loc_);
Loc mutable_loc(loc_);
@@ -262,7 +262,7 @@
state_ = ParserState::NOT_AFTER_RULE;
}
- void ParseDefine(StringPiece line, StringPiece) {
+ void ParseDefine(std::string_view line, std::string_view) {
if (line.empty()) {
Error("*** empty variable name.");
return;
@@ -274,9 +274,9 @@
state_ = ParserState::NOT_AFTER_RULE;
}
- void ParseInsideDefine(StringPiece line) {
+ void ParseInsideDefine(std::string_view line) {
line = TrimLeftSpace(line);
- StringPiece directive = GetDirective(line);
+ std::string_view directive = GetDirective(line);
if (directive == "define")
num_define_nest_++;
else if (directive == "endef")
@@ -287,8 +287,8 @@
return;
}
- StringPiece rest = TrimRightSpace(
- RemoveComment(TrimLeftSpace(line.substr(sizeof("endef")))));
+ std::string_view rest = TrimRightSpace(
+ RemoveComment(TrimLeftSpace(line.substr(sizeof("endef") - 1))));
if (!rest.empty()) {
WARN_LOC(loc_, "extraneous text after `endef' directive");
}
@@ -298,7 +298,7 @@
Loc mutable_loc(stmt->loc());
stmt->lhs = ParseExpr(&mutable_loc, define_name_);
mutable_loc.lineno++;
- StringPiece rhs;
+ std::string_view rhs;
if (define_start_)
rhs = buf_.substr(define_start_, l_ - define_start_ - 1);
stmt->rhs = ParseExpr(&mutable_loc, rhs, ParseExprOpt::DEFINE);
@@ -306,7 +306,7 @@
stmt->op = AssignOp::EQ;
stmt->directive = current_directive_;
out_stmts_->push_back(stmt);
- define_name_.clear();
+ define_name_ = std::string_view();
}
void EnterIf(IfStmt* stmt) {
@@ -318,7 +318,7 @@
out_stmts_ = &stmt->true_stmts;
}
- void ParseIfdef(StringPiece line, StringPiece directive) {
+ void ParseIfdef(std::string_view line, std::string_view directive) {
IfStmt* stmt = new IfStmt();
stmt->set_loc(loc_);
stmt->op = directive[2] == 'n' ? CondOp::IFNDEF : CondOp::IFDEF;
@@ -329,7 +329,7 @@
EnterIf(stmt);
}
- bool ParseIfEqCond(StringPiece s, IfStmt* stmt) {
+ bool ParseIfEqCond(std::string_view s, IfStmt* stmt) {
if (s.empty()) {
return false;
}
@@ -346,7 +346,7 @@
s = TrimLeftSpace(s.substr(n + 1));
stmt->rhs =
ParseExprImpl(&mutable_loc, s, NULL, ParseExprOpt::NORMAL, &n);
- s = TrimLeftSpace(s.substr(n));
+ s = TrimLeftSpace(s.substr(std::min(n, s.size())));
} else {
for (int i = 0; i < 2; i++) {
if (s.empty())
@@ -373,7 +373,7 @@
return true;
}
- void ParseIfeq(StringPiece line, StringPiece directive) {
+ void ParseIfeq(std::string_view line, std::string_view directive) {
IfStmt* stmt = new IfStmt();
stmt->set_loc(loc_);
stmt->op = directive[2] == 'n' ? CondOp::IFNEQ : CondOp::IFEQ;
@@ -387,7 +387,7 @@
EnterIf(stmt);
}
- void ParseElse(StringPiece line, StringPiece) {
+ void ParseElse(std::string_view line, std::string_view) {
if (!CheckIfStack("else"))
return;
IfState* st = if_stack_.top();
@@ -398,7 +398,7 @@
st->is_in_else = true;
out_stmts_ = &st->stmt->false_stmts;
- StringPiece next_if = TrimLeftSpace(line);
+ std::string_view next_if = TrimLeftSpace(line);
if (next_if.empty())
return;
@@ -409,7 +409,7 @@
num_if_nest_ = 0;
}
- void ParseEndif(StringPiece line, StringPiece) {
+ void ParseEndif(std::string_view line, std::string_view) {
if (!CheckIfStack("endif"))
return;
if (!line.empty()) {
@@ -437,7 +437,7 @@
static_cast<int>(AssignDirective::EXPORT));
}
- void CreateExport(StringPiece line, bool is_export) {
+ void CreateExport(std::string_view line, bool is_export) {
ExportStmt* stmt = new ExportStmt;
stmt->set_loc(loc_);
Loc mutable_loc(loc_);
@@ -446,7 +446,7 @@
out_stmts_->push_back(stmt);
}
- void ParseOverride(StringPiece line, StringPiece) {
+ void ParseOverride(std::string_view line, std::string_view) {
current_directive_ = static_cast<AssignDirective>(
(static_cast<int>(current_directive_) |
static_cast<int>(AssignDirective::OVERRIDE)));
@@ -458,7 +458,7 @@
ParseRuleOrAssign(line);
}
- void ParseExport(StringPiece line, StringPiece) {
+ void ParseExport(std::string_view line, std::string_view) {
current_directive_ = static_cast<AssignDirective>(
(static_cast<int>(current_directive_) |
static_cast<int>(AssignDirective::EXPORT)));
@@ -468,7 +468,7 @@
ParseRuleOrAssign(line);
}
- void ParseUnexport(StringPiece line, StringPiece) {
+ void ParseUnexport(std::string_view line, std::string_view) {
CreateExport(line, false);
}
bool CheckIfStack(const char* keyword) {
@@ -479,46 +479,47 @@
return true;
}
- StringPiece RemoveComment(StringPiece line) {
+ std::string_view RemoveComment(std::string_view line) {
size_t i = FindOutsideParen(line, '#');
if (i == std::string::npos)
return line;
return line.substr(0, i);
}
- StringPiece GetDirective(StringPiece line) {
+ std::string_view GetDirective(std::string_view line) {
if (line.size() < shortest_directive_len_)
- return StringPiece();
- StringPiece prefix = line.substr(0, longest_directive_len_ + 1);
+ return std::string_view();
+ std::string_view prefix = line.substr(0, longest_directive_len_ + 1);
size_t space_index = prefix.find_first_of(" \t#");
return prefix.substr(0, space_index);
}
- bool HandleDirective(StringPiece line, const DirectiveMap& directive_map) {
- StringPiece directive = GetDirective(line);
+ bool HandleDirective(std::string_view line,
+ const DirectiveMap& directive_map) {
+ std::string_view directive = GetDirective(line);
auto found = directive_map.find(directive);
if (found == directive_map.end())
return false;
- StringPiece rest = TrimRightSpace(
+ std::string_view rest = TrimRightSpace(
RemoveComment(TrimLeftSpace(line.substr(directive.size()))));
(this->*found->second)(rest, directive);
return true;
}
- StringPiece buf_;
+ std::string_view buf_;
size_t l_;
ParserState state_;
std::vector<Stmt*>* stmts_;
std::vector<Stmt*>* out_stmts_;
- StringPiece define_name_;
+ std::string_view define_name_;
int num_define_nest_;
size_t define_start_;
int define_start_line_;
- StringPiece orig_line_with_directives_;
+ std::string_view orig_line_with_directives_;
AssignDirective current_directive_;
int num_if_nest_;
@@ -536,18 +537,20 @@
void Parse(Makefile* mk) {
COLLECT_STATS("parse file time");
- Parser parser(StringPiece(mk->buf()), mk->filename().c_str(),
+ Parser parser(std::string_view(mk->buf()), mk->filename().c_str(),
mk->mutable_stmts());
parser.Parse();
}
-void Parse(StringPiece buf, const Loc& loc, std::vector<Stmt*>* out_stmts) {
+void Parse(std::string_view buf,
+ const Loc& loc,
+ std::vector<Stmt*>* out_stmts) {
COLLECT_STATS("parse eval time");
Parser parser(buf, loc, out_stmts);
parser.Parse();
}
-void ParseNotAfterRule(StringPiece buf,
+void ParseNotAfterRule(std::string_view buf,
const Loc& loc,
std::vector<Stmt*>* out_stmts) {
Parser parser(buf, loc, out_stmts);
@@ -597,10 +600,10 @@
std::vector<ParseErrorStmt*> Parser::parse_errors;
-void ParseAssignStatement(StringPiece line,
+void ParseAssignStatement(std::string_view line,
size_t sep,
- StringPiece* lhs,
- StringPiece* rhs,
+ std::string_view* lhs,
+ std::string_view* rhs,
AssignOp* op) {
CHECK(sep != 0);
*op = AssignOp::EQ;
@@ -620,7 +623,7 @@
break;
}
*lhs = TrimSpace(line.substr(0, lhs_end));
- *rhs = TrimLeftSpace(line.substr(sep + 1));
+ *rhs = TrimLeftSpace(line.substr(std::min(sep + 1, line.size())));
}
const std::vector<ParseErrorStmt*>& GetParseErrors() {
diff --git a/src/parser.h b/src/parser.h
index ad855df..d0457d2 100644
--- a/src/parser.h
+++ b/src/parser.h
@@ -15,24 +15,24 @@
#ifndef PARSER_H_
#define PARSER_H_
+#include <string_view>
#include <vector>
#include "loc.h"
#include "stmt.h"
-#include "string_piece.h"
class Makefile;
void Parse(Makefile* mk);
-void Parse(StringPiece buf, const Loc& loc, std::vector<Stmt*>* out_asts);
-void ParseNotAfterRule(StringPiece buf,
+void Parse(std::string_view buf, const Loc& loc, std::vector<Stmt*>* out_asts);
+void ParseNotAfterRule(std::string_view buf,
const Loc& loc,
std::vector<Stmt*>* out_asts);
-void ParseAssignStatement(StringPiece line,
+void ParseAssignStatement(std::string_view line,
size_t sep,
- StringPiece* lhs,
- StringPiece* rhs,
+ std::string_view* lhs,
+ std::string_view* rhs,
AssignOp* op);
const std::vector<ParseErrorStmt*>& GetParseErrors();
diff --git a/src/regen.cc b/src/regen.cc
index d32d025..0f2bb1c 100644
--- a/src/regen.cc
+++ b/src/regen.cc
@@ -44,9 +44,10 @@
return true; \
} while (0)
-bool ShouldIgnoreDirty(StringPiece s) {
- Pattern pat(g_flags.ignore_dirty_pattern);
- Pattern nopat(g_flags.no_ignore_dirty_pattern);
+bool ShouldIgnoreDirty(std::string_view s) {
+ Pattern pat(g_flags.ignore_dirty_pattern ? g_flags.ignore_dirty_pattern : "");
+ Pattern nopat(
+ g_flags.no_ignore_dirty_pattern ? g_flags.no_ignore_dirty_pattern : "");
return pat.Match(s) && !nopat.Match(s);
}
@@ -201,7 +202,7 @@
int num_envs = LOAD_INT(fp);
for (int i = 0; i < num_envs; i++) {
LOAD_STRING(fp, &s);
- StringPiece val(getenv(s.c_str()));
+ std::string_view val(getenv(s.c_str()));
LOAD_STRING(fp, &s2);
if (val != s2) {
if (g_flags.dump_kati_stamp) {
diff --git a/src/regen_dump.cc b/src/regen_dump.cc
index 5ee0159..70034dc 100644
--- a/src/regen_dump.cc
+++ b/src/regen_dump.cc
@@ -29,6 +29,8 @@
#include "log.h"
#include "strutil.h"
+using namespace std;
+
vector<std::string> LoadVecString(FILE* fp) {
int count = LoadInt(fp);
if (count < 0) {
diff --git a/src/rule.cc b/src/rule.cc
index 07116d2..01692d1 100644
--- a/src/rule.cc
+++ b/src/rule.cc
@@ -25,7 +25,7 @@
Rule::Rule() : is_double_colon(false), is_suffix_rule(false), cmd_lineno(0) {}
-void Rule::ParseInputs(const StringPiece& inputs_str) {
+void Rule::ParseInputs(const std::string_view& inputs_str) {
bool is_order_only = false;
for (auto const& input : WordScanner(inputs_str)) {
if (input == "|") {
@@ -37,7 +37,7 @@
}
}
-void Rule::ParsePrerequisites(const StringPiece& line,
+void Rule::ParsePrerequisites(const std::string_view& line,
size_t separator_pos,
const RuleStmt* rule_stmt) {
// line is either
@@ -46,7 +46,7 @@
// target-prerequisites : prereq-patterns [ ; command ]
// First, separate command. At this point separator_pos should point to ';'
// unless null.
- StringPiece prereq_string = line;
+ std::string_view prereq_string = line;
if (separator_pos != std::string::npos &&
rule_stmt->sep != RuleStmt::SEP_SEMICOLON) {
CHECK(line[separator_pos] == ';');
@@ -73,10 +73,10 @@
return;
}
- StringPiece target_prereq = prereq_string.substr(0, separator_pos);
- StringPiece prereq_patterns = prereq_string.substr(separator_pos + 1);
+ std::string_view target_prereq = prereq_string.substr(0, separator_pos);
+ std::string_view prereq_patterns = prereq_string.substr(separator_pos + 1);
- for (StringPiece target_pattern : WordScanner(target_prereq)) {
+ for (std::string_view target_pattern : WordScanner(target_prereq)) {
target_pattern = TrimLeadingCurdir(target_pattern);
for (Symbol target : outputs) {
if (!Pattern(target_pattern).Match(target.str())) {
diff --git a/src/rule.h b/src/rule.h
index bbf5d45..59f6de6 100644
--- a/src/rule.h
+++ b/src/rule.h
@@ -17,12 +17,12 @@
#include <functional>
#include <string>
+#include <string_view>
#include <vector>
#include "loc.h"
#include "log.h"
#include "stmt.h"
-#include "string_piece.h"
#include "symtab.h"
class Value;
@@ -35,13 +35,13 @@
std::string DebugString() const;
- void ParseInputs(const StringPiece& inputs_string);
+ void ParseInputs(const std::string_view& inputs_string);
- void ParsePrerequisites(const StringPiece& line,
+ void ParsePrerequisites(const std::string_view& line,
size_t pos,
const RuleStmt* rule_stmt);
- static bool IsPatternRule(const StringPiece& target_string) {
+ static bool IsPatternRule(const std::string_view& target_string) {
return target_string.find('%') != std::string::npos;
}
diff --git a/src/stmt.cc b/src/stmt.cc
index bdc3406..7c7d4f4 100644
--- a/src/stmt.cc
+++ b/src/stmt.cc
@@ -68,7 +68,7 @@
"AssignStmt(lhs=%s rhs=%s (%s) "
"opstr=%s dir=%s loc=%s:%d)",
Value::DebugString(lhs).c_str(), Value::DebugString(rhs).c_str(),
- NoLineBreak(orig_rhs.as_string()).c_str(), opstr, dirstr, LOCF(loc()));
+ NoLineBreak(std::string(orig_rhs)).c_str(), opstr, dirstr, LOCF(loc()));
}
Symbol AssignStmt::GetLhsSymbol(Evaluator* ev) const {
diff --git a/src/stmt.h b/src/stmt.h
index 1e96abc..1173f1b 100644
--- a/src/stmt.h
+++ b/src/stmt.h
@@ -16,10 +16,10 @@
#define STMT_H_
#include <string>
+#include <string_view>
#include <vector>
#include "loc.h"
-#include "string_piece.h"
#include "symtab.h"
class Evaluator;
@@ -51,7 +51,7 @@
Loc loc() const { return loc_; }
void set_loc(Loc loc) { loc_ = loc; }
- StringPiece orig() const { return orig_; }
+ std::string_view orig() const { return orig_; }
void Eval(Evaluator*) const;
virtual void EvalStatement(Evaluator* ev) const = 0;
@@ -63,7 +63,7 @@
private:
Loc loc_;
- StringPiece orig_;
+ std::string_view orig_;
};
/* Parsed "rule statement" before evaluation is kept as
@@ -88,7 +88,7 @@
struct AssignStmt : public Stmt {
Value* lhs;
Value* rhs;
- StringPiece orig_rhs;
+ std::string_view orig_rhs;
AssignOp op;
AssignDirective directive;
bool is_final;
@@ -108,7 +108,7 @@
struct CommandStmt : public Stmt {
Value* expr;
- StringPiece orig;
+ std::string_view orig;
virtual ~CommandStmt();
diff --git a/src/string_piece.cc b/src/string_piece.cc
deleted file mode 100644
index 32a7be0..0000000
--- a/src/string_piece.cc
+++ /dev/null
@@ -1,239 +0,0 @@
-// Copyright 2015 Google Inc. All rights reserved
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// Copyright (c) 2011 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-// Copied from strings/stringpiece.cc with modifications
-
-// +build ignore
-
-#include "string_piece.h"
-
-#include <ctype.h>
-#include <limits.h>
-#include <stdint.h>
-
-#include <algorithm>
-#include <ostream>
-
-typedef StringPiece::size_type size_type;
-
-bool operator==(const StringPiece& x, const StringPiece& y) {
- if (x.size() != y.size())
- return false;
- size_t len = x.size();
- if (len >= sizeof(uint64_t)) {
- len -= sizeof(uint64_t);
- uint64_t xt = *reinterpret_cast<const uint64_t*>(x.data() + len);
- uint64_t yt = *reinterpret_cast<const uint64_t*>(y.data() + len);
- if (xt != yt)
- return false;
- }
- return StringPiece::wordmemcmp(x.data(), y.data(), len) == 0;
-}
-
-void StringPiece::CopyToString(std::string* target) const {
- target->assign(!empty() ? data() : "", size());
-}
-
-void StringPiece::AppendToString(std::string* target) const {
- if (!empty())
- target->append(data(), size());
-}
-
-size_type StringPiece::copy(char* buf, size_type n, size_type pos) const {
- size_type ret = std::min(length_ - pos, n);
- memcpy(buf, ptr_ + pos, ret);
- return ret;
-}
-
-size_type StringPiece::find(const StringPiece& s, size_type pos) const {
- if (pos > length_)
- return npos;
-
- const char* result =
- std::search(ptr_ + pos, ptr_ + length_, s.ptr_, s.ptr_ + s.length_);
- const size_type xpos = result - ptr_;
- return xpos + s.length_ <= length_ ? xpos : npos;
-}
-
-size_type StringPiece::find(char c, size_type pos) const {
- if (pos >= length_)
- return npos;
-
- const char* result = std::find(ptr_ + pos, ptr_ + length_, c);
- return result != ptr_ + length_ ? static_cast<size_t>(result - ptr_) : npos;
-}
-
-size_type StringPiece::rfind(const StringPiece& s, size_type pos) const {
- if (length_ < s.length_)
- return npos;
-
- if (s.empty())
- return std::min(length_, pos);
-
- const char* last = ptr_ + std::min(length_ - s.length_, pos) + s.length_;
- const char* result = std::find_end(ptr_, last, s.ptr_, s.ptr_ + s.length_);
- return result != last ? static_cast<size_t>(result - ptr_) : npos;
-}
-
-size_type StringPiece::rfind(char c, size_type pos) const {
- if (length_ == 0)
- return npos;
-
- for (size_type i = std::min(pos, length_ - 1);; --i) {
- if (ptr_[i] == c)
- return i;
- if (i == 0)
- break;
- }
- return npos;
-}
-
-// For each character in characters_wanted, sets the index corresponding
-// to the ASCII code of that character to 1 in table. This is used by
-// the find_.*_of methods below to tell whether or not a character is in
-// the lookup table in constant time.
-// The argument `table' must be an array that is large enough to hold all
-// the possible values of an unsigned char. Thus it should be be declared
-// as follows:
-// bool table[UCHAR_MAX + 1]
-static inline void BuildLookupTable(const StringPiece& characters_wanted,
- bool* table) {
- const size_type length = characters_wanted.length();
- const char* const data = characters_wanted.data();
- for (size_type i = 0; i < length; ++i) {
- table[static_cast<unsigned char>(data[i])] = true;
- }
-}
-
-size_type StringPiece::find_first_of(const StringPiece& s,
- size_type pos) const {
- if (length_ == 0 || s.length_ == 0)
- return npos;
-
- // Avoid the cost of BuildLookupTable() for a single-character search.
- if (s.length_ == 1)
- return find_first_of(s.ptr_[0], pos);
-
- bool lookup[UCHAR_MAX + 1] = {false};
- BuildLookupTable(s, lookup);
- for (size_type i = pos; i < length_; ++i) {
- if (lookup[static_cast<unsigned char>(ptr_[i])]) {
- return i;
- }
- }
- return npos;
-}
-
-size_type StringPiece::find_first_not_of(const StringPiece& s,
- size_type pos) const {
- if (length_ == 0)
- return npos;
-
- if (s.length_ == 0)
- return 0;
-
- // Avoid the cost of BuildLookupTable() for a single-character search.
- if (s.length_ == 1)
- return find_first_not_of(s.ptr_[0], pos);
-
- bool lookup[UCHAR_MAX + 1] = {false};
- BuildLookupTable(s, lookup);
- for (size_type i = pos; i < length_; ++i) {
- if (!lookup[static_cast<unsigned char>(ptr_[i])]) {
- return i;
- }
- }
- return npos;
-}
-
-size_type StringPiece::find_first_not_of(char c, size_type pos) const {
- if (length_ == 0)
- return npos;
-
- for (; pos < length_; ++pos) {
- if (ptr_[pos] != c) {
- return pos;
- }
- }
- return npos;
-}
-
-size_type StringPiece::find_last_of(const StringPiece& s, size_type pos) const {
- if (length_ == 0 || s.length_ == 0)
- return npos;
-
- // Avoid the cost of BuildLookupTable() for a single-character search.
- if (s.length_ == 1)
- return find_last_of(s.ptr_[0], pos);
-
- bool lookup[UCHAR_MAX + 1] = {false};
- BuildLookupTable(s, lookup);
- for (size_type i = std::min(pos, length_ - 1);; --i) {
- if (lookup[static_cast<unsigned char>(ptr_[i])])
- return i;
- if (i == 0)
- break;
- }
- return npos;
-}
-
-size_type StringPiece::find_last_not_of(const StringPiece& s,
- size_type pos) const {
- if (length_ == 0)
- return npos;
-
- size_type i = std::min(pos, length_ - 1);
- if (s.length_ == 0)
- return i;
-
- // Avoid the cost of BuildLookupTable() for a single-character search.
- if (s.length_ == 1)
- return find_last_not_of(s.ptr_[0], pos);
-
- bool lookup[UCHAR_MAX + 1] = {false};
- BuildLookupTable(s, lookup);
- for (;; --i) {
- if (!lookup[static_cast<unsigned char>(ptr_[i])])
- return i;
- if (i == 0)
- break;
- }
- return npos;
-}
-
-size_type StringPiece::find_last_not_of(char c, size_type pos) const {
- if (length_ == 0)
- return npos;
-
- for (size_type i = std::min(pos, length_ - 1);; --i) {
- if (ptr_[i] != c)
- return i;
- if (i == 0)
- break;
- }
- return npos;
-}
-
-StringPiece StringPiece::substr(size_type pos, size_type n) const {
- if (pos > length_)
- pos = length_;
- if (n > length_ - pos)
- n = length_ - pos;
- return StringPiece(ptr_ + pos, n);
-}
-
-const StringPiece::size_type StringPiece::npos = size_type(-1);
diff --git a/src/string_piece.h b/src/string_piece.h
deleted file mode 100644
index df3562f..0000000
--- a/src/string_piece.h
+++ /dev/null
@@ -1,224 +0,0 @@
-// Copyright 2015 Google Inc. All rights reserved
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// Copyright (c) 2011 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-// Copied from strings/stringpiece.h with modifications
-//
-// A string-like object that points to a sized piece of memory.
-//
-// Functions or methods may use const StringPiece& parameters to accept either
-// a "const char*" or a "string" value that will be implicitly converted to
-// a StringPiece. The implicit conversion means that it is often appropriate
-// to include this .h file in other files rather than forward-declaring
-// StringPiece as would be appropriate for most other Google classes.
-//
-// Systematic usage of StringPiece is encouraged as it will reduce unnecessary
-// conversions from "const char*" to "string" and back again.
-//
-
-#ifndef BASE_STRING_PIECE_H_
-#define BASE_STRING_PIECE_H_
-#pragma once
-
-#include <stddef.h>
-#include <string.h>
-
-#include <string>
-
-//#include "base/base_api.h"
-//#include "base/basictypes.h"
-
-class StringPiece {
- public:
- // standard STL container boilerplate
- typedef size_t size_type;
- typedef char value_type;
- typedef const char* pointer;
- typedef const char& reference;
- typedef const char& const_reference;
- typedef ptrdiff_t difference_type;
- typedef const char* const_iterator;
- typedef const char* iterator;
- typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
- typedef std::reverse_iterator<iterator> reverse_iterator;
-
- static const size_type npos;
-
- public:
- // We provide non-explicit singleton constructors so users can pass
- // in a "const char*" or a "string" wherever a "StringPiece" is
- // expected.
- StringPiece() : ptr_(NULL), length_(0) {}
- StringPiece(const char* str)
- : ptr_(str), length_((str == NULL) ? 0 : strlen(str)) {}
- StringPiece(const std::string& str) : ptr_(str.data()), length_(str.size()) {}
- StringPiece(const std::string&& str)
- : ptr_(str.data()), length_(str.size()) {}
- StringPiece(const char* offset, size_type len) : ptr_(offset), length_(len) {}
-
- // data() may return a pointer to a buffer with embedded NULs, and the
- // returned buffer may or may not be null terminated. Therefore it is
- // typically a mistake to pass data() to a routine that expects a NUL
- // terminated string.
- const char* data() const { return ptr_; }
- size_type size() const { return length_; }
- size_type length() const { return length_; }
- bool empty() const { return length_ == 0; }
-
- void clear() {
- ptr_ = NULL;
- length_ = 0;
- }
- void set(const char* data, size_type len) {
- ptr_ = data;
- length_ = len;
- }
- void set(const char* str) {
- ptr_ = str;
- length_ = str ? strlen(str) : 0;
- }
- void set(const void* data, size_type len) {
- ptr_ = reinterpret_cast<const char*>(data);
- length_ = len;
- }
-
- char operator[](size_type i) const { return ptr_[i]; }
-
- void remove_prefix(size_type n) {
- ptr_ += n;
- length_ -= n;
- }
-
- void remove_suffix(size_type n) { length_ -= n; }
-
- int compare(const StringPiece& x) const {
- int r =
- wordmemcmp(ptr_, x.ptr_, (length_ < x.length_ ? length_ : x.length_));
- if (r == 0) {
- if (length_ < x.length_)
- r = -1;
- else if (length_ > x.length_)
- r = +1;
- }
- return r;
- }
-
- std::string as_string() const {
- // std::string doesn't like to take a NULL pointer even with a 0 size.
- return std::string(!empty() ? data() : "", size());
- }
-
- void CopyToString(std::string* target) const;
- void AppendToString(std::string* target) const;
-
- // Does "this" start with "x"
- bool starts_with(const StringPiece& x) const {
- return ((length_ >= x.length_) &&
- (wordmemcmp(ptr_, x.ptr_, x.length_) == 0));
- }
-
- // Does "this" end with "x"
- bool ends_with(const StringPiece& x) const {
- return ((length_ >= x.length_) &&
- (wordmemcmp(ptr_ + (length_ - x.length_), x.ptr_, x.length_) == 0));
- }
-
- iterator begin() const { return ptr_; }
- iterator end() const { return ptr_ + length_; }
- const_reverse_iterator rbegin() const {
- return const_reverse_iterator(ptr_ + length_);
- }
- const_reverse_iterator rend() const { return const_reverse_iterator(ptr_); }
-
- size_type max_size() const { return length_; }
- size_type capacity() const { return length_; }
-
- size_type copy(char* buf, size_type n, size_type pos = 0) const;
-
- size_type find(const StringPiece& s, size_type pos = 0) const;
- size_type find(char c, size_type pos = 0) const;
- size_type rfind(const StringPiece& s, size_type pos = npos) const;
- size_type rfind(char c, size_type pos = npos) const;
-
- size_type find_first_of(const StringPiece& s, size_type pos = 0) const;
- size_type find_first_of(char c, size_type pos = 0) const {
- return find(c, pos);
- }
- size_type find_first_not_of(const StringPiece& s, size_type pos = 0) const;
- size_type find_first_not_of(char c, size_type pos = 0) const;
- size_type find_last_of(const StringPiece& s, size_type pos = npos) const;
- size_type find_last_of(char c, size_type pos = npos) const {
- return rfind(c, pos);
- }
- size_type find_last_not_of(const StringPiece& s, size_type pos = npos) const;
- size_type find_last_not_of(char c, size_type pos = npos) const;
-
- StringPiece substr(size_type pos, size_type n = npos) const;
-
- static int wordmemcmp(const char* p, const char* p2, size_type N) {
- return memcmp(p, p2, N);
- }
-
- // kati specific functions will follow.
-
- char get(size_type i) const { return i < length_ ? ptr_[i] : 0; }
-
- private:
- const char* ptr_;
- size_type length_;
-};
-
-bool operator==(const StringPiece& x, const StringPiece& y);
-
-inline bool operator!=(const StringPiece& x, const StringPiece& y) {
- return !(x == y);
-}
-
-inline bool operator<(const StringPiece& x, const StringPiece& y) {
- const int r = StringPiece::wordmemcmp(
- x.data(), y.data(), (x.size() < y.size() ? x.size() : y.size()));
- return ((r < 0) || ((r == 0) && (x.size() < y.size())));
-}
-
-inline bool operator>(const StringPiece& x, const StringPiece& y) {
- return y < x;
-}
-
-inline bool operator<=(const StringPiece& x, const StringPiece& y) {
- return !(x > y);
-}
-
-inline bool operator>=(const StringPiece& x, const StringPiece& y) {
- return !(x < y);
-}
-
-namespace std {
-template <>
-struct hash<StringPiece> {
- size_t operator()(const StringPiece& s) const {
- size_t result = 0;
- for (char c : s) {
- result = (result * 131) + c;
- }
- return result;
- }
-};
-
-} // namespace std
-
-#define SPF(s) static_cast<int>((s).size()), (s).data()
-
-#endif // BASE_STRING_PIECE_H_
diff --git a/src/string_piece_test.cc b/src/string_piece_test.cc
deleted file mode 100644
index 275615f..0000000
--- a/src/string_piece_test.cc
+++ /dev/null
@@ -1,35 +0,0 @@
-// Copyright 2015 Google Inc. All rights reserved
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// +build ignore
-
-#include "string_piece.h"
-
-#include <assert.h>
-
-#include <unordered_set>
-
-int main() {
- std::unordered_set<StringPiece> sps;
- sps.insert(StringPiece("foo"));
- sps.insert(StringPiece("foo"));
- sps.insert(StringPiece("bar"));
- assert(sps.size() == 2);
- assert(sps.count(StringPiece("foo")) == 1);
- assert(sps.count(StringPiece("bar")) == 1);
-
- assert(StringPiece("hogefugahige") == StringPiece("hogefugahige"));
- assert(StringPiece("hogefugahoge") != StringPiece("hogefugahige"));
- assert(StringPiece("hogefugahige") != StringPiece("higefugahige"));
-}
diff --git a/src/strutil.cc b/src/strutil.cc
index 5d89241..ff240ae 100644
--- a/src/strutil.cc
+++ b/src/strutil.cc
@@ -53,11 +53,11 @@
return *this;
}
-StringPiece WordScanner::Iterator::operator*() const {
+std::string_view WordScanner::Iterator::operator*() const {
return in->substr(s, i - s);
}
-WordScanner::WordScanner(StringPiece in) : in_(in) {}
+WordScanner::WordScanner(std::string_view in) : in_(in) {}
WordScanner::Iterator WordScanner::begin() const {
Iterator iter;
@@ -76,8 +76,8 @@
return iter;
}
-void WordScanner::Split(std::vector<StringPiece>* o) {
- for (StringPiece t : *this)
+void WordScanner::Split(std::vector<std::string_view>* o) {
+ for (std::string_view t : *this)
o->push_back(t);
}
@@ -91,12 +91,13 @@
}
}
-void WordWriter::Write(StringPiece s) {
+void WordWriter::Write(std::string_view s) {
MaybeAddWhitespace();
AppendString(s, out_);
}
-ScopedTerminator::ScopedTerminator(StringPiece s) : s_(s), c_(s[s.size()]) {
+ScopedTerminator::ScopedTerminator(std::string_view s)
+ : s_(s), c_(s[s.size()]) {
const_cast<char*>(s_.data())[s_.size()] = '\0';
}
@@ -104,21 +105,21 @@
const_cast<char*>(s_.data())[s_.size()] = c_;
}
-void AppendString(StringPiece str, std::string* out) {
+void AppendString(std::string_view str, std::string* out) {
out->append(str.begin(), str.end());
}
-bool HasPrefix(StringPiece str, StringPiece prefix) {
+bool HasPrefix(std::string_view str, std::string_view prefix) {
ssize_t size_diff = str.size() - prefix.size();
return size_diff >= 0 && str.substr(0, prefix.size()) == prefix;
}
-bool HasSuffix(StringPiece str, StringPiece suffix) {
+bool HasSuffix(std::string_view str, std::string_view suffix) {
ssize_t size_diff = str.size() - suffix.size();
return size_diff >= 0 && str.substr(size_diff) == suffix;
}
-bool HasWord(StringPiece str, StringPiece w) {
+bool HasWord(std::string_view str, std::string_view w) {
size_t found = str.find(w);
if (found == std::string::npos)
return false;
@@ -130,41 +131,42 @@
return true;
}
-StringPiece TrimPrefix(StringPiece str, StringPiece prefix) {
+std::string_view TrimPrefix(std::string_view str, std::string_view prefix) {
ssize_t size_diff = str.size() - prefix.size();
if (size_diff < 0 || str.substr(0, prefix.size()) != prefix)
return str;
return str.substr(prefix.size());
}
-StringPiece TrimSuffix(StringPiece str, StringPiece suffix) {
+std::string_view TrimSuffix(std::string_view str, std::string_view suffix) {
ssize_t size_diff = str.size() - suffix.size();
if (size_diff < 0 || str.substr(size_diff) != suffix)
return str;
return str.substr(0, size_diff);
}
-Pattern::Pattern(StringPiece pat) : pat_(pat), percent_index_(pat.find('%')) {}
+Pattern::Pattern(std::string_view pat)
+ : pat_(pat), percent_index_(pat.find('%')) {}
-bool Pattern::Match(StringPiece str) const {
+bool Pattern::Match(std::string_view str) const {
if (percent_index_ == std::string::npos)
return str == pat_;
return MatchImpl(str);
}
-bool Pattern::MatchImpl(StringPiece str) const {
+bool Pattern::MatchImpl(std::string_view str) const {
return (HasPrefix(str, pat_.substr(0, percent_index_)) &&
HasSuffix(str, pat_.substr(percent_index_ + 1)));
}
-StringPiece Pattern::Stem(StringPiece str) const {
+std::string_view Pattern::Stem(std::string_view str) const {
if (!Match(str))
return "";
return str.substr(percent_index_, str.size() - pat_.size() + 1);
}
-void Pattern::AppendSubst(StringPiece str,
- StringPiece subst,
+void Pattern::AppendSubst(std::string_view str,
+ std::string_view subst,
std::string* out) const {
if (percent_index_ == std::string::npos) {
if (str == pat_) {
@@ -192,15 +194,15 @@
AppendString(str, out);
}
-void Pattern::AppendSubstRef(StringPiece str,
- StringPiece subst,
+void Pattern::AppendSubstRef(std::string_view str,
+ std::string_view subst,
std::string* out) const {
if (percent_index_ != std::string::npos &&
subst.find('%') != std::string::npos) {
AppendSubst(str, subst, out);
return;
}
- StringPiece s = TrimSuffix(str, pat_);
+ std::string_view s = TrimSuffix(str, pat_);
out->append(s.begin(), s.end());
out->append(subst.begin(), subst.end());
}
@@ -217,12 +219,12 @@
return r;
}
-StringPiece TrimLeftSpace(StringPiece s) {
+std::string_view TrimLeftSpace(std::string_view s) {
size_t i = 0;
for (; i < s.size(); i++) {
if (isSpace(s[i]))
continue;
- char n = s.get(i + 1);
+ char n = i + 1 < s.size() ? s[i + 1] : 0;
if (s[i] == '\\' && (n == '\r' || n == '\n')) {
i++;
continue;
@@ -232,12 +234,13 @@
return s.substr(i, s.size() - i);
}
-StringPiece TrimRightSpace(StringPiece s) {
+std::string_view TrimRightSpace(std::string_view s) {
size_t i = 0;
for (; i < s.size(); i++) {
char c = s[s.size() - 1 - i];
if (isSpace(c)) {
- if ((c == '\r' || c == '\n') && s.get(s.size() - 2 - i) == '\\')
+ if ((c == '\r' || c == '\n') && s.size() >= i + 2 &&
+ s[s.size() - 2 - i] == '\\')
i++;
continue;
}
@@ -246,34 +249,34 @@
return s.substr(0, s.size() - i);
}
-StringPiece TrimSpace(StringPiece s) {
+std::string_view TrimSpace(std::string_view s) {
return TrimRightSpace(TrimLeftSpace(s));
}
-StringPiece Dirname(StringPiece s) {
+std::string_view Dirname(std::string_view s) {
size_t found = s.rfind('/');
if (found == std::string::npos)
- return StringPiece(".");
+ return std::string_view(".");
if (found == 0)
- return StringPiece("");
+ return std::string_view("");
return s.substr(0, found);
}
-StringPiece Basename(StringPiece s) {
+std::string_view Basename(std::string_view s) {
size_t found = s.rfind('/');
if (found == std::string::npos || found == 0)
return s;
return s.substr(found + 1);
}
-StringPiece GetExt(StringPiece s) {
+std::string_view GetExt(std::string_view s) {
size_t found = s.rfind('.');
if (found == std::string::npos)
- return StringPiece("");
+ return std::string_view("");
return s.substr(found);
}
-StringPiece StripExt(StringPiece s) {
+std::string_view StripExt(std::string_view s) {
size_t slash_index = s.rfind('/');
size_t found = s.rfind('.');
if (found == std::string::npos ||
@@ -298,7 +301,8 @@
continue;
}
- StringPiece prev_dir = StringPiece(o->data() + prev_start, j - prev_start);
+ std::string_view prev_dir =
+ std::string_view(o->data() + prev_start, j - prev_start);
if (prev_dir == ".") {
j--;
} else if (prev_dir == ".." && j != 2 /* .. */) {
@@ -314,7 +318,7 @@
} else {
j++;
}
- if (StringPiece(o->data() + j, 3) == "../") {
+ if (std::string_view(o->data() + j, 3) == "../") {
j = orig_j;
(*o)[j] = c;
j++;
@@ -333,8 +337,8 @@
o->resize(j);
}
-void AbsPath(StringPiece s, std::string* o) {
- if (s.get(0) == '/') {
+void AbsPath(std::string_view s, std::string* o) {
+ if (!s.empty() && s.front() == '/') {
o->clear();
} else {
char buf[PATH_MAX];
@@ -352,7 +356,7 @@
}
template <typename Cond>
-size_t FindOutsideParenImpl(StringPiece s, Cond cond) {
+size_t FindOutsideParenImpl(std::string_view s, Cond cond) {
bool prev_backslash = false;
std::stack<char> paren_stack;
for (size_t i = 0; i < s.size(); i++) {
@@ -380,21 +384,21 @@
return std::string::npos;
}
-size_t FindOutsideParen(StringPiece s, char c) {
+size_t FindOutsideParen(std::string_view s, char c) {
return FindOutsideParenImpl(s, [&c](char d) { return c == d; });
}
-size_t FindTwoOutsideParen(StringPiece s, char c1, char c2) {
+size_t FindTwoOutsideParen(std::string_view s, char c1, char c2) {
return FindOutsideParenImpl(
s, [&c1, &c2](char d) { return d == c1 || d == c2; });
}
-size_t FindThreeOutsideParen(StringPiece s, char c1, char c2, char c3) {
+size_t FindThreeOutsideParen(std::string_view s, char c1, char c2, char c3) {
return FindOutsideParenImpl(
s, [&c1, &c2, &c3](char d) { return d == c1 || d == c2 || d == c3; });
}
-size_t FindEndOfLine(StringPiece s, size_t e, size_t* lf_cnt) {
+size_t FindEndOfLine(std::string_view s, size_t e, size_t* lf_cnt) {
while (e < s.size()) {
e += SkipUntil(s.data() + e, s.size() - e, "\n\\"); // skip to line end
if (e >= s.size()) {
@@ -424,7 +428,7 @@
return e;
}
-StringPiece TrimLeadingCurdir(StringPiece s) {
+std::string_view TrimLeadingCurdir(std::string_view s) {
while (s.substr(0, 2) == "./")
s = s.substr(2);
return s;
@@ -439,22 +443,22 @@
}
}
-std::string SortWordsInString(StringPiece s) {
+std::string SortWordsInString(std::string_view s) {
std::vector<std::string> toks;
- for (StringPiece tok : WordScanner(s)) {
- toks.push_back(tok.as_string());
+ for (std::string_view tok : WordScanner(s)) {
+ toks.push_back(std::string(tok));
}
sort(toks.begin(), toks.end());
return JoinStrings(toks, " ");
}
-std::string ConcatDir(StringPiece b, StringPiece n) {
+std::string ConcatDir(std::string_view b, std::string_view n) {
std::string r;
if (!b.empty() && (n.empty() || n[0] != '/')) {
- b.AppendToString(&r);
+ r.append(b);
r += '/';
}
- n.AppendToString(&r);
+ r.append(n);
NormalizePath(&r);
return r;
}
@@ -489,7 +493,7 @@
std::string r;
for (; i < s->size();) {
- StringPiece(*s).substr(prev, i - prev).AppendToString(&r);
+ r.append(std::string_view(*s).substr(prev, i - prev));
char c = (*s)[i];
r += '\\';
if (c == '$') {
@@ -503,11 +507,11 @@
prev = i;
i += SkipUntil(s->c_str() + i, s->size() - i, delimiters);
}
- StringPiece(*s).substr(prev).AppendToString(&r);
+ r.append(std::string_view(*s).substr(prev));
s->swap(r);
}
-bool IsInteger(StringPiece s) {
+bool IsInteger(std::string_view s) {
if (s.size() == 0) {
return false;
}
diff --git a/src/strutil.h b/src/strutil.h
index c5b961f..fe35d5e 100644
--- a/src/strutil.h
+++ b/src/strutil.h
@@ -16,40 +16,39 @@
#define STRUTIL_H_
#include <string>
+#include <string_view>
#include <vector>
-#include "string_piece.h"
-
class WordScanner {
public:
struct Iterator {
Iterator& operator++();
- StringPiece operator*() const;
+ std::string_view operator*() const;
bool operator!=(const Iterator& r) const {
return in != r.in || s != r.s || i != r.i;
}
- const StringPiece* in;
+ const std::string_view* in;
int s;
int i;
};
- explicit WordScanner(StringPiece in);
+ explicit WordScanner(std::string_view in);
Iterator begin() const;
Iterator end() const;
- void Split(std::vector<StringPiece>* o);
+ void Split(std::vector<std::string_view>* o);
private:
- StringPiece in_;
+ std::string_view in_;
};
class WordWriter {
public:
explicit WordWriter(std::string* o);
void MaybeAddWhitespace();
- void Write(StringPiece s);
+ void Write(std::string_view s);
private:
std::string* out_;
@@ -59,18 +58,18 @@
// Temporary modifies s[s.size()] to '\0'.
class ScopedTerminator {
public:
- explicit ScopedTerminator(StringPiece s);
+ explicit ScopedTerminator(std::string_view s);
~ScopedTerminator();
private:
- StringPiece s_;
+ std::string_view s_;
char c_;
};
template <class String>
inline std::string JoinStrings(std::vector<String> v, const char* sep) {
std::string r;
- for (StringPiece s : v) {
+ for (std::string_view s : v) {
if (!r.empty()) {
r += sep;
}
@@ -79,73 +78,75 @@
return r;
}
-void AppendString(StringPiece str, std::string* out);
+void AppendString(std::string_view str, std::string* out);
-bool HasPrefix(StringPiece str, StringPiece prefix);
+bool HasPrefix(std::string_view str, std::string_view prefix);
-bool HasSuffix(StringPiece str, StringPiece suffix);
+bool HasSuffix(std::string_view str, std::string_view suffix);
-bool HasWord(StringPiece str, StringPiece w);
+bool HasWord(std::string_view str, std::string_view w);
-StringPiece TrimPrefix(StringPiece str, StringPiece suffix);
+std::string_view TrimPrefix(std::string_view str, std::string_view prefix);
-StringPiece TrimSuffix(StringPiece str, StringPiece suffix);
+std::string_view TrimSuffix(std::string_view str, std::string_view suffix);
class Pattern {
public:
- explicit Pattern(StringPiece pat);
+ explicit Pattern(std::string_view pat);
- bool Match(StringPiece str) const;
+ bool Match(std::string_view str) const;
- StringPiece Stem(StringPiece str) const;
+ std::string_view Stem(std::string_view str) const;
- void AppendSubst(StringPiece str, StringPiece subst, std::string* out) const;
+ void AppendSubst(std::string_view str,
+ std::string_view subst,
+ std::string* out) const;
- void AppendSubstRef(StringPiece str,
- StringPiece subst,
+ void AppendSubstRef(std::string_view str,
+ std::string_view subst,
std::string* out) const;
private:
- bool MatchImpl(StringPiece str) const;
+ bool MatchImpl(std::string_view str) const;
- StringPiece pat_;
+ std::string_view pat_;
size_t percent_index_;
};
std::string NoLineBreak(const std::string& s);
-StringPiece TrimLeftSpace(StringPiece s);
-StringPiece TrimRightSpace(StringPiece s);
-StringPiece TrimSpace(StringPiece s);
+std::string_view TrimLeftSpace(std::string_view s);
+std::string_view TrimRightSpace(std::string_view s);
+std::string_view TrimSpace(std::string_view s);
-StringPiece Dirname(StringPiece s);
-StringPiece Basename(StringPiece s);
-StringPiece GetExt(StringPiece s);
-StringPiece StripExt(StringPiece s);
+std::string_view Dirname(std::string_view s);
+std::string_view Basename(std::string_view s);
+std::string_view GetExt(std::string_view s);
+std::string_view StripExt(std::string_view s);
void NormalizePath(std::string* o);
-void AbsPath(StringPiece s, std::string* o);
+void AbsPath(std::string_view s, std::string* o);
-size_t FindOutsideParen(StringPiece s, char c);
-size_t FindTwoOutsideParen(StringPiece s, char c1, char c2);
-size_t FindThreeOutsideParen(StringPiece s, char c1, char c2, char c3);
+size_t FindOutsideParen(std::string_view s, char c);
+size_t FindTwoOutsideParen(std::string_view s, char c1, char c2);
+size_t FindThreeOutsideParen(std::string_view s, char c1, char c2, char c3);
-size_t FindEndOfLine(StringPiece s, size_t e, size_t* lf_cnt);
+size_t FindEndOfLine(std::string_view s, size_t e, size_t* lf_cnt);
// Strip leading sequences of './' from file names, so that ./file
// and file are considered to be the same file.
// From http://www.gnu.org/software/make/manual/make.html#Features
-StringPiece TrimLeadingCurdir(StringPiece s);
+std::string_view TrimLeadingCurdir(std::string_view s);
void FormatForCommandSubstitution(std::string* s);
-std::string SortWordsInString(StringPiece s);
+std::string SortWordsInString(std::string_view s);
-std::string ConcatDir(StringPiece b, StringPiece n);
+std::string ConcatDir(std::string_view b, std::string_view n);
std::string EchoEscape(const std::string& str);
void EscapeShell(std::string* s);
-bool IsInteger(StringPiece s);
+bool IsInteger(std::string_view s);
#endif // STRUTIL_H_
diff --git a/src/strutil_bench.cc b/src/strutil_bench.cc
index f49bf7a..1d80b75 100644
--- a/src/strutil_bench.cc
+++ b/src/strutil_bench.cc
@@ -15,10 +15,10 @@
// +build ignore
#include <string>
+#include <string_view>
#include <vector>
#include "flags.h"
-#include "string_piece.h"
#include "strutil.h"
#include "timeutil.h"
@@ -34,7 +34,7 @@
ScopedTimeReporter tr("WordScanner");
static const int N = 1000;
for (int i = 0; i < N; i++) {
- std::vector<StringPiece> toks;
+ std::vector<std::string_view> toks;
WordScanner(s).Split(&toks);
}
}
diff --git a/src/strutil_test.cc b/src/strutil_test.cc
index 1209202..27d3b77 100644
--- a/src/strutil_test.cc
+++ b/src/strutil_test.cc
@@ -21,16 +21,16 @@
#include <unistd.h>
#include <string>
+#include <string_view>
#include <vector>
-#include "string_piece.h"
#include "testutil.h"
namespace {
void TestWordScanner() {
- std::vector<StringPiece> ss;
- for (StringPiece tok : WordScanner("foo bar baz hogeeeeeeeeeeeeeeee")) {
+ std::vector<std::string_view> ss;
+ for (std::string_view tok : WordScanner("foo bar baz hogeeeeeeeeeeeeeeee")) {
ss.push_back(tok);
}
assert(ss.size() == 4LU);
@@ -68,7 +68,9 @@
ASSERT_EQ(TrimSuffix("bar", "bbar"), "bar");
}
-std::string SubstPattern(StringPiece str, StringPiece pat, StringPiece subst) {
+std::string SubstPattern(std::string_view str,
+ std::string_view pat,
+ std::string_view subst) {
std::string r;
Pattern(pat).AppendSubst(str, subst, &r);
return r;
@@ -148,8 +150,8 @@
size_t lf_cnt = 0;
ASSERT_EQ(FindEndOfLine("foo", 0, &lf_cnt), 3);
char buf[10] = {'f', 'o', '\\', '\0', 'x', 'y'};
- ASSERT_EQ(FindEndOfLine(StringPiece(buf, 6), 0, &lf_cnt), 3);
- ASSERT_EQ(FindEndOfLine(StringPiece(buf, 2), 0, &lf_cnt), 2);
+ ASSERT_EQ(FindEndOfLine(std::string_view(buf, 6), 0, &lf_cnt), 3);
+ ASSERT_EQ(FindEndOfLine(std::string_view(buf, 2), 0, &lf_cnt), 2);
}
// Take a string, and copy it into an allocated buffer where
@@ -182,8 +184,9 @@
}
void TestWordScannerInvalidAccess() {
- std::vector<StringPiece> ss;
- for (StringPiece tok : WordScanner(CreateProtectedString("0123 456789"))) {
+ std::vector<std::string_view> ss;
+ for (std::string_view tok :
+ WordScanner(CreateProtectedString("0123 456789"))) {
ss.push_back(tok);
}
assert(ss.size() == 2LU);
diff --git a/src/symtab.cc b/src/symtab.cc
index 9c17495..0ba1213 100644
--- a/src/symtab.cc
+++ b/src/symtab.cc
@@ -147,7 +147,7 @@
delete s;
}
- Symbol InternImpl(StringPiece s) {
+ Symbol InternImpl(std::string_view s) {
auto found = symtab_.find(s);
if (found != symtab_.end()) {
return found->second;
@@ -159,7 +159,7 @@
return sym;
}
- Symbol Intern(StringPiece s) {
+ Symbol Intern(std::string_view s) {
#ifdef ENABLE_TID_CHECK
if (tid_ != pthread_self())
abort();
@@ -171,9 +171,9 @@
return InternImpl(s);
}
- std::vector<StringPiece> GetSymbolNames(
+ std::vector<std::string_view> GetSymbolNames(
std::function<bool(Var*)> const& filter) {
- std::vector<StringPiece> result;
+ std::vector<std::string_view> result;
for (auto entry : symtab_) {
Var* var = entry.second.PeekGlobalVar();
// The symbol table contains all interned strings, not just variables
@@ -189,7 +189,7 @@
}
private:
- std::unordered_map<StringPiece, Symbol> symtab_;
+ std::unordered_map<std::string_view, Symbol> symtab_;
std::vector<std::string*> symbols_;
#ifdef ENABLE_TID_CHECK
pthread_t tid_;
@@ -198,7 +198,7 @@
static Symtab g_symtab;
-Symbol Intern(StringPiece s) {
+Symbol Intern(std::string_view s) {
return g_symtab.Intern(s);
}
@@ -211,7 +211,7 @@
return JoinStrings(strs, sep);
}
-std::vector<StringPiece> GetSymbolNames(
+std::vector<std::string_view> GetSymbolNames(
std::function<bool(Var*)> const& filter) {
return g_symtab.GetSymbolNames(filter);
}
diff --git a/src/symtab.h b/src/symtab.h
index 137b8ef..641f416 100644
--- a/src/symtab.h
+++ b/src/symtab.h
@@ -18,10 +18,9 @@
#include <bitset>
#include <functional>
#include <string>
+#include <string_view>
#include <vector>
-#include "string_piece.h"
-
extern std::vector<std::string*>* g_symbols;
class Symtab;
@@ -219,12 +218,12 @@
extern Symbol kAllowRulesSym;
extern Symbol kKatiReadonlySym;
-Symbol Intern(StringPiece s);
+Symbol Intern(std::string_view s);
std::string JoinSymbols(const std::vector<Symbol>& syms, const char* sep);
// Get all symbol names for which filter returns true.
-std::vector<StringPiece> GetSymbolNames(
+std::vector<std::string_view> GetSymbolNames(
std::function<bool(Var*)> const& filter);
#endif // SYMTAB_H_
diff --git a/src/testutil.h b/src/testutil.h
index 8de3666..e94c8fd 100644
--- a/src/testutil.h
+++ b/src/testutil.h
@@ -13,8 +13,9 @@
// limitations under the License.
#include <assert.h>
+#include <string_view>
-#include "string_piece.h"
+#include "log.h"
bool g_failed;
@@ -38,10 +39,10 @@
} \
} while (0)
-StringPiece GetStringPiece(StringPiece s) {
+std::string_view GetStringPiece(std::string_view s) {
return s;
}
-StringPiece GetStringPiece(size_t v) {
+std::string_view GetStringPiece(size_t v) {
static char buf[64];
sprintf(buf, "%zd", v);
return buf;
diff --git a/src/var.cc b/src/var.cc
index 93b340a..0f1cb05 100644
--- a/src/var.cc
+++ b/src/var.cc
@@ -65,14 +65,14 @@
CHECK(false);
}
-void Var::SetDeprecated(const StringPiece& msg) {
+void Var::SetDeprecated(const std::string_view& msg) {
deprecated_ = true;
- diagnostic_messages_[this] = msg.as_string();
+ diagnostic_messages_[this] = std::string(msg);
}
-void Var::SetObsolete(const StringPiece& msg) {
+void Var::SetObsolete(const std::string_view& msg) {
obsolete_ = true;
- diagnostic_messages_[this] = msg.as_string();
+ diagnostic_messages_[this] = std::string(msg);
}
void Var::Used(Evaluator* ev, const Symbol& sym) const {
@@ -139,7 +139,7 @@
definition_ = ev->CurrentFrame();
}
-StringPiece SimpleVar::String() const {
+std::string_view SimpleVar::String() const {
return v_;
}
@@ -151,7 +151,7 @@
VarOrigin origin,
Frame* definition,
Loc loc,
- StringPiece orig)
+ std::string_view orig)
: Var(origin, definition, loc), v_(v), orig_(orig) {}
bool RecursiveVar::IsFunc(Evaluator* ev) const {
@@ -182,7 +182,7 @@
Var::Used(ev, sym);
}
-StringPiece RecursiveVar::String() const {
+std::string_view RecursiveVar::String() const {
return orig_;
}
@@ -200,15 +200,15 @@
// Nothing to do.
}
-StringPiece UndefinedVar::String() const {
- return StringPiece("");
+std::string_view UndefinedVar::String() const {
+ return std::string_view("");
}
std::string UndefinedVar::DebugString() const {
return "*undefined*";
}
-VariableNamesVar::VariableNamesVar(StringPiece name, bool all)
+VariableNamesVar::VariableNamesVar(std::string_view name, bool all)
: name_(name), all_(all) {
SetReadOnly();
SetAssignOp(AssignOp::COLON_EQ);
@@ -222,24 +222,25 @@
ConcatVariableNames(ev, s);
}
-StringPiece VariableNamesVar::String() const {
+std::string_view VariableNamesVar::String() const {
return name_;
}
void VariableNamesVar::ConcatVariableNames(Evaluator* ev,
std::string* s) const {
WordWriter ww(s);
- std::vector<StringPiece>&& symbols = GetSymbolNames([=](Var* var) -> bool {
- if (var->Obsolete()) {
- return false;
- }
- if (!all_) {
- if (var->IsFunc(ev)) {
- return false;
- }
- }
- return true;
- });
+ std::vector<std::string_view>&& symbols =
+ GetSymbolNames([=](Var* var) -> bool {
+ if (var->Obsolete()) {
+ return false;
+ }
+ if (!all_) {
+ if (var->IsFunc(ev)) {
+ return false;
+ }
+ }
+ return true;
+ });
for (auto entry : symbols) {
ww.Write(entry);
}
@@ -251,6 +252,7 @@
bool ShellStatusVar::is_set_ = false;
int ShellStatusVar::shell_status_ = 0;
+std::string ShellStatusVar::shell_status_string_;
ShellStatusVar::ShellStatusVar() {
SetReadOnly();
@@ -258,8 +260,11 @@
}
void ShellStatusVar::SetValue(int newShellStatus) {
- shell_status_ = newShellStatus;
- is_set_ = true;
+ if (!is_set_ || shell_status_ != newShellStatus) {
+ shell_status_ = newShellStatus;
+ is_set_ = true;
+ shell_status_string_.clear();
+ }
}
bool ShellStatusVar::IsDefined() const {
@@ -279,15 +284,19 @@
return;
}
- *s += std::to_string(shell_status_);
+ *s += String();
}
-StringPiece ShellStatusVar::String() const {
+std::string_view ShellStatusVar::String() const {
if (!is_set_) {
return "";
}
- return std::to_string(shell_status_);
+ if (shell_status_string_.empty()) {
+ shell_status_string_ = std::to_string(shell_status_);
+ }
+
+ return shell_status_string_;
}
std::string ShellStatusVar::DebugString() const {
diff --git a/src/var.h b/src/var.h
index 2186460..0e0972f 100644
--- a/src/var.h
+++ b/src/var.h
@@ -17,6 +17,7 @@
#include <memory>
#include <string>
+#include <string_view>
#include <unordered_map>
#include <unordered_set>
@@ -25,7 +26,6 @@
#include "loc.h"
#include "log.h"
#include "stmt.h"
-#include "string_piece.h"
#include "symtab.h"
class Evaluator;
@@ -57,7 +57,7 @@
virtual void AppendVar(Evaluator* ev, Value* v);
- virtual StringPiece String() const = 0;
+ virtual std::string_view String() const = 0;
virtual std::string DebugString() const = 0;
@@ -65,10 +65,10 @@
void SetReadOnly() { readonly_ = true; }
bool Deprecated() const { return deprecated_; }
- void SetDeprecated(const StringPiece& msg);
+ void SetDeprecated(const std::string_view& msg);
bool Obsolete() const { return obsolete_; }
- void SetObsolete(const StringPiece& msg);
+ void SetObsolete(const std::string_view& msg);
bool SelfReferential() const { return self_referential_; }
void SetSelfReferential() { self_referential_ = true; }
@@ -121,7 +121,7 @@
virtual void AppendVar(Evaluator* ev, Value* v) override;
- virtual StringPiece String() const override;
+ virtual std::string_view String() const override;
virtual std::string DebugString() const override;
@@ -134,7 +134,7 @@
VarOrigin origin,
Frame* definition,
Loc loc,
- StringPiece orig);
+ std::string_view orig);
virtual const char* Flavor() const override { return "recursive"; }
@@ -144,14 +144,14 @@
virtual void AppendVar(Evaluator* ev, Value* v) override;
- virtual StringPiece String() const override;
+ virtual std::string_view String() const override;
virtual std::string DebugString() const override;
virtual void Used(Evaluator* ev, const Symbol& sym) const override;
Value* v_;
- StringPiece orig_;
+ std::string_view orig_;
};
class UndefinedVar : public Var {
@@ -165,7 +165,7 @@
virtual void Eval(Evaluator* ev, std::string* s) const override;
- virtual StringPiece String() const override;
+ virtual std::string_view String() const override;
virtual std::string DebugString() const override;
};
@@ -173,7 +173,7 @@
// The built-in VARIABLES and KATI_SYMBOLS variables
class VariableNamesVar : public Var {
public:
- VariableNamesVar(StringPiece name, bool all);
+ VariableNamesVar(std::string_view name, bool all);
virtual const char* Flavor() const override { return "kati_variable_names"; }
virtual bool IsDefined() const override { return true; }
@@ -182,12 +182,12 @@
virtual void Eval(Evaluator* ev, std::string* s) const override;
- virtual StringPiece String() const override;
+ virtual std::string_view String() const override;
virtual std::string DebugString() const override;
private:
- StringPiece name_;
+ std::string_view name_;
bool all_;
void ConcatVariableNames(Evaluator* ev, std::string* s) const;
@@ -207,13 +207,14 @@
virtual void Eval(Evaluator* ev, std::string* s) const override;
- virtual StringPiece String() const override;
+ virtual std::string_view String() const override;
virtual std::string DebugString() const override;
private:
static bool is_set_;
static int shell_status_;
+ static std::string shell_status_string_;
};
class Vars : public std::unordered_map<Symbol, Var*> {