diff options
| author | Julian Andres Klode <jak@debian.org> | 2024-11-14 14:54:40 +0000 |
|---|---|---|
| committer | Julian Andres Klode <jak@debian.org> | 2024-11-14 14:54:40 +0000 |
| commit | 82752f6e0c65541244c2607e5dedf437701e07dc (patch) | |
| tree | 9f8a63e33e05350551919c0c6f66340820303120 | |
| parent | 8f10ee850db3892bc979694864451be3a73ad1e8 (diff) | |
| parent | 36998f582e211f745799ddc2a8bc286541e56689 (diff) | |
Merge branch 'svequiv' into 'main'
Internally replace APT::StringView with std::string_view where it doesn't affect the ABI, with implementations that support both std::string_view and APT::StringView with new shims. ReportMirrorFailureToCentral: fix use-after-free
See merge request apt-team/apt!394
28 files changed, 485 insertions, 485 deletions
diff --git a/apt-pkg/acquire-item.cc b/apt-pkg/acquire-item.cc index 3016dad59..12292eb28 100644 --- a/apt-pkg/acquire-item.cc +++ b/apt-pkg/acquire-item.cc @@ -5,7 +5,7 @@ Acquire Item - Item to acquire Each item can download to exactly one file at a time. This means you - cannot create an item that fetches two uri's to two files at the same + cannot create an item that fetches two uri's to two files at the same time. The pkgAcqIndex class creates a second class upon instantiation to fetch the other index files because of this. @@ -140,10 +140,11 @@ static void ReportMirrorFailureToCentral(pkgAcquire::Item const &I, std::string if(!FileExists(report)) return; + const auto DescURI = I.DescURI(); std::vector<char const*> const Args = { report.c_str(), I.UsedMirror.c_str(), - I.DescURI().c_str(), + DescURI.c_str(), FailCode.c_str(), Details.c_str(), NULL @@ -2388,7 +2389,7 @@ bool pkgAcqDiffIndex::ParseDiffIndex(string const &IndexDiffFile) /*{{{*/ string hash; unsigned long long size; - std::stringstream ss(tmp.to_string()); + std::istringstream ss(std::string{tmp}); // TODO: replace with std::string_view_stream in C++23 ss.imbue(posix); ss >> hash >> size; if (unlikely(hash.empty() == true)) @@ -2458,7 +2459,7 @@ bool pkgAcqDiffIndex::ParseDiffIndex(string const &IndexDiffFile) /*{{{*/ string hash, filename; unsigned long long size; - std::stringstream ss(tmp.to_string()); + std::stringstream ss(std::string{tmp}); // TODO: replace with std::string_view_stream in C++23 ss.imbue(posix); while (ss >> hash >> size >> filename) @@ -2515,7 +2516,7 @@ bool pkgAcqDiffIndex::ParseDiffIndex(string const &IndexDiffFile) /*{{{*/ string hash, filename; unsigned long long size; - std::stringstream ss(tmp.to_string()); + std::stringstream ss(std::string{tmp}); // TODO: replace with std::string_view_stream in C++23 ss.imbue(posix); while (ss >> hash >> size >> filename) @@ -2553,7 +2554,7 @@ bool pkgAcqDiffIndex::ParseDiffIndex(string const &IndexDiffFile) /*{{{*/ string hash, filename; unsigned long long size; - std::stringstream ss(tmp.to_string()); + std::stringstream ss(std::string{tmp}); // TODO: replace with std::string_view_stream in C++23 ss.imbue(posix); // FIXME: all of pdiff supports only .gz compressed patches @@ -2823,7 +2824,7 @@ void pkgAcqIndexDiffs::Failed(string const &Message,pkgAcquire::MethodConfig con void pkgAcqIndexDiffs::Finish(bool allDone) { if(Debug) - std::clog << "pkgAcqIndexDiffs::Finish(): " + std::clog << "pkgAcqIndexDiffs::Finish(): " << allDone << " " << Desc.URI << std::endl; @@ -3253,7 +3254,7 @@ void pkgAcqIndex::Done(string const &Message, { Item::Done(Message,Hashes,Cfg); - switch(Stage) + switch(Stage) { case STAGE_DOWNLOAD: StageDownloadDone(Message); diff --git a/apt-pkg/algorithms.cc b/apt-pkg/algorithms.cc index 72184748a..790ea4778 100644 --- a/apt-pkg/algorithms.cc +++ b/apt-pkg/algorithms.cc @@ -25,7 +25,6 @@ #include <apt-pkg/macros.h> #include <apt-pkg/packagemanager.h> #include <apt-pkg/pkgcache.h> -#include <apt-pkg/string_view.h> #include <apt-pkg/strutl.h> #include <apt-pkg/version.h> diff --git a/apt-pkg/cachefilter-patterns.cc b/apt-pkg/cachefilter-patterns.cc index 7e6d84ff6..31eb05016 100644 --- a/apt-pkg/cachefilter-patterns.cc +++ b/apt-pkg/cachefilter-patterns.cc @@ -12,6 +12,8 @@ #include <apti18n.h> +using namespace std::literals; + namespace APT { namespace Internal @@ -19,50 +21,50 @@ namespace Internal static const constexpr struct { - APT::StringView shortName; - APT::StringView longName; + std::string_view shortName; + std::string_view longName; bool takesArgument; } shortPatterns[] = { - {"r"_sv, "?architecture"_sv, true}, - {"A"_sv, "?archive"_sv, true}, - {"M"_sv, "?automatic"_sv, false}, - {"b"_sv, "?broken"_sv, false}, - {"c"_sv, "?config-files"_sv, false}, + {"r"sv, "?architecture"sv, true}, + {"A"sv, "?archive"sv, true}, + {"M"sv, "?automatic"sv, false}, + {"b"sv, "?broken"sv, false}, + {"c"sv, "?config-files"sv, false}, // FIXME: The words after ~D should be case-insensitive - {"DDepends:"_sv, "?depends"_sv, true}, - {"DPre-Depends:"_sv, "?pre-depends"_sv, true}, - {"DSuggests:"_sv, "?suggests"_sv, true}, - {"DRecommends:"_sv, "?recommends"_sv, true}, - {"DConflicts:"_sv, "?conflicts"_sv, true}, - {"DReplaces:"_sv, "?replaces"_sv, true}, - {"DObsoletes:"_sv, "?obsoletes"_sv, true}, - {"DBreaks:"_sv, "?breaks"_sv, true}, - {"DEnhances:"_sv, "?enhances"_sv, true}, - {"D"_sv, "?depends"_sv, true}, - {"RDepends:"_sv, "?reverse-depends"_sv, true}, - {"RPre-Depends:"_sv, "?reverse-pre-depends"_sv, true}, - {"RSuggests:"_sv, "?reverse-suggests"_sv, true}, - {"RRecommends:"_sv, "?reverse-recommends"_sv, true}, - {"RConflicts:"_sv, "?reverse-conflicts"_sv, true}, - {"RReplaces:"_sv, "?reverse-replaces"_sv, true}, - {"RObsoletes:"_sv, "?reverse-obsoletes"_sv, true}, - {"RBreaks:"_sv, "?reverse-breaks"_sv, true}, - {"REnhances:"_sv, "?reverse-enhances"_sv, true}, - {"R"_sv, "?reverse-depends"_sv, true}, - {"E"_sv, "?essential"_sv, false}, - {"F"_sv, "?false"_sv, false}, - {"g"_sv, "?garbage"_sv, false}, - {"i"_sv, "?installed"_sv, false}, - {"n"_sv, "?name"_sv, true}, - {"o"_sv, "?obsolete"_sv, false}, - {"O"_sv, "?origin"_sv, true}, - {"p"_sv, "?priority"_sv, true}, - {"s"_sv, "?section"_sv, true}, - {"e"_sv, "?source-package"_sv, true}, - {"T"_sv, "?true"_sv, false}, - {"U"_sv, "?upgradable"_sv, false}, - {"V"_sv, "?version"_sv, true}, - {"v"_sv, "?virtual"_sv, false}, + {"DDepends:"sv, "?depends"sv, true}, + {"DPre-Depends:"sv, "?pre-depends"sv, true}, + {"DSuggests:"sv, "?suggests"sv, true}, + {"DRecommends:"sv, "?recommends"sv, true}, + {"DConflicts:"sv, "?conflicts"sv, true}, + {"DReplaces:"sv, "?replaces"sv, true}, + {"DObsoletes:"sv, "?obsoletes"sv, true}, + {"DBreaks:"sv, "?breaks"sv, true}, + {"DEnhances:"sv, "?enhances"sv, true}, + {"D"sv, "?depends"sv, true}, + {"RDepends:"sv, "?reverse-depends"sv, true}, + {"RPre-Depends:"sv, "?reverse-pre-depends"sv, true}, + {"RSuggests:"sv, "?reverse-suggests"sv, true}, + {"RRecommends:"sv, "?reverse-recommends"sv, true}, + {"RConflicts:"sv, "?reverse-conflicts"sv, true}, + {"RReplaces:"sv, "?reverse-replaces"sv, true}, + {"RObsoletes:"sv, "?reverse-obsoletes"sv, true}, + {"RBreaks:"sv, "?reverse-breaks"sv, true}, + {"REnhances:"sv, "?reverse-enhances"sv, true}, + {"R"sv, "?reverse-depends"sv, true}, + {"E"sv, "?essential"sv, false}, + {"F"sv, "?false"sv, false}, + {"g"sv, "?garbage"sv, false}, + {"i"sv, "?installed"sv, false}, + {"n"sv, "?name"sv, true}, + {"o"sv, "?obsolete"sv, false}, + {"O"sv, "?origin"sv, true}, + {"p"sv, "?priority"sv, true}, + {"s"sv, "?section"sv, true}, + {"e"sv, "?source-package"sv, true}, + {"T"sv, "?true"sv, false}, + {"U"sv, "?upgradable"sv, false}, + {"V"sv, "?version"sv, true}, + {"v"sv, "?virtual"sv, false}, }; template <class... Args> @@ -270,7 +272,7 @@ std::unique_ptr<PatternTreeParser::Node> PatternTreeParser::parsePattern() static constexpr auto CHARS = ("0123456789" "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "-"_sv); + "-"sv); if (sentence[state.offset] != '?') return nullptr; @@ -278,7 +280,7 @@ std::unique_ptr<PatternTreeParser::Node> PatternTreeParser::parsePattern() node->end = node->start = state.offset; state.offset++; - while (CHARS.find(sentence[state.offset]) != APT::StringView::npos) + while (CHARS.find(sentence[state.offset]) != std::string_view::npos) { ++state.offset; } @@ -356,20 +358,20 @@ std::unique_ptr<PatternTreeParser::Node> PatternTreeParser::parseQuotedWord() std::unique_ptr<PatternTreeParser::Node> PatternTreeParser::parseWord(bool shrt) { // Characters not allowed at the start of a word (also see ..._SHRT) - static const constexpr auto DISALLOWED_START = "!?~|,() \0"_sv; + static const constexpr auto DISALLOWED_START = "!?~|,() \0"sv; // Characters terminating a word inside a long pattern - static const constexpr auto DISALLOWED_LONG = "|,()\0"_sv; + static const constexpr auto DISALLOWED_LONG = "|,()\0"sv; // Characters terminating a word as a short form argument, should contain all of START. - static const constexpr auto DISALLOWED_SHRT = "!?~|,() \0"_sv; + static const constexpr auto DISALLOWED_SHRT = "!?~|,() \0"sv; const auto DISALLOWED = shrt ? DISALLOWED_SHRT : DISALLOWED_LONG; - if (DISALLOWED_START.find(sentence[state.offset]) != APT::StringView::npos) + if (DISALLOWED_START.find(sentence[state.offset]) != std::string_view::npos) return nullptr; auto node = std::make_unique<WordNode>(); node->start = state.offset; - while (DISALLOWED.find(sentence[state.offset]) == APT::StringView::npos) + while (DISALLOWED.find(sentence[state.offset]) == std::string_view::npos) state.offset++; node->end = state.offset; @@ -381,7 +383,7 @@ std::unique_ptr<PatternTreeParser::Node> PatternTreeParser::parseWord(bool shrt) std::ostream &PatternTreeParser::PatternNode::render(std::ostream &os) { - os << term.to_string(); + os << term; if (haveArgumentList) { os << "("; @@ -394,7 +396,7 @@ std::ostream &PatternTreeParser::PatternNode::render(std::ostream &os) std::ostream &PatternTreeParser::WordNode::render(std::ostream &os) { - return quoted ? os << '"' << word.to_string() << '"' : os << word.to_string(); + return quoted ? os << '"' << word << '"' : os << word; } std::nullptr_t PatternTreeParser::Node::error(std::string message) @@ -402,20 +404,20 @@ std::nullptr_t PatternTreeParser::Node::error(std::string message) throw Error{*this, message}; } -bool PatternTreeParser::PatternNode::matches(APT::StringView name, int min, int max) +bool PatternTreeParser::PatternNode::matches(std::string_view name, int min, int max) { if (name != term) return false; if (max != 0 && !haveArgumentList) - error(rstrprintf("%s expects an argument list", term.to_string().c_str())); + error(rstrprintf("%.*s expects an argument list", (int)term.size(), term.data())); if (max == 0 && haveArgumentList) - error(rstrprintf("%s does not expect an argument list", term.to_string().c_str())); + error(rstrprintf("%.*s does not expect an argument list", (int)term.size(), term.data())); if (min >= 0 && min == max && (arguments.size() != size_t(min))) - error(rstrprintf("%s expects %d arguments, but received %d arguments", term.to_string().c_str(), min, arguments.size())); + error(rstrprintf("%.*s expects %d arguments, but received %d arguments", (int)term.size(), term.data(), min, arguments.size())); if (min >= 0 && arguments.size() < size_t(min)) - error(rstrprintf("%s expects at least %d arguments, but received %d arguments", term.to_string().c_str(), min, arguments.size())); + error(rstrprintf("%.*s expects at least %d arguments, but received %d arguments", (int)term.size(), term.data(), min, arguments.size())); if (max >= 0 && arguments.size() > size_t(max)) - error(rstrprintf("%s expects at most %d arguments, but received %d arguments", term.to_string().c_str(), max, arguments.size())); + error(rstrprintf("%.*s expects at most %d arguments, but received %d arguments", (int)term.size(), term.data(), max, arguments.size())); return true; } @@ -538,7 +540,7 @@ std::unique_ptr<APT::CacheFilter::Matcher> PatternParser::aPattern(std::unique_p return pattern; } - node->error(rstrprintf("Unrecognized pattern '%s'", node->term.to_string().c_str())); + node->error(rstrprintf("Unrecognized pattern '%.*s'", (int)node->term.size(), node->term.data())); return nullptr; } @@ -549,7 +551,7 @@ std::string PatternParser::aWord(std::unique_ptr<PatternTreeParser::Node> &nodeP auto node = dynamic_cast<PatternTreeParser::WordNode *>(nodeP.get()); if (node == nullptr) nodeP->error("Expected a word"); - return node->word.to_string(); + return std::string{node->word}; } namespace Patterns @@ -602,7 +604,7 @@ std::unique_ptr<APT::CacheFilter::Matcher> APT::CacheFilter::ParsePattern(APT::S { std::stringstream ss; ss << "input:" << e.location.start << "-" << e.location.end << ": error: " << e.message << "\n"; - ss << pattern.to_string() << "\n"; + ss << pattern << "\n"; for (size_t i = 0; i < e.location.start; i++) ss << " "; for (size_t i = e.location.start; i < e.location.end; i++) diff --git a/apt-pkg/cachefilter-patterns.h b/apt-pkg/cachefilter-patterns.h index 1f2f4f781..a45b9afcf 100644 --- a/apt-pkg/cachefilter-patterns.h +++ b/apt-pkg/cachefilter-patterns.h @@ -12,7 +12,6 @@ #include <apt-pkg/cachefilter.h> #include <apt-pkg/error.h> #include <apt-pkg/header-is-private.h> -#include <apt-pkg/string_view.h> #include <apt-pkg/strutl.h> #include <cassert> #include <iostream> @@ -59,17 +58,17 @@ struct APT_PUBLIC PatternTreeParser struct PatternNode : public Node { - APT::StringView term; + std::string_view term; std::vector<std::unique_ptr<Node>> arguments; bool haveArgumentList = false; APT_HIDDEN std::ostream &render(std::ostream &stream) override; - APT_HIDDEN bool matches(APT::StringView name, int min, int max); + APT_HIDDEN bool matches(std::string_view name, int min, int max); }; struct WordNode : public Node { - APT::StringView word; + std::string_view word; bool quoted = false; APT_HIDDEN std::ostream &render(std::ostream &stream) override; }; @@ -79,10 +78,10 @@ struct APT_PUBLIC PatternTreeParser size_t offset = 0; }; - APT::StringView sentence; + std::string_view sentence; State state; - PatternTreeParser(APT::StringView sentence) : sentence(sentence){}; + PatternTreeParser(std::string_view sentence) : sentence(sentence){}; off_t skipSpace() { while (sentence[state.offset] == ' ' || sentence[state.offset] == '\t' || sentence[state.offset] == '\r' || sentence[state.offset] == '\n') diff --git a/apt-pkg/cachefilter.h b/apt-pkg/cachefilter.h index 1b5f9aa71..4027178bf 100644 --- a/apt-pkg/cachefilter.h +++ b/apt-pkg/cachefilter.h @@ -7,7 +7,6 @@ #define APT_CACHEFILTER_H // Include Files /*{{{*/ #include <apt-pkg/pkgcache.h> -#include <apt-pkg/string_view.h> #include <memory> #include <string> diff --git a/apt-pkg/contrib/configuration.cc b/apt-pkg/contrib/configuration.cc index abda6b66b..c9b2dc0cc 100644 --- a/apt-pkg/contrib/configuration.cc +++ b/apt-pkg/contrib/configuration.cc @@ -4,7 +4,7 @@ /* ###################################################################### Configuration Class - + This class provides a configuration file and command line parser for a tree-oriented configuration environment. All runtime configuration is stored in here. @@ -25,7 +25,6 @@ #include <apt-pkg/fileutl.h> #include <apt-pkg/macros.h> #include <apt-pkg/strutl.h> -#include <apt-pkg/string_view.h> #include <cctype> #include <cstddef> @@ -219,7 +218,7 @@ Configuration::~Configuration() { if (ToFree == false) return; - + Item *Top = Root; for (; Top != 0;) { @@ -228,13 +227,13 @@ Configuration::~Configuration() Top = Top->Child; continue; } - + while (Top != 0 && Top->Next == 0) { Item *Parent = Top->Parent; delete Top; Top = Parent; - } + } if (Top != 0) { Item *Next = Top->Next; @@ -246,7 +245,7 @@ Configuration::~Configuration() /*}}}*/ // Configuration::Lookup - Lookup a single item /*{{{*/ // --------------------------------------------------------------------- -/* This will lookup a single item by name below another item. It is a +/* This will lookup a single item by name below another item. It is a helper function for the main lookup function */ Configuration::Item *Configuration::Lookup(Item *Head,const char *S, unsigned long const &Len,bool const &Create) @@ -254,7 +253,7 @@ Configuration::Item *Configuration::Lookup(Item *Head,const char *S, int Res = 1; Item *I = Head->Child; Item **Last = &Head->Child; - + // Empty strings match nothing. They are used for lists. if (Len != 0) { @@ -264,12 +263,12 @@ Configuration::Item *Configuration::Lookup(Item *Head,const char *S, } else for (; I != 0; Last = &I->Next, I = I->Next); - + if (Res == 0) return I; if (Create == false) return 0; - + I = new Item; I->Tag.assign(S,Len); I->Next = *Last; @@ -286,7 +285,7 @@ Configuration::Item *Configuration::Lookup(const char *Name,bool const &Create) { if (Name == 0) return Root->Child; - + const char *Start = Name; const char *End = Start + strlen(Name); const char *TagEnd = Name; @@ -298,9 +297,9 @@ Configuration::Item *Configuration::Lookup(const char *Name,bool const &Create) Itm = Lookup(Itm,Start,TagEnd - Start,Create); if (Itm == 0) return 0; - TagEnd = Start = TagEnd + 2; + TagEnd = Start = TagEnd + 2; } - } + } // This must be a trailing ::, we create unique items in a list if (End - Start == 0) @@ -308,7 +307,7 @@ Configuration::Item *Configuration::Lookup(const char *Name,bool const &Create) if (Create == false) return 0; } - + Itm = Lookup(Itm,Start,End - Start,Create); return Itm; } @@ -327,7 +326,7 @@ string Configuration::Find(const char *Name,const char *Default) const else return Default; } - + return Itm->Value; } /*}}}*/ @@ -440,12 +439,12 @@ int Configuration::FindI(const char *Name,int const &Default) const const Item *Itm = Lookup(Name); if (Itm == 0 || Itm->Value.empty() == true) return Default; - + char *End; int Res = strtol(Itm->Value.c_str(),&End,0); if (End == Itm->Value.c_str()) return Default; - + return Res; } /*}}}*/ @@ -458,7 +457,7 @@ bool Configuration::FindB(const char *Name,bool const &Default) const const Item *Itm = Lookup(Name); if (Itm == 0 || Itm->Value.empty() == true) return Default; - + return StringToBool(Itm->Value,Default); } /*}}}*/ @@ -479,19 +478,19 @@ string Configuration::FindAny(const char *Name,const char *Default) const switch (type) { // file - case 'f': + case 'f': return FindFile(key.c_str(), Default); - + // directory - case 'd': + case 'd': return FindDir(key.c_str(), Default); - + // bool - case 'b': + case 'b': return FindB(key, Default) ? "true" : "false"; - + // int - case 'i': + case 'i': { char buf[16]; snprintf(buf, sizeof(buf)-1, "%d", FindI(key, Default ? atoi(Default) : 0 )); @@ -590,7 +589,7 @@ void Configuration::Clear(string const &Name, string const &Value) I = I->Next; } } - + } /*}}}*/ // Configuration::Clear - Clear everything /*{{{*/ @@ -611,7 +610,7 @@ void Configuration::Clear() void Configuration::Clear(string const &Name) { Item *Top = Lookup(Name.c_str(),false); - if (Top == 0) + if (Top == 0) return; Top->Value.clear(); @@ -631,11 +630,11 @@ void Configuration::Clear(string const &Name) Item *Tmp = Top; Top = Top->Parent; delete Tmp; - + if (Top == Stop) return; } - + Item *Tmp = Top; if (Top != 0) Top = Top->Next; @@ -827,10 +826,10 @@ string Configuration::Item::FullTag(const Item *Stop) const // ReadConfigFile - Read a configuration file /*{{{*/ // --------------------------------------------------------------------- /* The configuration format is very much like the named.conf format - used in bind8, in fact this routine can parse most named.conf files. - Sectional config files are like bind's named.conf where there are + used in bind8, in fact this routine can parse most named.conf files. + Sectional config files are like bind's named.conf where there are sections like 'zone "foo.org" { .. };' This causes each section to be - added in with a tag like "zone::foo.org" instead of being split + added in with a tag like "zone::foo.org" instead of being split tag/value. AsSectional enables Sectional parsing.*/ static void leaveCurrentScope(std::stack<std::string> &Stack, std::string &ParentTag) { @@ -873,13 +872,13 @@ bool ReadConfigFile(Configuration &Conf,const string &FName,bool const &AsSectio // Now strip comments; if the whole line is contained in a // comment, skip this line. - APT::StringView Line{Input.data(), Input.size()}; + std::string_view Line{Input.data(), Input.size()}; // continued Multi line comment if (InComment) { size_t end = Line.find("*/"); - if (end != APT::StringView::npos) + if (end != std::string_view::npos) { Line.remove_prefix(end + 2); InComment = false; @@ -891,7 +890,7 @@ bool ReadConfigFile(Configuration &Conf,const string &FName,bool const &AsSectio // Discard single line comments { size_t start = 0; - while ((start = Line.find("//", start)) != APT::StringView::npos) + while ((start = Line.find("//", start)) != std::string_view::npos) { if (std::count(Line.begin(), Line.begin() + start, '"') % 2 != 0) { @@ -901,10 +900,10 @@ bool ReadConfigFile(Configuration &Conf,const string &FName,bool const &AsSectio Line.remove_suffix(Line.length() - start); break; } - using APT::operator""_sv; - constexpr std::array<APT::StringView, 3> magicComments { "clear"_sv, "include"_sv, "x-apt-configure-index"_sv }; + using std::literals::operator""sv; + constexpr std::array<std::string_view, 3> magicComments { "clear"sv, "include"sv, "x-apt-configure-index"sv }; start = 0; - while ((start = Line.find('#', start)) != APT::StringView::npos) + while ((start = Line.find('#', start)) != std::string_view::npos) { if (std::count(Line.begin(), Line.begin() + start, '"') % 2 != 0 || std::any_of(magicComments.begin(), magicComments.end(), [&](auto const m) { return Line.compare(start+1, m.length(), m) == 0; })) @@ -922,7 +921,7 @@ bool ReadConfigFile(Configuration &Conf,const string &FName,bool const &AsSectio Fragment.reserve(Line.length()); { size_t start = 0; - while ((start = Line.find("/*", start)) != APT::StringView::npos) + while ((start = Line.find("/*", start)) != std::string_view::npos) { if (std::count(Line.begin(), Line.begin() + start, '"') % 2 != 0) { @@ -931,9 +930,9 @@ bool ReadConfigFile(Configuration &Conf,const string &FName,bool const &AsSectio } Fragment.append(Line.data(), start); auto const end = Line.find("*/", start + 2); - if (end == APT::StringView::npos) + if (end == std::string_view::npos) { - Line.clear(); + Line = {}; InComment = true; break; } diff --git a/apt-pkg/contrib/fileutl.cc b/apt-pkg/contrib/fileutl.cc index 957d068de..bd7076701 100644 --- a/apt-pkg/contrib/fileutl.cc +++ b/apt-pkg/contrib/fileutl.cc @@ -2,20 +2,20 @@ // SPDX-License-Identifier: GPL-2.0+ // Description /*{{{*/ /* ###################################################################### - + File Utilities - + CopyFile - Buffered copy of a single file GetLock - dpkg compatible lock file manipulation (fcntl) - + This file had this historic note, but now includes further changes under the GPL-2.0+: - Most of this source is placed in the Public Domain, do with it what + Most of this source is placed in the Public Domain, do with it what you will It was originally written by Jason Gunthorpe <jgg@debian.org>. FileFd gzip support added by Martin Pitt <martin.pitt@canonical.com> - + The exception is RunScripts() it is under the GPLv2 We believe that this reference to GPLv2 was not meant to exclude later @@ -105,16 +105,16 @@ bool RunScripts(const char *Cnf) // Fork for running the system calls pid_t Child = ExecFork(); - + // This is the child if (Child == 0) { if (_system != nullptr && _system->IsLocked() == true && (stringcasecmp(Cnf, "dpkg::post-invoke") == 0 || stringcasecmp(Cnf, "dpkg::pre-invoke") == 0)) setenv("DPKG_FRONTEND_LOCKED", "true", 1); - if (_config->FindDir("DPkg::Chroot-Directory","/") != "/") + if (_config->FindDir("DPkg::Chroot-Directory","/") != "/") { - std::cerr << "Chrooting into " - << _config->FindDir("DPkg::Chroot-Directory") + std::cerr << "Chrooting into " + << _config->FindDir("DPkg::Chroot-Directory") << std::endl; if (chroot(_config->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0) _exit(100); @@ -122,7 +122,7 @@ bool RunScripts(const char *Cnf) if (chdir("/tmp/") != 0) _exit(100); - + unsigned int Count = 1; for (; Opts != 0; Opts = Opts->Next, Count++) { @@ -137,7 +137,7 @@ bool RunScripts(const char *Cnf) _exit(100+Count); } _exit(0); - } + } // Wait for the child int Status = 0; @@ -158,10 +158,10 @@ bool RunScripts(const char *Cnf) for (; Opts != 0 && Count != 1; Opts = Opts->Next, Count--); _error->Error("Problem executing scripts %s '%s'",Cnf,Opts->Value.c_str()); } - + return _error->Error("Sub-process returned an error code"); } - + return true; } /*}}}*/ @@ -260,7 +260,7 @@ int GetLock(string File,bool Errors) _error->Warning(_("Not using locking for read only lock file %s"),File.c_str()); return dup(0); // Need something for the caller to close } - + if (Errors == true) _error->Errno("open",_("Could not open lock file %s"),File.c_str()); @@ -269,7 +269,7 @@ int GetLock(string File,bool Errors) return -1; } SetCloseExec(FD,true); - + // Acquire a write lock struct flock fl; fl.l_type = F_WRLCK; @@ -300,9 +300,9 @@ int GetLock(string File,bool Errors) if (errno == ENOLCK) { _error->Warning(_("Not using locking for nfs mounted lock file %s"),File.c_str()); - return dup(0); // Need something for the caller to close + return dup(0); // Need something for the caller to close } - + if (Errors == true) { // We only do the lookup in the if ((errno == EACCES || errno == EAGAIN)) @@ -462,7 +462,7 @@ std::vector<string> GetListOfFilesInDir(string const &Dir, std::vector<string> c Configuration::MatchAgainstConfig SilentIgnore("Dir::Ignore-Files-Silently"); DIR *D = opendir(Dir.c_str()); - if (D == 0) + if (D == 0) { if (errno == EACCES) _error->WarningE("opendir", _("Unable to read %s"), Dir.c_str()); @@ -471,7 +471,7 @@ std::vector<string> GetListOfFilesInDir(string const &Dir, std::vector<string> c return List; } - for (struct dirent *Ent = readdir(D); Ent != 0; Ent = readdir(D)) + for (struct dirent *Ent = readdir(D); Ent != 0; Ent = readdir(D)) { // skip "hidden" files if (Ent->d_name[0] == '.') @@ -586,7 +586,7 @@ std::vector<string> GetListOfFilesInDir(string const &Dir, bool SortList) return List; } - for (struct dirent *Ent = readdir(D); Ent != 0; Ent = readdir(D)) + for (struct dirent *Ent = readdir(D); Ent != 0; Ent = readdir(D)) { // skip "hidden" files if (Ent->d_name[0] == '.') @@ -713,9 +713,9 @@ string flNoLink(string File) return File; if (stat(File.c_str(),&St) != 0) return File; - - /* Loop resolving the link. There is no need to limit the number of - loops because the stat call above ensures that the symlink is not + + /* Loop resolving the link. There is no need to limit the number of + loops because the stat call above ensures that the symlink is not circular */ char Buffer[1024]; string NFile = File; @@ -723,23 +723,23 @@ string flNoLink(string File) { // Read the link ssize_t Res; - if ((Res = readlink(NFile.c_str(),Buffer,sizeof(Buffer))) <= 0 || + if ((Res = readlink(NFile.c_str(),Buffer,sizeof(Buffer))) <= 0 || (size_t)Res >= sizeof(Buffer)) return File; - + // Append or replace the previous path Buffer[Res] = 0; if (Buffer[0] == '/') NFile = Buffer; else NFile = flNotFile(NFile) + Buffer; - + // See if we are done if (lstat(NFile.c_str(),&St) != 0) return File; if (S_ISLNK(St.st_mode) == 0) - return NFile; - } + return NFile; + } } /*}}}*/ // flCombine - Combine a file and a directory /*{{{*/ @@ -750,14 +750,14 @@ string flCombine(string Dir,string File) { if (File.empty() == true) return string(); - + if (File[0] == '/' || Dir.empty() == true) return File; if (File.length() >= 2 && File[0] == '.' && File[1] == '/') return File; if (Dir[Dir.length()-1] == '/') - return Dir + File; - return Dir + '/' + File; + return Dir += File; + return (Dir += '/') += File; } /*}}}*/ // flAbsPath - Return the absolute path of the filename /*{{{*/ @@ -799,7 +799,7 @@ std::string flNormalize(std::string file) /*{{{*/ // --------------------------------------------------------------------- /* */ void SetCloseExec(int Fd,bool Close) -{ +{ if (fcntl(Fd,F_SETFD,(Close == false)?0:FD_CLOEXEC) != 0) { cerr << "FATAL -> Could not set close on exec " << strerror(errno) << endl; @@ -811,7 +811,7 @@ void SetCloseExec(int Fd,bool Close) // --------------------------------------------------------------------- /* */ void SetNonBlock(int Fd,bool Block) -{ +{ int Flags = fcntl(Fd,F_GETFL) & (~O_NONBLOCK); if (fcntl(Fd,F_SETFL,Flags | ((Block == false)?0:O_NONBLOCK)) != 0) { @@ -823,7 +823,7 @@ void SetNonBlock(int Fd,bool Block) // WaitFd - Wait for a FD to become readable /*{{{*/ // --------------------------------------------------------------------- /* This waits for a FD to become readable using select. It is useful for - applications making use of non-blocking sockets. The timeout is + applications making use of non-blocking sockets. The timeout is in seconds. */ bool WaitFd(int Fd,bool write,unsigned long timeout) { @@ -833,19 +833,19 @@ bool WaitFd(int Fd,bool write,unsigned long timeout) FD_SET(Fd,&Set); tv.tv_sec = timeout; tv.tv_usec = 0; - if (write == true) - { + if (write == true) + { int Res; do { Res = select(Fd+1,0,&Set,0,(timeout != 0?&tv:0)); } while (Res < 0 && errno == EINTR); - + if (Res <= 0) return false; - } - else + } + else { int Res; do @@ -853,11 +853,11 @@ bool WaitFd(int Fd,bool write,unsigned long timeout) Res = select(Fd+1,&Set,0,0,(timeout != 0?&tv:0)); } while (Res < 0 && errno == EINTR); - + if (Res <= 0) return false; } - + return true; } /*}}}*/ @@ -884,13 +884,13 @@ void MergeKeepFdsFromConfiguration(std::set<int> &KeepFDs) /*}}}*/ // ExecFork - Magical fork that sanitizes the context before execing /*{{{*/ // --------------------------------------------------------------------- -/* This is used if you want to cleanse the environment for the forked +/* This is used if you want to cleanse the environment for the forked child, it fixes up the important signals and nukes all of the fds, otherwise acts like normal fork. */ pid_t ExecFork() { set<int> KeepFDs; - // we need to merge the Keep-Fds as external tools like + // we need to merge the Keep-Fds as external tools like // debconf-apt-progress use it MergeKeepFdsFromConfiguration(KeepFDs); return ExecFork(KeepFDs); @@ -939,20 +939,20 @@ pid_t ExecFork(std::set<int> KeepFDs) } } } - + return Process; } /*}}}*/ // ExecWait - Fancy waitpid /*{{{*/ // --------------------------------------------------------------------- -/* Waits for the given sub process. If Reap is set then no errors are +/* Waits for the given sub process. If Reap is set then no errors are generated. Otherwise a failed subprocess will generate a proper descriptive message */ bool ExecWait(pid_t Pid,const char *Name,bool Reap) { if (Pid <= 1) return true; - + // Wait and collect the error code int Status; while (waitpid(Pid,&Status,0) != Pid) @@ -962,11 +962,11 @@ bool ExecWait(pid_t Pid,const char *Name,bool Reap) if (Reap == true) return false; - + return _error->Error(_("Waited for %s but it wasn't there"),Name); } - + // Check for an error code. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0) { @@ -976,16 +976,16 @@ bool ExecWait(pid_t Pid,const char *Name,bool Reap) { if( WTERMSIG(Status) == SIGSEGV) return _error->Error(_("Sub-process %s received a segmentation fault."),Name); - else + else return _error->Error(_("Sub-process %s received signal %u."),Name, WTERMSIG(Status)); } if (WIFEXITED(Status) != 0) return _error->Error(_("Sub-process %s returned an error code (%u)"),Name,WEXITSTATUS(Status)); - + return _error->Error(_("Sub-process %s exited unexpectedly"),Name); - } - + } + return true; } /*}}}*/ @@ -2729,10 +2729,10 @@ bool FileFd::Read(void *To,unsigned long long Size,unsigned long long *Actual) if (Actual != nullptr) *Actual += Res; } - + if (Size == 0) return true; - + // Eof handling if (Actual != 0) { diff --git a/apt-pkg/contrib/gpgv.cc b/apt-pkg/contrib/gpgv.cc index c5ea19aa8..147f15d9d 100644 --- a/apt-pkg/contrib/gpgv.cc +++ b/apt-pkg/contrib/gpgv.cc @@ -35,18 +35,18 @@ class LineBuffer /*{{{*/ size_t buffer_size = 0; int line_length = 0; // a "normal" find_last_not_of returns npos if not found - int find_last_not_of_length(APT::StringView const bad) const + int find_last_not_of_length(std::string_view const bad) const { for (int result = line_length - 1; result >= 0; --result) - if (bad.find(buffer[result]) == APT::StringView::npos) + if (bad.find(buffer[result]) == std::string_view::npos) return result + 1; return 0; } public: bool empty() const noexcept { return view().empty(); } - APT::StringView view() const noexcept { return {buffer, static_cast<size_t>(line_length)}; } - bool starts_with(APT::StringView const start) const { return view().substr(0, start.size()) == start; } + std::string_view view() const noexcept { return {buffer, static_cast<size_t>(line_length)}; } + bool starts_with(std::string_view const start) const { return view().substr(0, start.size()) == start; } bool writeTo(FileFd *const to, size_t offset = 0) const { @@ -92,11 +92,11 @@ class LineBuffer /*{{{*/ ~LineBuffer() { free(buffer); } }; -static bool operator==(LineBuffer const &buf, APT::StringView const exp) noexcept +static bool operator==(LineBuffer const &buf, std::string_view const exp) noexcept { return buf.view() == exp; } -static bool operator!=(LineBuffer const &buf, APT::StringView const exp) noexcept +static bool operator!=(LineBuffer const &buf, std::string_view const exp) noexcept { return buf.view() != exp; } @@ -447,7 +447,7 @@ bool SplitClearSignedFile(std::string const &InFile, FileFd * const ContentFile, // but we assume that there will never be a header key starting with a dash return _error->Error("Clearsigned file '%s' contains unexpected line starting with a dash (%s)", InFile.c_str(), "armor"); if (ContentHeader != nullptr && buf.starts_with("Hash: ")) - ContentHeader->push_back(buf.view().to_string()); + ContentHeader->emplace_back(buf.view()); } // the message itself diff --git a/apt-pkg/contrib/string_view.h b/apt-pkg/contrib/string_view.h index 71f47f563..b062517b6 100644 --- a/apt-pkg/contrib/string_view.h +++ b/apt-pkg/contrib/string_view.h @@ -38,6 +38,7 @@ public: StringView(const char *data) : data_(data), size_(strlen(data)) {} StringView(std::string const & str): data_(str.data()), size_(str.size()) {} + inline StringView(std::string_view const & str): data_(str.data()), size_(str.size()) {} /* Modifiers */ void remove_prefix(size_t n) { data_ += n; size_ -= n; } @@ -136,17 +137,24 @@ public: constexpr char operator [](size_t i) const { return data_[i]; } constexpr size_t size() const { return size_; } constexpr size_t length() const { return size_; } + + inline constexpr operator std::string_view() const { return {data_, size_}; } }; +inline std::ostream& operator<<(std::ostream& os, const StringView& sv) +{ + return os << static_cast<std::string_view>(sv); +} + /** * \brief Faster comparison for string views (compare size before data) * * Still stable, but faster than the normal ordering. */ -static inline int StringViewCompareFast(StringView a, StringView b) { +static inline int StringViewCompareFast(const std::string_view & a, const std::string_view & b) { if (a.size() != b.size()) return a.size() - b.size(); - return memcmp(a.data(), b.data(), a.size()); + return a.compare(b); } static constexpr inline APT::StringView operator""_sv(const char *data, size_t size) @@ -157,7 +165,8 @@ static constexpr inline APT::StringView operator""_sv(const char *data, size_t s inline bool operator ==(const char *other, APT::StringView that); inline bool operator ==(const char *other, APT::StringView that) { return that.operator==(other); } -inline bool operator ==(std::string const &other, APT::StringView that); -inline bool operator ==(std::string const &other, APT::StringView that) { return that.operator==(other); } +template<class = void> bool operator ==(std::string_view const &other, APT::StringView const &that) { return that.operator==(other); } +template<class = void> bool operator !=(std::string_view const &other, APT::StringView const &that) { return that.operator!=(other); } +template<class = void> bool operator !=(APT::StringView const &that, std::string_view const &other) { return that.operator!=(other); } #endif diff --git a/apt-pkg/deb/deblistparser.cc b/apt-pkg/deb/deblistparser.cc index 13e8fd06d..3f37d2134 100644 --- a/apt-pkg/deb/deblistparser.cc +++ b/apt-pkg/deb/deblistparser.cc @@ -1,11 +1,11 @@ // -*- mode: cpp; mode: fold -*- // Description /*{{{*/ /* ###################################################################### - + Package Cache Generator - Generator for the cache structure. - - This builds the cache structure from the abstract package list parser. - + + This builds the cache structure from the abstract package list parser. + ##################################################################### */ /*}}}*/ // Include Files /*{{{*/ @@ -33,7 +33,8 @@ /*}}}*/ using std::string; -using APT::StringView; +using std::string_view; +using namespace std::literals; static const debListParser::WordList PrioList[] = { {"required",pkgCache::State::Required}, @@ -68,7 +69,7 @@ debListParser::debListParser(FileFd *File) : // --------------------------------------------------------------------- /* This is to return the name of the package this section describes */ string debListParser::Package() { - string Result = Section.Find(pkgTagSection::Key::Package).to_string(); + string Result{Section.Find(pkgTagSection::Key::Package)}; // Normalize mixed case package names to lower case, like dpkg does // See Bug#807012 for details. @@ -93,7 +94,7 @@ string debListParser::Package() { // ListParser::Architecture - Return the package arch /*{{{*/ // --------------------------------------------------------------------- /* This will return the Architecture of the package this section describes */ -APT::StringView debListParser::Architecture() { +std::string_view debListParser::Architecture() { auto const Arch = Section.Find(pkgTagSection::Key::Architecture); return Arch.empty() ? "none" : Arch; } @@ -108,9 +109,9 @@ bool debListParser::ArchitectureAll() { // ListParser::Version - Return the version string /*{{{*/ // --------------------------------------------------------------------- /* This is to return the string describing the version in debian form, - epoch:upstream-release. If this returns the blank string then the + epoch:upstream-release. If this returns the blank string then the entry is assumed to only describe package properties */ -APT::StringView debListParser::Version() +std::string_view debListParser::Version() { return Section.Find(pkgTagSection::Key::Version); } @@ -139,8 +140,8 @@ unsigned char debListParser::ParseMultiArch(bool const showErrors) /*{{{*/ else { if (showErrors == true) - _error->Warning("Unknown Multi-Arch type '%s' for package '%s'", - MultiArch.to_string().c_str(), Package().c_str()); + _error->Warning("Unknown Multi-Arch type '%.*s' for package '%s'", + (int)MultiArch.size(), MultiArch.data(), Package().c_str()); MA = pkgCache::Version::No; } @@ -185,7 +186,7 @@ bool debListParser::NewVersion(pkgCache::VerIterator &Ver) const char * const Close = static_cast<const char *>(memchr(Open, ')', Stop - Open)); if (likely(Close != NULL)) { - APT::StringView const version(Open + 1, (Close - Open) - 1); + std::string_view const version(Open + 1, (Close - Open) - 1); if (version != Ver.VerStr()) { map_stringitem_t const idx = StoreString(pkgCacheGenerator::VERSIONNUMBER, version); @@ -197,7 +198,7 @@ bool debListParser::NewVersion(pkgCache::VerIterator &Ver) Stop = Space; } - APT::StringView const pkgname(Start, Stop - Start); + std::string_view const pkgname(Start, Stop - Start); // Oh, our group is the wrong one for the source package. Make a new one. if (pkgname != G.Name()) { @@ -221,7 +222,7 @@ bool debListParser::NewVersion(pkgCache::VerIterator &Ver) // Priority if (Section.Find(pkgTagSection::Key::Priority,Start,Stop) == true) { - if (GrabWord(StringView(Start,Stop-Start),PrioList,Ver->Priority) == false) + if (GrabWord(string_view(Start,Stop-Start),PrioList,Ver->Priority) == false) Ver->Priority = pkgCache::State::Extra; } @@ -268,7 +269,7 @@ std::vector<std::string> debListParser::AvailableDescriptionLanguages() continue; } memcpy(buf + prefixLen, lang.c_str(), lang.size()); - if (Section.Exists(StringView(buf, prefixLen + lang.size())) == true) + if (Section.Exists(string_view(buf, prefixLen + lang.size())) == true) avail.push_back(lang); } return avail; @@ -280,14 +281,14 @@ std::vector<std::string> debListParser::AvailableDescriptionLanguages() description. If no Description-md5 is found in the section it will be calculated. */ -APT::StringView debListParser::Description_md5() +std::string_view debListParser::Description_md5() { return Section.Find(pkgTagSection::Key::Description_md5); } /*}}}*/ // ListParser::UsePackage - Update a package structure /*{{{*/ // --------------------------------------------------------------------- -/* This is called to update the package with any new information +/* This is called to update the package with any new information that might be found in the section */ bool debListParser::UsePackage(pkgCache::PkgIterator &Pkg, pkgCache::VerIterator &Ver) @@ -349,7 +350,7 @@ uint32_t debListParser::VersionHash() const char *End; if (Section.Find(I,Start,End) == false) continue; - + /* Strip out any spaces from the text, this undoes dpkgs reformatting of certain fields. dpkg also has the rather interesting notion of reformatting depends operators < -> <=, so we drop all = from the @@ -368,7 +369,7 @@ uint32_t debListParser::VersionHash() } - + return Result; } /*}}}*/ @@ -418,7 +419,7 @@ bool debStatusListParser::ParseStatus(pkgCache::PkgIterator &Pkg, {"deinstall",pkgCache::State::DeInstall}, {"purge",pkgCache::State::Purge}, {"", 0}}; - if (GrabWord(StringView(Start,I-Start),WantList,Pkg->SelectedState) == false) + if (GrabWord(string_view(Start,I-Start),WantList,Pkg->SelectedState) == false) return _error->Error("Malformed 1st word in the Status line"); // Isloate the next word @@ -434,7 +435,7 @@ bool debStatusListParser::ParseStatus(pkgCache::PkgIterator &Pkg, {"hold",pkgCache::State::HoldInst}, {"hold-reinstreq",pkgCache::State::HoldReInstReq}, {"", 0}}; - if (GrabWord(StringView(Start,I-Start),FlagList,Pkg->InstState) == false) + if (GrabWord(string_view(Start,I-Start),FlagList,Pkg->InstState) == false) return _error->Error("Malformed 2nd word in the Status line"); // Isloate the last word @@ -454,12 +455,12 @@ bool debStatusListParser::ParseStatus(pkgCache::PkgIterator &Pkg, {"triggers-pending",pkgCache::State::TriggersPending}, {"installed",pkgCache::State::Installed}, {"", 0}}; - if (GrabWord(StringView(Start,I-Start),StatusList,Pkg->CurrentState) == false) + if (GrabWord(string_view(Start,I-Start),StatusList,Pkg->CurrentState) == false) return _error->Error("Malformed 3rd word in the Status line"); /* A Status line marks the package as indicating the current version as well. Only if it is actually installed.. Otherwise - the interesting dpkg handling of the status file creates bogus + the interesting dpkg handling of the status file creates bogus entries. */ if (!(Pkg->CurrentState == pkgCache::State::NotInstalled || Pkg->CurrentState == pkgCache::State::ConfigFiles)) @@ -469,7 +470,7 @@ bool debStatusListParser::ParseStatus(pkgCache::PkgIterator &Pkg, else Pkg->CurrentVer = Ver.MapPointer(); } - + return true; } @@ -486,18 +487,18 @@ const char *debListParser::ConvertRelation(const char *I,unsigned int &Op) Op = pkgCache::Dep::LessEq; break; } - + if (*I == '<') { I++; Op = pkgCache::Dep::Less; break; } - + // < is the same as <= and << is really Cs < for some reason Op = pkgCache::Dep::LessEq; break; - + case '>': I++; if (*I == '=') @@ -506,18 +507,18 @@ const char *debListParser::ConvertRelation(const char *I,unsigned int &Op) Op = pkgCache::Dep::GreaterEq; break; } - + if (*I == '>') { I++; Op = pkgCache::Dep::Greater; break; } - + // > is the same as >= and >> is really Cs > for some reason Op = pkgCache::Dep::GreaterEq; break; - + case '=': Op = pkgCache::Dep::Equals; I++; @@ -552,19 +553,19 @@ const char *debListParser::ParseDepends(const char *Start,const char *Stop, bool const &ParseRestrictionsList, string const &Arch) { - StringView PackageView; - StringView VerView; + string_view PackageView; + string_view VerView; auto res = ParseDepends(Start, Stop, PackageView, VerView, Op, (bool)ParseArchFlags, (bool) StripMultiArch, (bool) ParseRestrictionsList, Arch); - Package = PackageView.to_string(); - Ver = VerView.to_string(); + Package = PackageView; + Ver = VerView; return res; } const char *debListParser::ParseDepends(const char *Start, const char *Stop, - StringView &Package, StringView &Ver, + string_view &Package, string_view &Ver, unsigned int &Op, bool ParseArchFlags, bool StripMultiArch, bool ParseRestrictionsList, string Arch) @@ -573,27 +574,27 @@ const char *debListParser::ParseDepends(const char *Start, const char *Stop, Arch = _config->Find("APT::Architecture"); // Strip off leading space for (;Start != Stop && isspace_ascii(*Start) != 0; ++Start); - + // Parse off the package name const char *I = Start; for (;I != Stop && isspace_ascii(*I) == 0 && *I != '(' && *I != ')' && *I != ',' && *I != '|' && *I != '[' && *I != ']' && *I != '<' && *I != '>'; ++I); - + // Malformed, no '(' if (I != Stop && *I == ')') return 0; if (I == Start) return 0; - + // Stash the package name - Package = StringView(Start, I - Start); + Package = string_view(Start, I - Start); // We don't want to confuse library users which can't handle MultiArch if (StripMultiArch == true) { size_t const found = Package.rfind(':'); - if (found != StringView::npos && + if (found != string_view::npos && (Package.substr(found) == ":any" || Package.substr(found) == ":native" || Package.substr(found +1) == Arch)) @@ -602,7 +603,7 @@ const char *debListParser::ParseDepends(const char *Start, const char *Stop, // Skip white space to the '(' for (;I != Stop && isspace_ascii(*I) != 0 ; I++); - + // Parse a version if (I != Stop && *I == '(') { @@ -611,27 +612,27 @@ const char *debListParser::ParseDepends(const char *Start, const char *Stop, if (I + 3 > Stop) return 0; I = ConvertRelation(I,Op); - + // Skip whitespace for (;I != Stop && isspace_ascii(*I) != 0; I++); Start = I; I = (const char*) memchr(I, ')', Stop - I); if (I == NULL || Start == I) return 0; - + // Skip trailing whitespace const char *End = I; for (; End > Start && isspace_ascii(End[-1]); End--); - - Ver = StringView(Start,End-Start); + + Ver = string_view(Start,End-Start); I++; } else { - Ver = StringView(); + Ver = string_view(); Op = pkgCache::Dep::NoOp; } - + // Skip whitespace for (;I != Stop && isspace_ascii(*I) != 0; I++); @@ -784,14 +785,14 @@ const char *debListParser::ParseDepends(const char *Start, const char *Stop, if (I != Stop && *I == '|') Op |= pkgCache::Dep::Or; - + if (I == Stop || *I == ',' || *I == '|') { if (I != Stop) for (I++; I != Stop && isspace_ascii(*I) != 0; I++); return I; } - + return 0; } /*}}}*/ @@ -812,8 +813,8 @@ bool debListParser::ParseDepends(pkgCache::VerIterator &Ver, while (1) { - StringView Package; - StringView Version; + string_view Package; + string_view Version; unsigned int Op; Start = ParseDepends(Start, Stop, Package, Version, Op, false, false, false, myArch); @@ -845,7 +846,7 @@ bool debListParser::ParseDepends(pkgCache::VerIterator &Ver, // … but this is probably the best thing to do anyway if (Package.substr(found + 1) == "native") { - std::string const Pkg = Package.substr(0, found).to_string() + ':' + Ver.Cache()->NativeArch(); + std::string const Pkg = (std::string{Package.substr(0, found)} += ':') += Ver.Cache()->NativeArch(); if (NewDepends(Ver, Pkg, "any", Version, Op | pkgCache::Dep::ArchSpecific, Type) == false) return false; } @@ -886,8 +887,8 @@ bool debListParser::ParseProvides(pkgCache::VerIterator &Ver) const char *Stop; if (Section.Find(pkgTagSection::Key::Provides,Start,Stop) && Start != Stop) { - StringView Package; - StringView Version; + string_view Package; + string_view Version; unsigned int Op; do @@ -897,9 +898,9 @@ bool debListParser::ParseProvides(pkgCache::VerIterator &Ver) if (Start == 0) return _error->Error("Problem parsing Provides line of %s:%s=%s", Ver.ParentPkg().Name(), Ver.Arch(), Ver.VerStr()); if (unlikely(Op != pkgCache::Dep::NoOp && Op != pkgCache::Dep::Equals)) { - _error->Warning("Ignoring non-equal Provides for package %s in %s:%s=%s", Package.to_string().c_str(), Ver.ParentPkg().Name(), Ver.Arch(), Ver.VerStr()); + _error->Warning("Ignoring non-equal Provides for package %.*s in %s:%s=%s", (int)Package.size(), Package.data(), Ver.ParentPkg().Name(), Ver.Arch(), Ver.VerStr()); } else if (archfound != string::npos) { - StringView spzArch = Package.substr(archfound + 1); + string_view spzArch = Package.substr(archfound + 1); if (spzArch != "any") { if (NewProvides(Ver, Package.substr(0, archfound), spzArch, Version, pkgCache::Flag::MultiArchImplicit | pkgCache::Flag::ArchSpecific) == false) @@ -918,7 +919,7 @@ bool debListParser::ParseProvides(pkgCache::VerIterator &Ver) } else { if ((Ver->MultiArch & pkgCache::Version::Allowed) == pkgCache::Version::Allowed && not barbarianArch) { - if (NewProvides(Ver, Package.to_string().append(":any"), "any", Version, pkgCache::Flag::MultiArchImplicit) == false) + if (NewProvides(Ver, std::string{Package}.append(":any"), "any", Version, pkgCache::Flag::MultiArchImplicit) == false) return false; } if (NewProvides(Ver, Package, Arch, Version, 0) == false) @@ -926,7 +927,7 @@ bool debListParser::ParseProvides(pkgCache::VerIterator &Ver) } if (archfound == std::string::npos) { - string spzName = Package.to_string(); + string spzName{Package}; spzName.push_back(':'); spzName.append(Ver.ParentPkg().Arch()); pkgCache::PkgIterator const spzPkg = Ver.Cache()->FindPkg(spzName, "any"); @@ -969,7 +970,7 @@ bool debListParser::ParseProvides(pkgCache::VerIterator &Ver) // ListParser::GrabWord - Matches a word and returns /*{{{*/ // --------------------------------------------------------------------- /* Looks for a word in a list of words - for ParseStatus */ -bool debListParser::GrabWord(StringView Word, WordList const *List, unsigned char &Out) +bool debListParser::GrabWord(string_view Word, WordList const *List, unsigned char &Out) { for (unsigned int C = 0; List[C].Str.empty() == false; C++) { @@ -1000,7 +1001,7 @@ unsigned char debListParser::GetPrio(string Str) unsigned char Out; if (GrabWord(Str,PrioList,Out) == false) Out = pkgCache::State::Extra; - + return Out; } /*}}}*/ diff --git a/apt-pkg/deb/deblistparser.h b/apt-pkg/deb/deblistparser.h index e6767d7d5..06d3715a4 100644 --- a/apt-pkg/deb/deblistparser.h +++ b/apt-pkg/deb/deblistparser.h @@ -1,10 +1,10 @@ // -*- mode: cpp; mode: fold -*- // Description /*{{{*/ /* ###################################################################### - - Debian Package List Parser - This implements the abstract parser + + Debian Package List Parser - This implements the abstract parser interface for Debian package files - + ##################################################################### */ /*}}}*/ #ifndef PKGLIB_DEBLISTPARSER_H @@ -20,7 +20,6 @@ #include <string> #include <vector> -#include <apt-pkg/string_view.h> class FileFd; @@ -32,7 +31,7 @@ class APT_HIDDEN debListParser : public pkgCacheListParser // Parser Helper struct WordList { - APT::StringView Str; + std::string_view Str; unsigned char Val; }; @@ -52,21 +51,21 @@ class APT_HIDDEN debListParser : public pkgCacheListParser unsigned int Type); bool ParseProvides(pkgCache::VerIterator &Ver); - APT_HIDDEN static bool GrabWord(APT::StringView Word,const WordList *List,unsigned char &Out); + APT_HIDDEN static bool GrabWord(std::string_view Word,const WordList *List,unsigned char &Out); APT_HIDDEN unsigned char ParseMultiArch(bool const showErrors); public: APT_PUBLIC static unsigned char GetPrio(std::string Str); - + // These all operate against the current section virtual std::string Package() APT_OVERRIDE; virtual bool ArchitectureAll() APT_OVERRIDE; - virtual APT::StringView Architecture() APT_OVERRIDE; - virtual APT::StringView Version() APT_OVERRIDE; + virtual std::string_view Architecture() APT_OVERRIDE; + virtual std::string_view Version() APT_OVERRIDE; virtual bool NewVersion(pkgCache::VerIterator &Ver) APT_OVERRIDE; virtual std::vector<std::string> AvailableDescriptionLanguages() APT_OVERRIDE; - virtual APT::StringView Description_md5() APT_OVERRIDE; + virtual std::string_view Description_md5() APT_OVERRIDE; virtual uint32_t VersionHash() APT_OVERRIDE; virtual bool SameVersion(uint32_t Hash, pkgCache::VerIterator const &Ver) APT_OVERRIDE; virtual bool UsePackage(pkgCache::PkgIterator &Pkg, @@ -83,8 +82,8 @@ class APT_HIDDEN debListParser : public pkgCacheListParser std::string const &Arch = ""); APT_PUBLIC static const char *ParseDepends(const char *Start, const char *Stop, - APT::StringView &Package, - APT::StringView &Ver, unsigned int &Op, + std::string_view &Package, + std::string_view &Ver, unsigned int &Op, bool const ParseArchFlags = false, bool StripMultiArch = true, bool const ParseRestrictionsList = false, std::string Arch = ""); @@ -95,7 +94,7 @@ class APT_HIDDEN debListParser : public pkgCacheListParser virtual ~debListParser(); #ifdef APT_COMPILING_APT - APT::StringView SHA256() const + std::string_view SHA256() const { return Section.Find(pkgTagSection::Key::SHA256); } @@ -117,8 +116,8 @@ class APT_HIDDEN debTranslationsParser : public debListParser { public: // a translation can never be a real package - virtual APT::StringView Architecture() APT_OVERRIDE { return ""; } - virtual APT::StringView Version() APT_OVERRIDE { return ""; } + virtual std::string_view Architecture() APT_OVERRIDE { return ""; } + virtual std::string_view Version() APT_OVERRIDE { return ""; } explicit debTranslationsParser(FileFd *File) : debListParser(File) {}; diff --git a/apt-pkg/deb/debmetaindex.cc b/apt-pkg/deb/debmetaindex.cc index 266313bef..b9369a898 100644 --- a/apt-pkg/deb/debmetaindex.cc +++ b/apt-pkg/deb/debmetaindex.cc @@ -533,7 +533,7 @@ bool debReleaseIndex::Load(std::string const &Filename, std::string * const Erro if (!parseSumData(Start, End, Name, Hash, Size)) return false; - HashString const hs(hashinfo.name.to_string(), Hash); + HashString const hs(std::string{hashinfo.name}, Hash); if (Entries.find(Name) == Entries.end()) { metaIndex::checkSum *Sum = new metaIndex::checkSum; @@ -698,7 +698,7 @@ bool debReleaseIndex::parseSumData(const char *&Start, const char *End, /*{{{*/ Start++; if (Start >= End) return false; - + EntryEnd = Start; /* Find the end of the second entry (the size) */ while ((*EntryEnd != '\t' && *EntryEnd != ' ' ) @@ -706,19 +706,19 @@ bool debReleaseIndex::parseSumData(const char *&Start, const char *End, /*{{{*/ EntryEnd++; if (EntryEnd == End) return false; - + Size = strtoull (Start, NULL, 10); - + /* Skip over intermediate blanks */ Start = EntryEnd; while (*Start == '\t' || *Start == ' ') Start++; if (Start >= End) return false; - + EntryEnd = Start; /* Find the end of the third entry (the filename) */ - while ((*EntryEnd != '\t' && *EntryEnd != ' ' && + while ((*EntryEnd != '\t' && *EntryEnd != ' ' && *EntryEnd != '\n' && *EntryEnd != '\r') && EntryEnd < End) EntryEnd++; @@ -1255,7 +1255,7 @@ class APT_HIDDEN debSLTypeDebian : public pkgSourceList::Type /*{{{*/ } protected: - // This is a duplicate of pkgAcqChangelog::URITemplate() with some changes to work + // This is a duplicate of pkgAcqChangelog::URITemplate() with some changes to work // on metaIndex instead of cache structures, and using Snapshots std::string SnapshotServer(debReleaseIndex const *Rls) const { diff --git a/apt-pkg/deb/debrecords.cc b/apt-pkg/deb/debrecords.cc index b9d1b6e2f..625bfab50 100644 --- a/apt-pkg/deb/debrecords.cc +++ b/apt-pkg/deb/debrecords.cc @@ -1,9 +1,9 @@ // -*- mode: cpp; mode: fold -*- // Description /*{{{*/ /* ###################################################################### - + Debian Package Records - Parser for debian package records - + ##################################################################### */ /*}}}*/ // Include Files /*{{{*/ @@ -58,13 +58,13 @@ debRecordParserBase::debRecordParserBase() : Parser(), d(NULL) {} // RecordParserBase::FileName - Return the archive filename on the site /*{{{*/ string debRecordParserBase::FileName() { - return Section.Find(pkgTagSection::Key::Filename).to_string(); + return string{Section.Find(pkgTagSection::Key::Filename)}; } /*}}}*/ // RecordParserBase::Name - Return the package name /*{{{*/ string debRecordParserBase::Name() { - auto Result = Section.Find(pkgTagSection::Key::Package).to_string(); + auto Result = string{Section.Find(pkgTagSection::Key::Package)}; // Normalize mixed case package names to lower case, like dpkg does // See Bug#807012 for details @@ -76,7 +76,7 @@ string debRecordParserBase::Name() // RecordParserBase::Homepage - Return the package homepage /*{{{*/ string debRecordParserBase::Homepage() { - return Section.Find(pkgTagSection::Key::Homepage).to_string(); + return string{Section.Find(pkgTagSection::Key::Homepage)}; } /*}}}*/ // RecordParserBase::Hashes - return the available archive hashes /*{{{*/ @@ -87,7 +87,7 @@ HashStringList debRecordParserBase::Hashes() const { std::string const hash = Section.FindS(*type); if (hash.empty() == false) - hashes.push_back(HashString(*type, hash)); + hashes.push_back(HashString(*type, std::move(hash))); } auto const size = Section.FindULL(pkgTagSection::Key::Size, 0); if (size != 0) @@ -98,7 +98,7 @@ HashStringList debRecordParserBase::Hashes() const // RecordParserBase::Maintainer - Return the maintainer email /*{{{*/ string debRecordParserBase::Maintainer() { - return Section.Find(pkgTagSection::Key::Maintainer).to_string(); + return string{Section.Find(pkgTagSection::Key::Maintainer)}; } /*}}}*/ // RecordParserBase::RecordField - Return the value of an arbitrary field /*{{*/ @@ -135,20 +135,20 @@ string debRecordParserBase::LongDesc(std::string const &lang) break; else if (*l == "en") { - orig = Section.Find(pkgTagSection::Key::Description).to_string(); + orig = Section.Find(pkgTagSection::Key::Description); if (orig.empty() == false) break; } } if (orig.empty() == true) - orig = Section.Find(pkgTagSection::Key::Description).to_string(); + orig = Section.Find(pkgTagSection::Key::Description); } else { std::string const tagname = "Description-" + lang; orig = Section.FindS(tagname.c_str()); if (orig.empty() == true && lang == "en") - orig = Section.Find(pkgTagSection::Key::Description).to_string(); + orig = Section.Find(pkgTagSection::Key::Description); } char const * const codeset = nl_langinfo(CODESET); @@ -166,7 +166,7 @@ static const char * const SourceVerSeparators = " ()"; // RecordParserBase::SourcePkg - Return the source package name if any /*{{{*/ string debRecordParserBase::SourcePkg() { - auto Res = Section.Find(pkgTagSection::Key::Source).to_string(); + auto Res = string{Section.Find(pkgTagSection::Key::Source)}; auto const Pos = Res.find_first_of(SourceVerSeparators); if (Pos != std::string::npos) Res.erase(Pos); @@ -176,22 +176,22 @@ string debRecordParserBase::SourcePkg() // RecordParserBase::SourceVer - Return the source version number if present /*{{{*/ string debRecordParserBase::SourceVer() { - auto const Pkg = Section.Find(pkgTagSection::Key::Source).to_string(); - string::size_type Pos = Pkg.find_first_of(SourceVerSeparators); - if (Pos == string::npos) + std::string_view Pkg = Section.Find(pkgTagSection::Key::Source); + auto Pos = Pkg.find_first_of(SourceVerSeparators); + if (Pos == std::string_view::npos) return ""; - string::size_type VerStart = Pkg.find_first_not_of(SourceVerSeparators, Pos); - if(VerStart == string::npos) + auto VerStart = Pkg.find_first_not_of(SourceVerSeparators, Pos); + if(VerStart == std::string_view::npos) return ""; - string::size_type VerEnd = Pkg.find_first_of(SourceVerSeparators, VerStart); - if(VerEnd == string::npos) + auto VerEnd = Pkg.find_first_of(SourceVerSeparators, VerStart); + if(VerEnd == std::string_view::npos) // Corresponds to the case of, e.g., "foo (1.2" without a closing // paren. Be liberal and guess what it means. - return string(Pkg, VerStart); + return string(Pkg.data(), VerStart); else - return string(Pkg, VerStart, VerEnd - VerStart); + return string(Pkg.data(), VerStart, VerEnd - VerStart); } /*}}}*/ // RecordParserBase::GetRec - Return the whole record /*{{{*/ diff --git a/apt-pkg/deb/debsrcrecords.cc b/apt-pkg/deb/debsrcrecords.cc index ab78b88ce..6b3cae143 100644 --- a/apt-pkg/deb/debsrcrecords.cc +++ b/apt-pkg/deb/debsrcrecords.cc @@ -1,10 +1,10 @@ // -*- mode: cpp; mode: fold -*- // Description /*{{{*/ /* ###################################################################### - + Debian Source Package Records - Parser implementation for Debian style source indexes - + ##################################################################### */ /*}}}*/ // Include Files /*{{{*/ @@ -46,8 +46,8 @@ std::string debSrcRecordParser::Package() const /*{{{*/ { auto const name = Sect.Find(pkgTagSection::Key::Package); if (iIndex != nullptr || name.empty() == false) - return name.to_string(); - return Sect.Find(pkgTagSection::Key::Source).to_string(); + return std::string{name}; + return std::string{Sect.Find(pkgTagSection::Key::Source)}; } /*}}}*/ // SrcRecordParser::Binaries - Return the binaries field /*{{{*/ @@ -93,9 +93,9 @@ const char **debSrcRecordParser::Binaries() /*}}}*/ // SrcRecordParser::BuildDepends - Return the Build-Depends information /*{{{*/ // --------------------------------------------------------------------- -/* This member parses the build-depends information and returns a list of - package/version records representing the build dependency. The returned - array need not be freed and will be reused by the next call to this +/* This member parses the build-depends information and returns a list of + package/version records representing the build dependency. The returned + array need not be freed and will be reused by the next call to this function */ bool debSrcRecordParser::BuildDepends(std::vector<pkgSrcRecords::Parser::BuildDepRec> &BuildDeps, bool const &ArchOnly, bool const &StripMultiArch) @@ -165,7 +165,7 @@ bool debSrcRecordParser::Files(std::vector<pkgSrcRecords::File> &List) List.clear(); // Stash the / terminated directory prefix - std::string Base = Sect.Find(pkgTagSection::Key::Directory).to_string(); + std::string Base{Sect.Find(pkgTagSection::Key::Directory)}; if (Base.empty() == false && Base[Base.length()-1] != '/') Base += '/'; @@ -177,7 +177,7 @@ bool debSrcRecordParser::Files(std::vector<pkgSrcRecords::File> &List) auto const Files = Sect.Find(hashinfo.chksumskey); if (Files.empty() == true) continue; - std::istringstream ss(Files.to_string()); + std::istringstream ss(std::string{Files}); // TODO: replace with std::string_view_stream in C++23 ss.imbue(posix); while (ss.good()) @@ -193,9 +193,9 @@ bool debSrcRecordParser::Files(std::vector<pkgSrcRecords::File> &List) ss >> hash >> size >> path; if (ss.fail() || hash.empty() || path.empty()) - return _error->Error("Error parsing file record in %s of source package %s", hashinfo.chksumsname.to_string().c_str(), Package().c_str()); + return _error->Error("Error parsing file record in %.*s of source package %s", (int)hashinfo.chksumsname.size(), hashinfo.chksumsname.data(), Package().c_str()); - HashString const hashString(hashinfo.name.to_string(), hash); + HashString const hashString(std::string{hashinfo.name}, hash); if (Base.empty() == false) path = Base + path; @@ -210,7 +210,7 @@ bool debSrcRecordParser::Files(std::vector<pkgSrcRecords::File> &List) { // an error here indicates that we have two different hashes for the same file if (file->Hashes.push_back(hashString) == false) - return _error->Error("Error parsing checksum in %s of source package %s", hashinfo.chksumsname.to_string().c_str(), Package().c_str()); + return _error->Error("Error parsing checksum in %.*s of source package %s", (int)hashinfo.chksumsname.size(), hashinfo.chksumsname.data(), Package().c_str()); continue; } diff --git a/apt-pkg/deb/debsrcrecords.h b/apt-pkg/deb/debsrcrecords.h index 6ba30c2ac..dedcb6dbe 100644 --- a/apt-pkg/deb/debsrcrecords.h +++ b/apt-pkg/deb/debsrcrecords.h @@ -1,10 +1,10 @@ // -*- mode: cpp; mode: fold -*- // Description /*{{{*/ /* ###################################################################### - + Debian Source Package Records - Parser implementation for Debian style source indexes - + ##################################################################### */ /*}}}*/ #ifndef PKGLIB_DEBSRCRECORDS_H @@ -33,7 +33,7 @@ class APT_HIDDEN debSrcRecordParser : public pkgSrcRecords::Parser std::vector<const char*> StaticBinList; unsigned long iOffset; char *Buffer; - + public: virtual bool Restart() APT_OVERRIDE {return Jump(0);}; @@ -41,13 +41,13 @@ class APT_HIDDEN debSrcRecordParser : public pkgSrcRecords::Parser virtual bool Jump(unsigned long const &Off) APT_OVERRIDE {iOffset = Off; return Tags.Jump(Sect,Off);}; virtual std::string Package() const APT_OVERRIDE; - virtual std::string Version() const APT_OVERRIDE {return Sect.Find(pkgTagSection::Key::Version).to_string();}; - virtual std::string Maintainer() const APT_OVERRIDE {return Sect.Find(pkgTagSection::Key::Maintainer).to_string();}; - virtual std::string Section() const APT_OVERRIDE {return Sect.Find(pkgTagSection::Key::Section).to_string();}; + virtual std::string Version() const APT_OVERRIDE {return std::string{Sect.Find(pkgTagSection::Key::Version)};}; + virtual std::string Maintainer() const APT_OVERRIDE {return std::string{Sect.Find(pkgTagSection::Key::Maintainer)};}; + virtual std::string Section() const APT_OVERRIDE {return std::string{Sect.Find(pkgTagSection::Key::Section)};}; virtual const char **Binaries() APT_OVERRIDE; virtual bool BuildDepends(std::vector<BuildDepRec> &BuildDeps, bool const &ArchOnly, bool const &StripMultiArch = true) APT_OVERRIDE; virtual unsigned long Offset() APT_OVERRIDE {return iOffset;}; - virtual std::string AsStr() APT_OVERRIDE + virtual std::string AsStr() APT_OVERRIDE { const char *Start=0,*Stop=0; Sect.GetSection(Start,Stop); diff --git a/apt-pkg/edsp.cc b/apt-pkg/edsp.cc index 0ffde46c0..d3ce830ea 100644 --- a/apt-pkg/edsp.cc +++ b/apt-pkg/edsp.cc @@ -20,7 +20,6 @@ #include <apt-pkg/prettyprinters.h> #include <apt-pkg/progress.h> #include <apt-pkg/solver3.h> -#include <apt-pkg/string_view.h> #include <apt-pkg/strutl.h> #include <apt-pkg/tagfile.h> @@ -55,7 +54,7 @@ constexpr char const * const DepMap[] = { // WriteOkay - varaidic helper to easily Write to a FileFd /*{{{*/ static bool WriteOkay_fn(FileFd &) { return true; } -template<typename... Tail> static bool WriteOkay_fn(FileFd &output, APT::StringView data, Tail... more_data) +template<typename... Tail> static bool WriteOkay_fn(FileFd &output, std::string_view data, Tail... more_data) { return likely(output.Write(data.data(), data.length()) && WriteOkay_fn(output, more_data...)); } @@ -217,7 +216,7 @@ static bool checkKnownArchitecture(std::string const &arch) /*{{{*/ return std::find(veryforeign.begin(), veryforeign.end(), arch) != veryforeign.end(); } /*}}}*/ -static bool WriteGenericRequestHeaders(FileFd &output, APT::StringView const head)/*{{{*/ +static bool WriteGenericRequestHeaders(FileFd &output, std::string_view const head)/*{{{*/ { bool Okay = WriteOkay(output, head, "Architecture: ", _config->Find("APT::Architecture"), "\n", "Architectures:"); @@ -537,7 +536,7 @@ static bool localStringToBool(std::string answer, bool const defValue) { return defValue; } /*}}}*/ -static bool LineStartsWithAndStrip(std::string &line, APT::StringView const with)/*{{{*/ +static bool LineStartsWithAndStrip(std::string &line, std::string_view const with)/*{{{*/ { if (line.compare(0, with.size(), with.data()) != 0) return false; @@ -545,7 +544,7 @@ static bool LineStartsWithAndStrip(std::string &line, APT::StringView const with return true; } /*}}}*/ -static bool ReadFlag(unsigned int &flags, std::string &line, APT::StringView const name, unsigned int const setflag)/*{{{*/ +static bool ReadFlag(unsigned int &flags, std::string &line, std::string_view const name, unsigned int const setflag)/*{{{*/ { if (LineStartsWithAndStrip(line, name) == false) return false; @@ -985,14 +984,14 @@ bool EIPP::WriteScenario(pkgDepCache &Cache, FileFd &output, OpProgress * const pkgset[P->ID] = true; if (strcmp(P.Arch(), "any") == 0) { - APT::StringView const pkgname(P.Name()); + std::string_view const pkgname(P.Name()); auto const idxColon = pkgname.find(':'); - if (idxColon != APT::StringView::npos) + if (idxColon != std::string_view::npos) { pkgCache::PkgIterator PA; if (pkgname.substr(idxColon + 1) == "any") { - auto const GA = Cache.FindGrp(pkgname.substr(0, idxColon).to_string()); + auto const GA = Cache.FindGrp(pkgname.substr(0, idxColon)); for (auto PA = GA.PackageList(); PA.end() == false; PA = GA.NextPkg(PA)) { pkgset[PA->ID] = true; @@ -1000,7 +999,7 @@ bool EIPP::WriteScenario(pkgDepCache &Cache, FileFd &output, OpProgress * const } else { - auto const PA = Cache.FindPkg(pkgname.to_string()); + auto const PA = Cache.FindPkg(pkgname); if (PA.end() == false) pkgset[PA->ID] = true; } diff --git a/apt-pkg/edsp/edsplistparser.cc b/apt-pkg/edsp/edsplistparser.cc index 183ace654..d3e761be4 100644 --- a/apt-pkg/edsp/edsplistparser.cc +++ b/apt-pkg/edsp/edsplistparser.cc @@ -17,7 +17,6 @@ #include <apt-pkg/fileutl.h> #include <apt-pkg/pkgcache.h> #include <apt-pkg/pkgsystem.h> -#include <apt-pkg/string_view.h> #include <apt-pkg/strutl.h> #include <apt-pkg/tagfile-keys.h> #include <apt-pkg/tagfile.h> @@ -48,7 +47,7 @@ bool edspLikeListParser::NewVersion(pkgCache::VerIterator &Ver) return false; // Patch up the source version, it is stored in the Source-Version field in EDSP. - if (APT::StringView version = Section.Find(pkgTagSection::Key::Source_Version); not version.empty()) + if (std::string_view version = Section.Find(pkgTagSection::Key::Source_Version); not version.empty()) { if (version != Ver.VerStr()) { @@ -67,9 +66,9 @@ std::vector<std::string> edspLikeListParser::AvailableDescriptionLanguages() { return {}; } -APT::StringView edspLikeListParser::Description_md5() +std::string_view edspLikeListParser::Description_md5() { - return APT::StringView(); + return {}; } /*}}}*/ // ListParser::VersionHash - Compute a unique hash for this version /*{{{*/ diff --git a/apt-pkg/edsp/edsplistparser.h b/apt-pkg/edsp/edsplistparser.h index 41bfd1f79..3f0f3e64c 100644 --- a/apt-pkg/edsp/edsplistparser.h +++ b/apt-pkg/edsp/edsplistparser.h @@ -18,15 +18,12 @@ #include <string> -namespace APT { - class StringView; -} class APT_HIDDEN edspLikeListParser : public debListParser { public: virtual bool NewVersion(pkgCache::VerIterator &Ver) APT_OVERRIDE; virtual std::vector<std::string> AvailableDescriptionLanguages() APT_OVERRIDE; - virtual APT::StringView Description_md5() APT_OVERRIDE; + virtual std::string_view Description_md5() APT_OVERRIDE; virtual uint32_t VersionHash() APT_OVERRIDE; explicit edspLikeListParser(FileFd *File); diff --git a/apt-pkg/indexcopy.cc b/apt-pkg/indexcopy.cc index bf787036f..e635b9042 100644 --- a/apt-pkg/indexcopy.cc +++ b/apt-pkg/indexcopy.cc @@ -3,9 +3,9 @@ /* ###################################################################### Index Copying - Aid for copying and verifying the index files - - This class helps apt-cache reconstruct a damaged index files. - + + This class helps apt-cache reconstruct a damaged index files. + ##################################################################### */ /*}}}*/ // Include Files /*{{{*/ @@ -48,13 +48,13 @@ bool IndexCopy::CopyPackages(string CDROM,string Name,vector<string> &List, OpProgress *Progress = NULL; if (List.empty() == true) return true; - - if(log) + + if(log) Progress = log->GetOpProgress(); - + bool NoStat = _config->FindB("APT::CDROM::Fast",false); bool Debug = _config->FindB("Debug::aptcdrom",false); - + // Prepare the progress indicator off_t TotalSize = 0; std::vector<APT::Configuration::Compressor> const compressor = APT::Configuration::getCompressors(); @@ -91,7 +91,7 @@ bool IndexCopy::CopyPackages(string CDROM,string Name,vector<string> &List, pkgTagFile Parser(&Pkg); if (Pkg.IsOpen() == false || Pkg.Failed()) return false; - + // Open the output file char S[400]; snprintf(S,sizeof(S),"cdrom:[%s]/%s%s",Name.c_str(), @@ -282,14 +282,14 @@ bool IndexCopy::ReconstructPrefix(string &Prefix,string OrigPath,string CD, cout << "Failed, " << CD + MyPrefix + File << endl; if (GrabFirst(OrigPath,MyPrefix,Depth++) == true) continue; - + return false; } else { Prefix = MyPrefix; return true; - } + } } return false; } @@ -324,16 +324,16 @@ bool IndexCopy::ReconstructChop(unsigned long &Chop,string Dir,string File) /*}}}*/ // IndexCopy::ConvertToSourceList - Convert a Path to a sourcelist /*{{{*/ // --------------------------------------------------------------------- -/* We look for things in dists/ notation and convert them to +/* We look for things in dists/ notation and convert them to <dist> <component> form otherwise it is left alone. This also strips - the CD path. - - This implements a regex sort of like: - (.*)/dists/([^/]*)/(.*)/binary-* + the CD path. + + This implements a regex sort of like: + (.*)/dists/([^/]*)/(.*)/binary-* ^ ^ ^- Component | |-------- Distribution |------------------- Path - + It was deciced to use only a single word for dist (rather than say unstable/non-us) to increase the chance that each CD gets a single line in sources.list. @@ -344,22 +344,22 @@ void IndexCopy::ConvertToSourceList(string CD,string &Path) Path = string(Path,CD.length()); if (Path.empty() == true) Path = "/"; - + // Too short to be a dists/ type if (Path.length() < strlen("dists/")) return; - + // Not a dists type. if (stringcmp(Path.c_str(),Path.c_str()+strlen("dists/"),"dists/") != 0) return; - + // Isolate the dist string::size_type Slash = strlen("dists/"); string::size_type Slash2 = Path.find('/',Slash + 1); if (Slash2 == string::npos || Slash2 + 2 >= Path.length()) return; string Dist = string(Path,Slash,Slash2 - Slash); - + // Isolate the component Slash = Slash2; for (unsigned I = 0; I != 10; I++) @@ -368,13 +368,13 @@ void IndexCopy::ConvertToSourceList(string CD,string &Path) if (Slash == string::npos || Slash + 2 >= Path.length()) return; string Comp = string(Path,Slash2+1,Slash - Slash2-1); - + // Verify the trailing binary- bit string::size_type BinSlash = Path.find('/',Slash + 1); if (Slash == string::npos) return; string Binary = string(Path,Slash+1,BinSlash - Slash-1); - + if (strncmp(Binary.c_str(), "binary-", strlen("binary-")) == 0) { Binary.erase(0, strlen("binary-")); @@ -386,7 +386,7 @@ void IndexCopy::ConvertToSourceList(string CD,string &Path) Path = Dist + ' ' + Comp; return; - } + } } /*}}}*/ // IndexCopy::GrabFirst - Return the first Depth path components /*{{{*/ @@ -401,7 +401,7 @@ bool IndexCopy::GrabFirst(string Path,string &To,unsigned int Depth) Depth--; } while (I != string::npos && Depth != 0); - + if (I == string::npos) return false; @@ -414,7 +414,7 @@ bool IndexCopy::GrabFirst(string Path,string &To,unsigned int Depth) /* */ bool PackageCopy::GetFile(string &File,unsigned long long &Size) { - File = Section->Find(pkgTagSection::Key::Filename).to_string(); + File = Section->Find(pkgTagSection::Key::Filename); Size = Section->FindULL(pkgTagSection::Key::Size); if (File.empty() || Size == 0) return _error->Error("Cannot find filename or size tag"); @@ -440,7 +440,7 @@ bool SourceCopy::GetFile(string &File,unsigned long long &Size) std::string Files; for (auto hashinfo : HashString::SupportedHashesInfo()) { - Files = Section->Find(hashinfo.chksumskey).to_string(); + Files = Section->Find(hashinfo.chksumskey); if (not Files.empty()) break; } @@ -451,17 +451,17 @@ bool SourceCopy::GetFile(string &File,unsigned long long &Size) const char *C = Files.c_str(); string sSize; string MD5Hash; - + // Parse each of the elements if (ParseQuoteWord(C,MD5Hash) == false || ParseQuoteWord(C,sSize) == false || ParseQuoteWord(C,File) == false) return _error->Error("Error parsing file record"); - + // Parse the size and append the directory Size = strtoull(sSize.c_str(), NULL, 10); auto const Base = Section->Find(pkgTagSection::Key::Directory); - File = flCombine(Base.to_string(), File); + File = flCombine(std::string{Base}, File); return true; } /*}}}*/ @@ -552,7 +552,7 @@ bool SigVerify::CopyAndVerify(string CDROM,string Name,vector<string> &SigList, cout << "Signature verify for: " << *I << endl; metaIndex *MetaIndex = new debReleaseIndex("","", {}); - string prefix = *I; + string prefix = *I; string const releasegpg = *I+"Release.gpg"; string const release = *I+"Release"; @@ -604,18 +604,18 @@ bool SigVerify::CopyAndVerify(string CDROM,string Name,vector<string> &SigList, // if so, remove them from our copy of the lists vector<string> keys = MetaIndex->MetaKeys(); for (vector<string>::iterator I = keys.begin(); I != keys.end(); ++I) - { + { if(!Verify(prefix,*I, MetaIndex)) { // something went wrong, don't copy the Release.gpg // FIXME: delete any existing gpg file? _error->Discard(); - continue; + continue; } } // we need a fresh one for the Release.gpg delete MetaIndex; - + // everything was fine, copy the Release and Release.gpg file if (useInRelease == true) CopyMetaIndex(CDROM, Name, prefix, "InRelease"); @@ -624,7 +624,7 @@ bool SigVerify::CopyAndVerify(string CDROM,string Name,vector<string> &SigList, CopyMetaIndex(CDROM, Name, prefix, "Release"); CopyMetaIndex(CDROM, Name, prefix, "Release.gpg"); } - } + } return true; } @@ -635,12 +635,12 @@ bool TranslationsCopy::CopyTranslations(string CDROM,string Name, /*{{{*/ OpProgress *Progress = NULL; if (List.empty() == true) return true; - - if(log) + + if(log) Progress = log->GetOpProgress(); - + bool Debug = _config->FindB("Debug::aptcdrom",false); - + // Prepare the progress indicator off_t TotalSize = 0; std::vector<APT::Configuration::Compressor> const compressor = APT::Configuration::getCompressors(); diff --git a/apt-pkg/pkgcachegen.cc b/apt-pkg/pkgcachegen.cc index 981d360d2..ab697fbce 100644 --- a/apt-pkg/pkgcachegen.cc +++ b/apt-pkg/pkgcachegen.cc @@ -1,11 +1,11 @@ // -*- mode: cpp; mode: fold -*- // Description /*{{{*/ /* ###################################################################### - + Package Cache Generator - Generator for the cache structure. - - This builds the cache structure from the abstract package list parser. - + + This builds the cache structure from the abstract package list parser. + ##################################################################### */ /*}}}*/ // Include Files /*{{{*/ @@ -24,6 +24,7 @@ #include <apt-pkg/pkgsystem.h> #include <apt-pkg/progress.h> #include <apt-pkg/sourcelist.h> +#include <apt-pkg/string_view.h> #include <apt-pkg/version.h> #include <algorithm> @@ -45,10 +46,10 @@ typedef std::vector<pkgIndexFile *>::iterator FileIterator; template <typename Iter> std::vector<Iter*> pkgCacheGenerator::Dynamic<Iter>::toReMap; static bool IsDuplicateDescription(pkgCache &Cache, pkgCache::DescIterator Desc, - APT::StringView CurMd5, std::string const &CurLang); + std::string_view CurMd5, std::string const &CurLang); using std::string; -using APT::StringView; +using std::string_view; // Convert an offset returned from e.g. DynamicMMap or ptr difference to // an uint32_t location without data loss. @@ -129,7 +130,7 @@ bool pkgCacheGenerator::Start() else { // Map directly from the existing file - Cache.ReMap(); + Cache.ReMap(); Map.UsePools(*Cache.HeaderP->Pools,sizeof(Cache.HeaderP->Pools)/sizeof(Cache.HeaderP->Pools[0])); if (Cache.VS != _system->VS) return _error->Error(_("Cache has an incompatible versioning system")); @@ -150,7 +151,7 @@ pkgCacheGenerator::~pkgCacheGenerator() return; if (Map.Sync() == false) return; - + Cache.HeaderP->Dirty = false; Cache.HeaderP->CacheFileSize = Cache.CacheHash(); @@ -192,7 +193,7 @@ void pkgCacheGenerator::ReMap(void const * const oldMap, void * const newMap, si APT_REMAP(pkgCache::RlsFileIterator); #undef APT_REMAP - for (APT::StringView* ViewP : Dynamic<APT::StringView>::toReMap) { + for (std::string_view* ViewP : Dynamic<std::string_view>::toReMap) { if (std::get<1>(seen.insert(ViewP)) == false) continue; // Ignore views outside of the cache. @@ -200,7 +201,7 @@ void pkgCacheGenerator::ReMap(void const * const oldMap, void * const newMap, si || ViewP->data() > static_cast<const char*>(oldMap) + oldSize) continue; const char *data = ViewP->data() + (static_cast<const char*>(newMap) - static_cast<const char*>(oldMap)); - *ViewP = StringView(data , ViewP->size()); + *ViewP = string_view(data , ViewP->size()); } } /*}}}*/ // CacheGenerator::WriteStringInMap /*{{{*/ @@ -255,10 +256,10 @@ bool pkgCacheGenerator::MergeList(ListParser &List, if (Counter % 100 == 0 && Progress != 0) Progress->Progress(List.Offset()); - APT::StringView Arch = List.Architecture(); - Dynamic<APT::StringView> DynArch(Arch); - APT::StringView Version = List.Version(); - Dynamic<APT::StringView> DynVersion(Version); + std::string_view Arch = List.Architecture(); + Dynamic<std::string_view> DynArch(Arch); + std::string_view Version = List.Version(); + Dynamic<std::string_view> DynVersion(Version); if (Version.empty() == true && Arch.empty() == true) { // package descriptions @@ -339,7 +340,7 @@ bool pkgCacheGenerator::MergeListPackage(ListParser &List, pkgCache::PkgIterator Pkg.Name(), "UsePackage", 1); // Find the right version to write the description - StringView CurMd5 = List.Description_md5(); + string_view CurMd5 = List.Description_md5(); std::vector<std::string> availDesc = List.AvailableDescriptionLanguages(); for (Ver = Pkg.VersionList(); Ver.end() == false; ++Ver) { @@ -369,7 +370,7 @@ bool pkgCacheGenerator::MergeListPackage(ListParser &List, pkgCache::PkgIterator /*}}}*/ // CacheGenerator::MergeListVersion /*{{{*/ bool pkgCacheGenerator::MergeListVersion(ListParser &List, pkgCache::PkgIterator &Pkg, - APT::StringView const &Version, pkgCache::VerIterator* &OutVer) + std::string_view const &Version, pkgCache::VerIterator* &OutVer) { pkgCache::VerIterator Ver = Pkg.VersionList(); Dynamic<pkgCache::VerIterator> DynVer(Ver); @@ -377,7 +378,7 @@ bool pkgCacheGenerator::MergeListVersion(ListParser &List, pkgCache::PkgIterator void const * oldMap = Map.Data(); auto Hash = List.VersionHash(); - APT::StringView ListSHA256; + std::string_view ListSHA256; bool const Debug = _config->FindB("Debug::pkgCacheGen", false); auto DebList = dynamic_cast<debListParser *>(&List); @@ -405,10 +406,10 @@ bool pkgCacheGenerator::MergeListVersion(ListParser &List, pkgCache::PkgIterator if (ListSHA256.empty() || VersionExtra[Ver->ID].SHA256[0] == 0) break; // We have SHA256 for both, so they must match. - if (ListSHA256 == APT::StringView(VersionExtra[Ver->ID].SHA256, 64)) + if (ListSHA256 == std::string_view(VersionExtra[Ver->ID].SHA256, 64)) break; if (Debug) - std::cerr << "Found differing SHA256 for " << Pkg.Name() << "=" << Version.to_string() << std::endl; + std::cerr << "Found differing SHA256 for " << Pkg.Name() << "=" << Version << std::endl; } // sort (volatile) sources above not-sources like the status file @@ -506,7 +507,7 @@ bool pkgCacheGenerator::MergeListVersion(ListParser &List, pkgCache::PkgIterator } /* Record the Description(s) based on their master md5sum */ - StringView CurMd5 = List.Description_md5(); + string_view CurMd5 = List.Description_md5(); /* Before we add a new description we first search in the group for a version with a description of the same MD5 - if so we reuse this @@ -532,7 +533,7 @@ bool pkgCacheGenerator::MergeListVersion(ListParser &List, pkgCache::PkgIterator return true; } /*}}}*/ -bool pkgCacheGenerator::AddNewDescription(ListParser &List, pkgCache::VerIterator &Ver, std::string const &lang, APT::StringView CurMd5, map_stringitem_t &md5idx) /*{{{*/ +bool pkgCacheGenerator::AddNewDescription(ListParser &List, pkgCache::VerIterator &Ver, std::string const &lang, std::string_view CurMd5, map_stringitem_t &md5idx) /*{{{*/ { pkgCache::DescIterator Desc; Dynamic<pkgCache::DescIterator> DynDesc(Desc); @@ -563,9 +564,9 @@ bool pkgCacheGenerator::AddNewDescription(ListParser &List, pkgCache::VerIterato // CacheGenerator::NewGroup - Add a new group /*{{{*/ // --------------------------------------------------------------------- /* This creates a new group structure and adds it to the hash table */ -bool pkgCacheGenerator::NewGroup(pkgCache::GrpIterator &Grp, StringView Name) +bool pkgCacheGenerator::NewGroup(pkgCache::GrpIterator &Grp, string_view Name) { - Dynamic<StringView> DName(Name); + Dynamic<string_view> DName(Name); Grp = Cache.FindGrp(Name); if (Grp.end() == false) return true; @@ -598,11 +599,11 @@ bool pkgCacheGenerator::NewGroup(pkgCache::GrpIterator &Grp, StringView Name) // CacheGenerator::NewPackage - Add a new package /*{{{*/ // --------------------------------------------------------------------- /* This creates a new package structure and adds it to the hash table */ -bool pkgCacheGenerator::NewPackage(pkgCache::PkgIterator &Pkg, StringView Name, - StringView Arch) { +bool pkgCacheGenerator::NewPackage(pkgCache::PkgIterator &Pkg, string_view Name, + string_view Arch) { pkgCache::GrpIterator Grp; - Dynamic<StringView> DName(Name); - Dynamic<StringView> DArch(Arch); + Dynamic<string_view> DName(Name); + Dynamic<string_view> DArch(Arch); Dynamic<pkgCache::GrpIterator> DynGrp(Grp); if (unlikely(NewGroup(Grp, Name) == false)) return false; @@ -714,24 +715,24 @@ bool pkgCacheGenerator::NewPackage(pkgCache::PkgIterator &Pkg, StringView Name, if (Arch == "any") { size_t const found = Name.rfind(':'); - StringView ArchA = Name.substr(found + 1); + string_view ArchA = Name.substr(found + 1); if (ArchA != "any") { // ArchA is used inside the loop which might remap (NameA is not used) - Dynamic<StringView> DynArchA(ArchA); - StringView NameA = Name.substr(0, found); + Dynamic<string_view> DynArchA(ArchA); + string_view NameA = Name.substr(0, found); pkgCache::PkgIterator PkgA = Cache.FindPkg(NameA, ArchA); Dynamic<pkgCache::PkgIterator> DynPkgA(PkgA); if (PkgA.end()) { - Dynamic<StringView> DynNameA(NameA); + Dynamic<string_view> DynNameA(NameA); if (NewPackage(PkgA, NameA, ArchA) == false) return false; } if (unlikely(PkgA.end())) - return _error->Fatal("NewPackage was successful for %s:%s," + return _error->Fatal("NewPackage was successful for %.*s:%.*s," "but the package doesn't exist anyhow!", - NameA.to_string().c_str(), ArchA.to_string().c_str()); + (int)NameA.size(), NameA.data(), (int)ArchA.size(), ArchA.data()); else { pkgCache::PrvIterator Prv = PkgA.ProvidesList(); @@ -763,8 +764,8 @@ bool pkgCacheGenerator::AddImplicitDepends(pkgCache::GrpIterator &G, pkgCache::PkgIterator &P, pkgCache::VerIterator &V) { - APT::StringView Arch = P.Arch() == NULL ? "" : P.Arch(); - Dynamic<APT::StringView> DynArch(Arch); + std::string_view Arch = P.Arch() == NULL ? "" : P.Arch(); + Dynamic<std::string_view> DynArch(Arch); map_pointer<pkgCache::Dependency> *OldDepLast = NULL; /* MultiArch handling introduces a lot of implicit Dependencies: - MultiArch: same → Co-Installable if they have the same version @@ -836,28 +837,28 @@ bool pkgCacheGenerator::NewFileVer(pkgCache::VerIterator &Ver, { if (CurrentFile == nullptr) return true; - + // Get a structure auto const VerFile = AllocateInMap<pkgCache::VerFile>(); if (VerFile == 0) return false; - + pkgCache::VerFileIterator VF(Cache,Cache.VerFileP + VerFile); VF->File = map_pointer<pkgCache::PackageFile>{NarrowOffset(CurrentFile - Cache.PkgFileP)}; - + // Link it to the end of the list map_pointer<pkgCache::VerFile> *Last = &Ver->FileList; for (pkgCache::VerFileIterator V = Ver.FileList(); V.end() == false; ++V) Last = &V->NextFile; VF->NextFile = *Last; *Last = VF.MapPointer(); - + VF->Offset = List.Offset(); VF->Size = List.Size(); if (Cache.HeaderP->MaxVerFileSize < VF->Size) Cache.HeaderP->MaxVerFileSize = VF->Size; Cache.HeaderP->VerFileCount++; - + return true; } /*}}}*/ @@ -865,7 +866,7 @@ bool pkgCacheGenerator::NewFileVer(pkgCache::VerIterator &Ver, // --------------------------------------------------------------------- /* This puts a version structure in the linked list */ map_pointer<pkgCache::Version> pkgCacheGenerator::NewVersion(pkgCache::VerIterator &Ver, - APT::StringView const &VerStr, + std::string_view const &VerStr, map_pointer<pkgCache::Package> const ParentPkg, uint32_t Hash, map_pointer<pkgCache::Version> const Next) @@ -874,7 +875,7 @@ map_pointer<pkgCache::Version> pkgCacheGenerator::NewVersion(pkgCache::VerIterat auto const Version = AllocateInMap<pkgCache::Version>(); if (Version == 0) return 0; - + // Fill it in Ver = pkgCache::VerIterator(Cache,Cache.VerP + Version); auto d = AllocateInMap<pkgCache::Version::Extra>(); // sequence point so Ver can be moved if needed @@ -930,7 +931,7 @@ bool pkgCacheGenerator::NewFileDesc(pkgCache::DescIterator &Desc, { if (CurrentFile == nullptr) return true; - + // Get a structure auto const DescFile = AllocateInMap<pkgCache::DescFile>(); if (DescFile == 0) @@ -946,13 +947,13 @@ bool pkgCacheGenerator::NewFileDesc(pkgCache::DescIterator &Desc, DF->NextFile = *Last; *Last = DF.MapPointer(); - + DF->Offset = List.Offset(); DF->Size = List.Size(); if (Cache.HeaderP->MaxDescFileSize < DF->Size) Cache.HeaderP->MaxDescFileSize = DF->Size; Cache.HeaderP->DescFileCount++; - + return true; } /*}}}*/ @@ -961,7 +962,7 @@ bool pkgCacheGenerator::NewFileDesc(pkgCache::DescIterator &Desc, /* This puts a description structure in the linked list */ map_pointer<pkgCache::Description> pkgCacheGenerator::NewDescription(pkgCache::DescIterator &Desc, const string &Lang, - APT::StringView md5sum, + std::string_view md5sum, map_stringitem_t const idxmd5str) { // Get a structure @@ -1094,17 +1095,17 @@ bool pkgCacheGenerator::NewDepends(pkgCache::PkgIterator &Pkg, /* This creates a Group and the Package to link this dependency to if needed and handles also the caching of the old endpoint */ bool pkgCacheListParser::NewDepends(pkgCache::VerIterator &Ver, - StringView PackageName, - StringView Arch, - StringView Version, + string_view PackageName, + string_view Arch, + string_view Version, uint8_t const Op, uint8_t const Type) { pkgCache::GrpIterator Grp; Dynamic<pkgCache::GrpIterator> DynGrp(Grp); - Dynamic<StringView> DynPackageName(PackageName); - Dynamic<StringView> DynArch(Arch); - Dynamic<StringView> DynVersion(Version); + Dynamic<string_view> DynPackageName(PackageName); + Dynamic<string_view> DynArch(Arch); + Dynamic<string_view> DynVersion(Version); if (unlikely(Owner->NewGroup(Grp, PackageName) == false)) return false; @@ -1166,18 +1167,18 @@ bool pkgCacheListParser::NewDepends(pkgCache::VerIterator &Ver, /*}}}*/ // ListParser::NewProvides - Create a Provides element /*{{{*/ bool pkgCacheListParser::NewProvides(pkgCache::VerIterator &Ver, - StringView PkgName, - StringView PkgArch, - StringView Version, + string_view PkgName, + string_view PkgArch, + string_view Version, uint8_t const Flags) { pkgCache const &Cache = Owner->Cache; - Dynamic<StringView> DynPkgName(PkgName); - Dynamic<StringView> DynArch(PkgArch); - Dynamic<StringView> DynVersion(Version); + Dynamic<string_view> DynPkgName(PkgName); + Dynamic<string_view> DynArch(PkgArch); + Dynamic<string_view> DynVersion(Version); // We do not add self referencing provides - if (Ver.ParentPkg().Name() == PkgName && (PkgArch == Ver.ParentPkg().Arch() || + if (string_view{Ver.ParentPkg().Name()} == PkgName && (PkgArch == Ver.ParentPkg().Arch() || (PkgArch == "all" && strcmp((Cache.StrP + Cache.HeaderP->Architecture), Ver.ParentPkg().Arch()) == 0)) && (Version.empty() || Version == Ver.VerStr())) return true; @@ -1223,13 +1224,13 @@ bool pkgCacheGenerator::NewProvides(pkgCache::VerIterator &Ver, } /*}}}*/ // ListParser::NewProvidesAllArch - add provides for all architectures /*{{{*/ -bool pkgCacheListParser::NewProvidesAllArch(pkgCache::VerIterator &Ver, StringView Package, - StringView Version, uint8_t const Flags) { +bool pkgCacheListParser::NewProvidesAllArch(pkgCache::VerIterator &Ver, string_view Package, + string_view Version, uint8_t const Flags) { pkgCache &Cache = Owner->Cache; pkgCache::GrpIterator Grp = Cache.FindGrp(Package); Dynamic<pkgCache::GrpIterator> DynGrp(Grp); - Dynamic<StringView> DynPackage(Package); - Dynamic<StringView> DynVersion(Version); + Dynamic<string_view> DynPackage(Package); + Dynamic<string_view> DynVersion(Version); if (Grp.end() == true || Grp->FirstPackage == 0) return NewProvides(Ver, Package, Cache.NativeArch(), Version, Flags); @@ -1615,7 +1616,7 @@ static bool BuildCache(pkgCacheGenerator &Gen, /*}}}*/ // CacheGenerator::MakeStatusCache - Construct the status cache /*{{{*/ // --------------------------------------------------------------------- -/* This makes sure that the status cache (the cache that has all +/* This makes sure that the status cache (the cache that has all index files from the sources list and all local ones) is ready to be mmaped. If OutMap is not zero then a MMap object representing the cache will be stored there. This is pretty much mandatory if you @@ -1868,13 +1869,13 @@ bool pkgCacheGenerator::MakeOnlyStatusCache(OpProgress *Progress,DynamicMMap **O if (_error->PendingError() == true) return false; *OutMap = Map.release(); - + return true; } /*}}}*/ // IsDuplicateDescription /*{{{*/ static bool IsDuplicateDescription(pkgCache &Cache, pkgCache::DescIterator Desc, - APT::StringView CurMd5, std::string const &CurLang) + std::string_view CurMd5, std::string const &CurLang) { // Descriptions in the same link-list have all the same md5 if (Desc.end() == true || Cache.ViewString(Desc->md5sum) != CurMd5) diff --git a/apt-pkg/pkgcachegen.h b/apt-pkg/pkgcachegen.h index 420642684..3c0295220 100644 --- a/apt-pkg/pkgcachegen.h +++ b/apt-pkg/pkgcachegen.h @@ -27,7 +27,6 @@ #if __cplusplus >= 201103L #include <unordered_set> #endif -#include <apt-pkg/string_view.h> #ifdef APT_COMPILING_APT #include <xxhash.h> @@ -41,7 +40,7 @@ class pkgCacheListParser; class APT_HIDDEN pkgCacheGenerator /*{{{*/ { - APT_HIDDEN map_stringitem_t WriteStringInMap(APT::StringView String) { return WriteStringInMap(String.data(), String.size()); }; + APT_HIDDEN map_stringitem_t WriteStringInMap(std::string_view String) { return WriteStringInMap(String.data(), String.size()); }; APT_HIDDEN map_stringitem_t WriteStringInMap(const char *String); APT_HIDDEN map_stringitem_t WriteStringInMap(const char *String, const unsigned long &Len); APT_HIDDEN uint32_t AllocateInMap(const unsigned long &size); @@ -115,12 +114,12 @@ class APT_HIDDEN pkgCacheGenerator /*{{{*/ std::string PkgFileName; pkgCache::PackageFile *CurrentFile; - bool NewGroup(pkgCache::GrpIterator &Grp, APT::StringView Name); - bool NewPackage(pkgCache::PkgIterator &Pkg, APT::StringView Name, APT::StringView Arch); - map_pointer<pkgCache::Version> NewVersion(pkgCache::VerIterator &Ver, APT::StringView const &VerStr, + bool NewGroup(pkgCache::GrpIterator &Grp, std::string_view Name); + bool NewPackage(pkgCache::PkgIterator &Pkg, std::string_view Name, std::string_view Arch); + map_pointer<pkgCache::Version> NewVersion(pkgCache::VerIterator &Ver, std::string_view const &VerStr, map_pointer<pkgCache::Package> const ParentPkg, uint32_t Hash, map_pointer<pkgCache::Version> const Next); - map_pointer<pkgCache::Description> NewDescription(pkgCache::DescIterator &Desc,const std::string &Lang, APT::StringView md5sum,map_stringitem_t const idxmd5str); + map_pointer<pkgCache::Description> NewDescription(pkgCache::DescIterator &Desc,const std::string &Lang, std::string_view md5sum,map_stringitem_t const idxmd5str); bool NewFileVer(pkgCache::VerIterator &Ver,ListParser &List); bool NewFileDesc(pkgCache::DescIterator &Desc,ListParser &List); bool NewDepends(pkgCache::PkgIterator &Pkg, pkgCache::VerIterator &Ver, @@ -134,7 +133,7 @@ class APT_HIDDEN pkgCacheGenerator /*{{{*/ enum StringType { MIXED, VERSIONNUMBER, SECTION }; map_stringitem_t StoreString(StringType const type, const char * S, unsigned int const Size); - inline map_stringitem_t StoreString(enum StringType const type, APT::StringView S) {return StoreString(type, S.data(),S.length());}; + inline map_stringitem_t StoreString(enum StringType const type, std::string_view S) {return StoreString(type, S.data(),S.length());}; void DropProgress() {Progress = 0;}; bool SelectFile(const std::string &File,pkgIndexFile const &Index, std::string const &Architecture, std::string const &Component, unsigned long Flags = 0); @@ -163,14 +162,14 @@ class APT_HIDDEN pkgCacheGenerator /*{{{*/ APT_HIDDEN bool MergeListGroup(ListParser &List, std::string const &GrpName); APT_HIDDEN bool MergeListPackage(ListParser &List, pkgCache::PkgIterator &Pkg); APT_HIDDEN bool MergeListVersion(ListParser &List, pkgCache::PkgIterator &Pkg, - APT::StringView const &Version, pkgCache::VerIterator* &OutVer); + std::string_view const &Version, pkgCache::VerIterator* &OutVer); APT_HIDDEN bool AddImplicitDepends(pkgCache::GrpIterator &G, pkgCache::PkgIterator &P, pkgCache::VerIterator &V); APT_HIDDEN bool AddImplicitDepends(pkgCache::VerIterator &V, pkgCache::PkgIterator &D); APT_HIDDEN bool AddNewDescription(ListParser &List, pkgCache::VerIterator &Ver, - std::string const &lang, APT::StringView CurMd5, map_stringitem_t &md5idx); + std::string const &lang, std::string_view CurMd5, map_stringitem_t &md5idx); }; /*}}}*/ // This is the abstract package list parser class. /*{{{*/ @@ -186,30 +185,30 @@ class APT_HIDDEN pkgCacheListParser void * const d; protected: - inline bool NewGroup(pkgCache::GrpIterator &Grp, APT::StringView Name) { return Owner->NewGroup(Grp, Name); } + inline bool NewGroup(pkgCache::GrpIterator &Grp, std::string_view Name) { return Owner->NewGroup(Grp, Name); } inline map_stringitem_t StoreString(pkgCacheGenerator::StringType const type, const char *S,unsigned int Size) {return Owner->StoreString(type, S, Size);}; - inline map_stringitem_t StoreString(pkgCacheGenerator::StringType const type, APT::StringView S) {return Owner->StoreString(type, S);}; - inline map_stringitem_t WriteString(APT::StringView S) {return Owner->WriteStringInMap(S.data(), S.size());}; + inline map_stringitem_t StoreString(pkgCacheGenerator::StringType const type, std::string_view S) {return Owner->StoreString(type, S);}; + inline map_stringitem_t WriteString(std::string_view S) {return Owner->WriteStringInMap(S.data(), S.size());}; inline map_stringitem_t WriteString(const char *S,unsigned int Size) {return Owner->WriteStringInMap(S,Size);}; - bool NewDepends(pkgCache::VerIterator &Ver,APT::StringView Package, APT::StringView Arch, - APT::StringView Version,uint8_t const Op, + bool NewDepends(pkgCache::VerIterator &Ver,std::string_view Package, std::string_view Arch, + std::string_view Version,uint8_t const Op, uint8_t const Type); - bool NewProvides(pkgCache::VerIterator &Ver,APT::StringView PkgName, - APT::StringView PkgArch, APT::StringView Version, + bool NewProvides(pkgCache::VerIterator &Ver,std::string_view PkgName, + std::string_view PkgArch, std::string_view Version, uint8_t const Flags); - bool NewProvidesAllArch(pkgCache::VerIterator &Ver, APT::StringView Package, - APT::StringView Version, uint8_t const Flags); + bool NewProvidesAllArch(pkgCache::VerIterator &Ver, std::string_view Package, + std::string_view Version, uint8_t const Flags); public: // These all operate against the current section virtual std::string Package() = 0; virtual bool ArchitectureAll() = 0; - virtual APT::StringView Architecture() = 0; - virtual APT::StringView Version() = 0; + virtual std::string_view Architecture() = 0; + virtual std::string_view Version() = 0; virtual bool NewVersion(pkgCache::VerIterator &Ver) = 0; virtual std::vector<std::string> AvailableDescriptionLanguages() = 0; - virtual APT::StringView Description_md5() = 0; + virtual std::string_view Description_md5() = 0; virtual uint32_t VersionHash() = 0; /** compare currently parsed version with given version * diff --git a/apt-pkg/policy.cc b/apt-pkg/policy.cc index 5d361af1a..a54f04db6 100644 --- a/apt-pkg/policy.cc +++ b/apt-pkg/policy.cc @@ -21,7 +21,6 @@ #include <apt-pkg/fileutl.h> #include <apt-pkg/pkgcache.h> #include <apt-pkg/policy.h> -#include <apt-pkg/string_view.h> #include <apt-pkg/strutl.h> #include <apt-pkg/tagfile-keys.h> #include <apt-pkg/tagfile.h> @@ -438,13 +437,13 @@ bool ReadPinFile(pkgPolicy &Plcy,string File) if (Name.empty()) return _error->Error(_("Invalid record in the preferences file %s, no Package header"), File.c_str()); if (Name == "*") - Name = APT::StringView{}; + Name = {}; const char *Start; const char *End; if (Tags.Find("Pin",Start,End) == false) continue; - + const char *Word = Start; for (; Word != End && isspace(*Word) == 0; Word++); @@ -490,7 +489,7 @@ bool ReadPinFile(pkgPolicy &Plcy,string File) return _error->Error(_("No priority (or zero) specified for pin")); } - std::istringstream s(Name.to_string()); + std::istringstream s(std::string{Name}); // TODO: replace with std::string_view_stream in C++23 string pkg; while(!s.eof()) { diff --git a/apt-pkg/tagfile.cc b/apt-pkg/tagfile.cc index 934a89d59..aff786df1 100644 --- a/apt-pkg/tagfile.cc +++ b/apt-pkg/tagfile.cc @@ -1004,7 +1004,7 @@ static bool RewriteTags(FileFd &File, pkgTagSection const *const This, char cons } else if(R->Action == pkgTagSection::Tag::RENAME && R->Data.length() == TagLen && strncasecmp(R->Data.c_str(), Tag, R->Data.length()) == 0) - data = This->FindRaw(R->Name.c_str()).to_string(); + data = This->FindRaw(R->Name.c_str()); else continue; diff --git a/apt-private/private-update.cc b/apt-private/private-update.cc index 6edde05ed..4f0296046 100644 --- a/apt-private/private-update.cc +++ b/apt-private/private-update.cc @@ -191,7 +191,7 @@ bool DoUpdate() { /* Try to notify users who have installed firmware packages at some point, but have not enabled non-free currently – they might want to opt into updates now */ - APT::StringView const affected_pkgs[] = { + std::string_view const affected_pkgs[] = { "amd64-microcode", "atmel-firmware", "bluez-firmware", "dahdi-firmware-nonfree", "firmware-amd-graphics", "firmware-ast", "firmware-atheros", "firmware-bnx2", "firmware-bnx2x", "firmware-brcm80211", "firmware-cavium", "firmware-intel-sound", diff --git a/cmdline/apt-extracttemplates.cc b/cmdline/apt-extracttemplates.cc index a578fa84b..1354928dc 100644 --- a/cmdline/apt-extracttemplates.cc +++ b/cmdline/apt-extracttemplates.cc @@ -1,14 +1,14 @@ // -*- mode: cpp; mode: fold -*- // Description /*{{{*/ /* ###################################################################### - + APT Extract Templates - Program to extract debconf config and template files - This is a simple program to extract config and template information + This is a simple program to extract config and template information from Debian packages. It can be used to speed up the preconfiguration process for debconf-enabled packages - + ##################################################################### */ /*}}}*/ // Include Files /*{{{*/ @@ -75,7 +75,7 @@ DebFile::~DebFile() string DebFile::GetInstalledVer(const string &package) { pkgCache::PkgIterator Pkg = Cache->FindPkg(package); - if (Pkg.end() == false) + if (Pkg.end() == false) { pkgCache::VerIterator V = Pkg.CurrentVer(); if (V.end() == false) @@ -120,8 +120,8 @@ bool DebFile::DoItem(Item &I, int &Fd) Config = new char[I.Size+1]; Config[I.Size] = 0; Which = IsConfig; - Fd = -2; - } + Fd = -2; + } else if (strcmp(I.Name, "templates") == 0) { delete [] Template; @@ -129,8 +129,8 @@ bool DebFile::DoItem(Item &I, int &Fd) Template[I.Size] = 0; Which = IsTemplate; Fd = -2; - } - else + } + else { // Ignore it Fd = -1; @@ -171,7 +171,7 @@ bool DebFile::ParseInfo() if (Section.Scan(Control, ControlLen) == false) return false; - Package = Section.Find(pkgTagSection::Key::Package).to_string(); + Package = Section.Find(pkgTagSection::Key::Package); Version = GetInstalledVer(Package); const char *Start, *Stop; @@ -210,7 +210,7 @@ bool DebFile::ParseInfo() if (Start == Stop) break; } } - + return true; } /*}}}*/ @@ -249,7 +249,7 @@ static void WriteConfig(const DebFile &file) if (templatefile.empty() == true || configscript.empty() == true) return; - cout << file.Package << " " << file.Version << " " + cout << file.Package << " " << file.Version << " " << templatefile << " " << configscript << endl; } /*}}}*/ @@ -257,7 +257,7 @@ static void WriteConfig(const DebFile &file) // --------------------------------------------------------------------- /* */ static bool Go(CommandLine &CmdL) -{ +{ // Initialize the apt cache MMap *Map = 0; pkgSourceList List; @@ -303,17 +303,17 @@ static bool Go(CommandLine &CmdL) if (file.PreDepVer != "" && DebFile::Cache->VS->CheckDep(debconfver.c_str(), file.PreDepOp,file.PreDepVer.c_str() - ) == false) + ) == false) continue; WriteConfig(file); } } - + delete Map; delete DebFile::Cache; - + return !_error->PendingError(); } /*}}}*/ diff --git a/cmdline/apt-sortpkgs.cc b/cmdline/apt-sortpkgs.cc index acbb2832e..8442a959d 100644 --- a/cmdline/apt-sortpkgs.cc +++ b/cmdline/apt-sortpkgs.cc @@ -1,13 +1,13 @@ // -*- mode: cpp; mode: fold -*- // Description /*{{{*/ /* ###################################################################### - + APT Sort Packages - Program to sort Package and Source files This program is quite simple, it just sorts the package files by package and sorts the fields inside by the internal APT sort order. Input is taken from a named file and sent to stdout. - + ##################################################################### */ /*}}}*/ // Include Files /*{{{*/ @@ -46,7 +46,7 @@ struct PkgName /*{{{*/ string Arch; unsigned long Offset; unsigned long Length; - + inline int Compare3(const PkgName &x) const { int A = stringcasecmp(Name,x.Name); @@ -58,7 +58,7 @@ struct PkgName /*{{{*/ } return A; } - + bool operator <(const PkgName &x) const {return Compare3(x) < 0;}; bool operator >(const PkgName &x) const {return Compare3(x) > 0;}; bool operator ==(const PkgName &x) const {return Compare3(x) == 0;}; @@ -73,7 +73,7 @@ static bool DoIt(string InFile) pkgTagFile Tags(&Fd); if (_error->PendingError() == true) return false; - + // Parse. vector<PkgName> List; pkgTagSection Section; @@ -83,28 +83,28 @@ static bool DoIt(string InFile) while (Tags.Step(Section) == true) { PkgName Tmp; - - /* Fetch the name, auto-detecting if this is a source file or a + + /* Fetch the name, auto-detecting if this is a source file or a package file */ - Tmp.Name = Section.Find(pkgTagSection::Key::Package).to_string(); - Tmp.Ver = Section.Find(pkgTagSection::Key::Version).to_string(); - Tmp.Arch = Section.Find(pkgTagSection::Key::Architecture).to_string(); - + Tmp.Name = Section.Find(pkgTagSection::Key::Package); + Tmp.Ver = Section.Find(pkgTagSection::Key::Version); + Tmp.Arch = Section.Find(pkgTagSection::Key::Architecture); + if (Tmp.Name.empty() == true) return _error->Error(_("Unknown package record!")); - + Tmp.Offset = Offset; Tmp.Length = Section.size(); if (Largest < Tmp.Length) Largest = Tmp.Length; - + List.push_back(Tmp); - + Offset = Tags.Offset(); } if (_error->PendingError() == true) return false; - + // Sort it sort(List.begin(),List.end()); diff --git a/methods/http.cc b/methods/http.cc index 0c4d82262..4d0e60d93 100644 --- a/methods/http.cc +++ b/methods/http.cc @@ -23,7 +23,6 @@ #include <apt-pkg/fileutl.h> #include <apt-pkg/hashes.h> #include <apt-pkg/proxy.h> -#include <apt-pkg/string_view.h> #include <apt-pkg/strutl.h> #include <cerrno> @@ -977,12 +976,12 @@ void HttpMethod::SendReq(FetchItem *Itm) #ifdef HAVE_SYSTEMD if (ConfigFindB("User-Agent-Non-Interactive", false)) { - using APT::operator""_sv; + using std::literals::operator""sv; char *unit = nullptr; sd_pid_get_unit(getpid(), &unit); if (unit != nullptr && *unit != '\0' && not APT::String::Startswith(unit, "user@") // user@ _is_ interactive - && "packagekit.service"_sv != unit // packagekit likely is interactive - && "dbus.service"_sv != unit) // aptdaemon and qapt don't have systemd services + && "packagekit.service"sv != unit // packagekit likely is interactive + && "dbus.service"sv != unit) // aptdaemon and qapt don't have systemd services Req << " non-interactive"; free(unit); diff --git a/test/libapt/strutil_test.cc b/test/libapt/strutil_test.cc index d7e57365f..500ba98da 100644 --- a/test/libapt/strutil_test.cc +++ b/test/libapt/strutil_test.cc @@ -1,6 +1,5 @@ #include <config.h> #include <apt-pkg/fileutl.h> -#include <apt-pkg/string_view.h> #include <apt-pkg/strutl.h> #include <limits> #include <string> @@ -259,7 +258,7 @@ TEST(StrUtilTest,QuoteString) EXPECT_EQ("Eltville-Erbach", DeQuoteString(QuoteString("Eltville-Erbach", ""))); } -static void EXPECT_STRTONUM(APT::StringView const str, bool const success, unsigned long const expected, unsigned const base) +static void EXPECT_STRTONUM(std::string_view const str, bool const success, unsigned long const expected, unsigned const base) { SCOPED_TRACE(std::string(str.data(), str.length())); SCOPED_TRACE(base); |
