Support/PathV2: Implement has_magic in terms of get_magic.

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@123545 91177308-0d34-0410-b5e6-96231b3b80d8
This commit is contained in:
Michael J. Spencer 2011-01-15 18:52:41 +00:00
parent d6cdf1d3cb
commit b33594be3d

View File

@ -686,38 +686,20 @@ void directory_entry::replace_filename(const Twine &filename, file_status st,
}
error_code has_magic(const Twine &path, const Twine &magic, bool &result) {
SmallString<128> PathStorage;
SmallString<32> MagicStorage;
StringRef Path = path.toNullTerminatedStringRef(PathStorage);
StringRef Magic = magic.toNullTerminatedStringRef(MagicStorage);
StringRef Magic = magic.toStringRef(MagicStorage);
SmallString<32> Buffer;
assert(Magic.size() > 0 && "magic must be non-empty!");
SmallString<32> BufferStorage;
BufferStorage.reserve(Magic.size());
// Open file.
std::FILE *file = std::fopen(Path.data(), "rb");
if (file == 0)
return error_code(errno, posix_category());
size_t size = ::fread(BufferStorage.data(), 1, Magic.size(), file);
if (size != Magic.size()) {
int error = errno;
bool eof = std::feof(file) != 0;
std::fclose(file);
if (eof) {
// EOF, return false.
if (error_code ec = get_magic(path, Magic.size(), Buffer)) {
if (ec == errc::value_too_large) {
// Magic.size() > file_size(Path).
result = false;
return success;
}
return error_code(error, posix_category());
return ec;
}
std::fclose(file);
if (std::memcmp(BufferStorage.data(), Magic.data(), Magic.size()) != 0)
result = false;
else
result = true;
result = Magic == Buffer;
return success;
}