blob: 3a1df32351df1236a5f988cb0fc7e4dfe28617fd [file] [edit]
// Copyright 2026 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.
#include "text_utils.h"
#include <cstring>
#include "disk_interface.h"
TextLineSplitter::TextLineSplitter(StringPiece input)
: p_(input.str_), limit_(input.str_ + input.size()) {}
bool TextLineSplitter::GetNextLine(StringPiece* line) {
if (p_ == limit_)
return false;
const char* start = p_;
const char* newline =
static_cast<const char*>(::memchr(p_, '\n', limit_ - p_));
if (newline) {
p_ = newline + 1;
} else {
newline = p_ = limit_;
}
if (newline > start && newline[-1] == '\r')
newline -= 1;
*line = StringPiece(start, newline - start);
return true;
}
TextFileParser::TextFileParser(DiskInterface& disk_interface)
: disk_interface_(disk_interface) {}
bool TextFileParser::Reset(const char* input_file, std::string* error) {
content_.clear();
lines_.clear();
if (disk_interface_.ReadFile(input_file, &content_, error) !=
FileReader::Okay) {
return false;
}
StringPiece target;
TextLineSplitter splitter(content_);
while (splitter.GetNextLine(&target)) {
if (!target.empty())
lines_.push_back(target);
}
return true;
}
StringPiece StripStringPiece(StringPiece input) {
auto IsWhitespace = [](char ch) {
return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r';
};
size_t start = 0;
while (start < input.len_ && IsWhitespace(input.str_[start])) {
++start;
}
size_t end = input.len_;
while (end > start && IsWhitespace(input.str_[end - 1])) {
--end;
}
return StringPiece(input.str_ + start, end - start);
}