Path: blob/main/contrib/llvm-project/lld/Common/Strings.cpp
34879 views
//===- Strings.cpp -------------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "lld/Common/Strings.h"9#include "lld/Common/ErrorHandler.h"10#include "lld/Common/LLVM.h"11#include "llvm/ADT/StringExtras.h"12#include "llvm/Support/FileSystem.h"13#include "llvm/Support/GlobPattern.h"14#include <algorithm>15#include <mutex>16#include <vector>1718using namespace llvm;19using namespace lld;2021SingleStringMatcher::SingleStringMatcher(StringRef Pattern) {22if (Pattern.size() > 2 && Pattern.starts_with("\"") &&23Pattern.ends_with("\"")) {24ExactMatch = true;25ExactPattern = Pattern.substr(1, Pattern.size() - 2);26} else {27Expected<GlobPattern> Glob = GlobPattern::create(Pattern);28if (!Glob) {29error(toString(Glob.takeError()) + ": " + Pattern);30return;31}32ExactMatch = false;33GlobPatternMatcher = *Glob;34}35}3637bool SingleStringMatcher::match(StringRef s) const {38return ExactMatch ? (ExactPattern == s) : GlobPatternMatcher.match(s);39}4041bool StringMatcher::match(StringRef s) const {42for (const SingleStringMatcher &pat : patterns)43if (pat.match(s))44return true;45return false;46}4748// Converts a hex string (e.g. "deadbeef") to a vector.49SmallVector<uint8_t, 0> lld::parseHex(StringRef s) {50SmallVector<uint8_t, 0> hex;51while (!s.empty()) {52StringRef b = s.substr(0, 2);53s = s.substr(2);54uint8_t h;55if (!to_integer(b, h, 16)) {56error("not a hexadecimal value: " + b);57return {};58}59hex.push_back(h);60}61return hex;62}6364// Returns true if S is valid as a C language identifier.65bool lld::isValidCIdentifier(StringRef s) {66return !s.empty() && !isDigit(s[0]) &&67llvm::all_of(s, [](char c) { return isAlnum(c) || c == '_'; });68}6970// Write the contents of the a buffer to a file71void lld::saveBuffer(StringRef buffer, const Twine &path) {72std::error_code ec;73raw_fd_ostream os(path.str(), ec, sys::fs::OpenFlags::OF_None);74if (ec)75error("cannot create " + path + ": " + ec.message());76os << buffer;77}787980