// If this FilePath contains a drive letter specification, returns the // position of the last character of the drive letter specification, // otherwise returns npos. This can only be true on Windows, when a pathname // begins with a letter followed by a colon. On other platforms, this always // returns npos.
StringPieceType::size_type FindDriveLetter(StringPieceType path) { #ifdefined(FILE_PATH_USES_DRIVE_LETTERS) // This is dependent on an ASCII-based character set, but that's a // reasonable assumption. iswalpha can be too inclusive here. if (path.length() >= 2 && path[1] == L':' &&
((path[0] >= L'A' && path[0] <= L'Z') ||
(path[0] >= L'a' && path[0] <= L'z'))) { return1;
} #endif// FILE_PATH_USES_DRIVE_LETTERS return StringType::npos;
}
#ifdefined(FILE_PATH_USES_DRIVE_LETTERS) bool EqualDriveLetterCaseInsensitive(StringPieceType a, StringPieceType b) {
size_t a_letter_pos = FindDriveLetter(a);
size_t b_letter_pos = FindDriveLetter(b);
if (a_letter_pos == StringType::npos || b_letter_pos == StringType::npos) return a == b;
bool IsPathAbsolute(StringPieceType path) { #ifdefined(FILE_PATH_USES_DRIVE_LETTERS)
StringType::size_type letter = FindDriveLetter(path); if (letter != StringType::npos) { // Look for a separator right after the drive specification. return path.length() > letter + 1 &&
FilePath::IsSeparator(path[letter + 1]);
} // Look for a pair of leading separators. return path.length() > 1 &&
FilePath::IsSeparator(path[0]) && FilePath::IsSeparator(path[1]); #else// FILE_PATH_USES_DRIVE_LETTERS // Look for a separator in the first position. return path.length() > 0 && FilePath::IsSeparator(path[0]); #endif// FILE_PATH_USES_DRIVE_LETTERS
}
bool AreAllSeparators(const StringType& input) { for (auto it : input) { if (!FilePath::IsSeparator(it)) returnfalse;
}
return true;
}
// Find the position of the '.' that separates the extension from the rest // of the file name. The position is relative to BaseName(), not value(). // Returns npos if it can't find an extension.
StringType::size_type FinalExtensionSeparatorPosition(const StringType& path) { // Special case "." and ".." if (path == FilePath::kCurrentDirectory || path == FilePath::kParentDirectory) return StringType::npos;
// Same as above, but allow a second extension component of up to 4 // characters when the rightmost extension component is a common double // extension (gz, bz2, Z). For example, foo.tar.gz or foo.tar.Z would have // extension components of '.tar.gz' and '.tar.Z' respectively.
StringType::size_type ExtensionSeparatorPosition(const StringType& path) { const StringType::size_type last_dot = FinalExtensionSeparatorPosition(path);
// No extension, or the extension is the whole filename. if (last_dot == StringType::npos || last_dot == 0U) return last_dot;
// static bool FilePath::IsSeparator(CharType character) { for (size_t i = 0; i < kSeparatorsLength - 1; ++i) { if (character == kSeparators[i]) { return true;
}
}
returnfalse;
}
std::vector<FilePath::StringType> FilePath::GetComponents() const {
std::vector<StringType> ret_val; if (value().empty()) return ret_val;
FilePath current = *this;
FilePath base;
// Capture path components. while (current != current.DirName()) {
base = current.BaseName(); if (!AreAllSeparators(base.value()))
ret_val.push_back(base.value());
current = current.DirName();
}
// Capture root, if any.
base = current.BaseName(); if (!base.value().empty() && base.value() != kCurrentDirectory)
ret_val.push_back(current.BaseName().value());
// Capture drive letter, if any.
FilePath dir = current.DirName();
StringType::size_type letter = FindDriveLetter(dir.value()); if (letter != StringType::npos)
ret_val.emplace_back(dir.value(), 0, letter + 1);
#ifdefined(FILE_PATH_USES_DRIVE_LETTERS) // Windows can access case sensitive filesystems, so component // comparisions must be case sensitive, but drive letters are // never case sensitive. if ((FindDriveLetter(*parent_comp) != StringType::npos) &&
(FindDriveLetter(*child_comp) != StringType::npos)) { if (!StartsWith(*parent_comp, *child_comp, CompareCase::INSENSITIVE_ASCII)) returnfalse;
++parent_comp;
++child_comp;
} #endif// defined(FILE_PATH_USES_DRIVE_LETTERS)
// The first 2 components for network paths are [<2-Separators>, <hostname>]. // Use case-insensitive comparison for the hostname. // https://tools.ietf.org/html/rfc3986#section-3.2.2 if (IsNetwork() && parent_components.size() > 1) { if (*parent_comp++ != *child_comp++ ||
!base::EqualsCaseInsensitiveASCII(*parent_comp++, *child_comp++)) { returnfalse;
}
}
while (parent_comp != parent_components.end()) { if (*parent_comp != *child_comp) returnfalse;
++parent_comp;
++child_comp;
}
if (path != nullptr) { for (; child_comp != child_components.end(); ++child_comp) {
*path = path->Append(*child_comp);
}
} return true;
}
// libgen's dirname and basename aren't guaranteed to be thread-safe and aren't // guaranteed to not modify their input strings, and in fact are implemented // differently in this regard on different platforms. Don't use them, but // adhere to their behavior.
FilePath FilePath::DirName() const {
FilePath new_path(path_);
new_path.StripTrailingSeparatorsInternal();
// The drive letter, if any, always needs to remain in the output. If there // is no drive letter, as will always be the case on platforms which do not // support drive letters, letter will be npos, or -1, so the comparisons and // resizes below using letter will still be valid.
StringType::size_type letter = FindDriveLetter(new_path.path_);
StringType::size_type last_separator =
new_path.path_.find_last_of(kSeparators, StringType::npos,
kSeparatorsLength - 1); if (last_separator == StringType::npos) { // path_ is in the current directory.
new_path.path_.resize(letter + 1);
} elseif (last_separator == letter + 1) { // path_ is in the root directory.
new_path.path_.resize(letter + 2);
} elseif (last_separator == letter + 2 &&
IsSeparator(new_path.path_[letter + 1])) { // path_ is in "//" (possibly with a drive letter); leave the double // separator intact indicating alternate root.
new_path.path_.resize(letter + 3);
} elseif (last_separator != 0) { bool trim_to_basename = true; #if BUILDFLAG(IS_POSIX) // On Posix, more than two leading separators are always collapsed to one. // See // https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13 // So, do not strip any of the separators, let // StripTrailingSeparatorsInternal() take care of the extra. if (AreAllSeparators(new_path.path_.substr(0, last_separator + 1))) {
new_path.path_.resize(last_separator + 1);
trim_to_basename = false;
} #endif// BUILDFLAG(IS_POSIX) if (trim_to_basename) { // path_ is somewhere else, trim the basename.
new_path.path_.resize(last_separator);
}
}
new_path.StripTrailingSeparatorsInternal(); if (!new_path.path_.length())
new_path.path_ = kCurrentDirectory;
// The drive letter, if any, is always stripped.
StringType::size_type letter = FindDriveLetter(new_path.path_); if (letter != StringType::npos) {
new_path.path_.erase(0, letter + 1);
}
// Keep everything after the final separator, but if the pathname is only // one character and it's a separator, leave it alone.
StringType::size_type last_separator =
new_path.path_.find_last_of(kSeparators, StringType::npos,
kSeparatorsLength - 1); if (last_separator != StringType::npos &&
last_separator < new_path.path_.length() - 1) {
new_path.path_.erase(0, last_separator + 1);
}
FilePath FilePath::AddExtension(StringPieceType extension) const { if (IsEmptyOrSpecialCase(BaseName().value())) return FilePath();
// If the new extension is "" or ".", then just return the current FilePath. if (extension.empty() ||
(extension.size() == 1 && extension[0] == kExtensionSeparator)) return *this;
FilePath FilePath::ReplaceExtension(StringPieceType extension) const { if (IsEmptyOrSpecialCase(BaseName().value())) return FilePath();
FilePath no_ext = RemoveExtension(); // If the new extension is "" or ".", then just remove the current extension. if (extension.empty() ||
(extension.size() == 1 && extension[0] == kExtensionSeparator)) return no_ext;
if (path_.compare(kCurrentDirectory) == 0 && !appended.empty()) { // Append normally doesn't do any normalization, but as a special case, // when appending to kCurrentDirectory, just return a new path for the // component argument. Appending component to kCurrentDirectory would // serve no purpose other than needlessly lengthening the path, and // it's likely in practice to wind up with FilePath objects containing // only kCurrentDirectory when calling DirName on a single relative path // component. return FilePath(appended);
}
// Don't append a separator if the path is empty (indicating the current // directory) or if the path component is empty (indicating nothing to // append). if (!appended.empty() && !new_path.path_.empty()) { // Don't append a separator if the path still ends with a trailing // separator after stripping (indicating the root directory). if (!IsSeparator(new_path.path_.back())) { // Don't append a separator if the path is just a drive letter. if (FindDriveLetter(new_path.path_) + 1 != new_path.path_.length()) {
new_path.path_.append(1, kSeparators[0]);
}
}
}
bool FilePath::ReferencesParent() const { if (path_.find(kParentDirectory) == StringType::npos) { // GetComponents is quite expensive, so avoid calling it in the majority // of cases where there isn't a kParentDirectory anywhere in the path. returnfalse;
}
std::vector<StringType> components = GetComponents();
std::vector<StringType>::const_iterator it = components.begin(); for (; it != components.end(); ++it) { const StringType& component = *it; // Windows has odd, undocumented behavior with path components containing // only whitespace and . characters. So, if all we see is . and // whitespace, then we treat any .. sequence as referencing parent. // For simplicity we enforce this on all platforms. if (component.find_first_not_of(FILE_PATH_LITERAL(". \n\r\t")) ==
std::string::npos &&
component.find(kParentDirectory) != std::string::npos) { return true;
}
} returnfalse;
}
if (path_.find(kStringTerminator) != StringType::npos) returnfalse;
return true;
} #endif// !defined(MOZ_ZUCCHINI)
#if BUILDFLAG(IS_WIN) // Windows specific implementation of file string comparisons.
int FilePath::CompareIgnoreCase(StringPieceType string1,
StringPieceType string2) { // CharUpperW within user32 is used here because it will provide unicode // conversions regardless of locale. The STL alternative, towupper, has a // locale consideration that prevents it from converting all characters by // default.
CHECK(win::IsUser32AndGdi32Available()); // Perform character-wise upper case comparison rather than using the // fully Unicode-aware CompareString(). For details see: // http://blogs.msdn.com/michkap/archive/2005/10/17/481600.aspx
StringPieceType::const_iterator i1 = string1.begin();
StringPieceType::const_iterator i2 = string2.begin();
StringPieceType::const_iterator string1end = string1.end();
StringPieceType::const_iterator string2end = string2.end(); for ( ; i1 != string1end && i2 != string2end; ++i1, ++i2) {
wchar_t c1 =
(wchar_t)LOWORD(::CharUpperW((LPWSTR)(DWORD_PTR)MAKELONG(*i1, 0)));
wchar_t c2 =
(wchar_t)LOWORD(::CharUpperW((LPWSTR)(DWORD_PTR)MAKELONG(*i2, 0))); if (c1 < c2) return -1; if (c1 > c2) return1;
} if (i1 != string1end) return1; if (i2 != string2end) return -1; return0;
}
#elif BUILDFLAG(IS_APPLE) // Mac OS X specific implementation of file string comparisons.
// cf. https://developer.apple.com/library/archive/technotes/tn/tn1150.html#UnicodeSubtleties // // "When using CreateTextEncoding to create a text encoding, you should set // the TextEncodingBase to kTextEncodingUnicodeV2_0, set the // TextEncodingVariant to kUnicodeCanonicalDecompVariant, and set the // TextEncodingFormat to kUnicode16BitFormat. Using these values ensures that // the Unicode will be in the same form as on an HFS Plus volume, even as the // Unicode standard evolves." // // Another technical article for X 10.4 updates this: one should use // the new (unambiguous) kUnicodeHFSPlusDecompVariant. // cf. http://developer.apple.com/mac/library/releasenotes/TextFonts/RN-TEC/index.html // // This implementation uses CFStringGetFileSystemRepresentation() to get the // decomposed form, and an adapted version of the FastUnicodeCompare as // described in the tech note to compare the strings.
// Character conversion table for FastUnicodeCompare() // // The lower case table consists of a 256-entry high-byte table followed by // some number of 256-entry subtables. The high-byte table contains either an // offset to the subtable for characters with that high byte or zero, which // means that there are no case mappings or ignored characters in that block. // Ignored characters are mapped to zero. // // cf. downloadable file linked in // https://developer.apple.com/library/archive/technotes/tn/tn1150.html#Downloads
namespace {
// clang-format off const UInt16 lower_case_table[11 * 256] = { // High-byte indices ( == 0 iff no case mapping and no ignorables )
// Returns the next non-ignorable codepoint within `string` starting from the // position indicated by `index`, or zero if there are no more. // The passed-in `index` is automatically advanced as the characters in the // input HFS-decomposed UTF-8 strings are read. inline base_icu::UChar32 HFSReadNextNonIgnorableCodepoint(constchar* string,
size_t length,
size_t* index) {
base_icu::UChar32 codepoint = 0; while (*index < length && codepoint == 0) { // CBU8_NEXT returns a value < 0 in error cases. For purposes of string // comparison, we just use that value and flag it with DCHECK.
CBU8_NEXT(reinterpret_cast<const uint8_t*>(string), *index, length,
codepoint);
DCHECK_GT(codepoint, 0);
// Note: Here, there are no lower case conversion implemented in the // Supplementary Multilingual Plane (codepoint > 0xFFFF).
if (codepoint > 0 && codepoint <= 0xFFFF) { // Check if there is a subtable for this upper byte. int lookup_offset = lower_case_table[codepoint >> 8]; if (lookup_offset != 0)
codepoint = lower_case_table[lookup_offset + (codepoint & 0x00FF)]; // Note: `codepoint` may be again 0 at this point if the character was // an ignorable.
}
} return codepoint;
}
} // namespace
// Special UTF-8 version of FastUnicodeCompare. Cf: // http://developer.apple.com/mac/library/technotes/tn/tn1150.html#StringComparisonAlgorithm // The input strings must be in the special HFS decomposed form. int FilePath::HFSFastUnicodeCompare(StringPieceType string1,
StringPieceType string2) {
size_t length1 = string1.length();
size_t length2 = string2.length();
size_t index1 = 0;
size_t index2 = 0;
StringType FilePath::GetHFSDecomposedForm(StringPieceType string) {
StringType result;
ScopedCFTypeRef<CFStringRef> cfstring(CFStringCreateWithBytesNoCopy(
NULL, reinterpret_cast<const UInt8*>(string.data()),
checked_cast<CFIndex>(string.length()), kCFStringEncodingUTF8, false,
kCFAllocatorNull)); if (cfstring) { // Query the maximum length needed to store the result. In most cases this // will overestimate the required space. The return value also already // includes the space needed for a terminating 0.
CFIndex length = CFStringGetMaximumSizeOfFileSystemRepresentation(cfstring);
DCHECK_GT(length, 0); // should be at least 1 for the 0-terminator. // Reserve enough space for CFStringGetFileSystemRepresentation to write // into. Also set the length to the maximum so that we can shrink it later. // (Increasing rather than decreasing it would clobber the string contents!)
result.reserve(static_cast<size_t>(length));
result.resize(static_cast<size_t>(length) - 1);
Boolean success = CFStringGetFileSystemRepresentation(cfstring,
&result[0],
length); if (success) { // Reduce result.length() to actual string length.
result.resize(strlen(result.c_str()));
} else { // An error occurred -> clear result.
result.clear();
}
} return result;
}
int FilePath::CompareIgnoreCase(StringPieceType string1,
StringPieceType string2) { // Quick checks for empty strings - these speed things up a bit and make the // following code cleaner. if (string1.empty()) return string2.empty() ? 0 : -1; if (string2.empty()) return1;
// GetHFSDecomposedForm() returns an empty string in an error case. if (hfs1.empty() || hfs2.empty()) {
ScopedCFTypeRef<CFStringRef> cfstring1(CFStringCreateWithBytesNoCopy(
NULL, reinterpret_cast<const UInt8*>(string1.data()),
checked_cast<CFIndex>(string1.length()), kCFStringEncodingUTF8, false,
kCFAllocatorNull));
ScopedCFTypeRef<CFStringRef> cfstring2(CFStringCreateWithBytesNoCopy(
NULL, reinterpret_cast<const UInt8*>(string2.data()),
checked_cast<CFIndex>(string2.length()), kCFStringEncodingUTF8, false,
kCFAllocatorNull)); // If neither GetHFSDecomposedForm nor CFStringCreateWithBytesNoCopy // succeed, fall back to strcmp. This can occur when the input string is // invalid UTF-8. if (!cfstring1 || !cfstring2) { int comparison = memcmp(string1.data(), string2.data(),
std::min(string1.length(), string2.length())); if (comparison < 0) return -1; if (comparison > 0) return1; return0;
}
void FilePath::StripTrailingSeparatorsInternal() { // If there is no drive letter, start will be 1, which will prevent stripping // the leading separator if there is only one separator. If there is a drive // letter, start will be set appropriately to prevent stripping the first // separator following the drive letter, if a separator immediately follows // the drive letter.
StringType::size_type start = FindDriveLetter(path_) + 2;
StringType::size_type last_stripped = StringType::npos; for (StringType::size_type pos = path_.length();
pos > start && IsSeparator(path_[pos - 1]);
--pos) { // If the string only has two separators and they're at the beginning, // don't strip them, unless the string began with more than two separators. if (pos != start + 1 || last_stripped == start + 2 ||
!IsSeparator(path_[start - 1])) {
path_.resize(pos - 1);
last_stripped = pos;
}
}
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.