summaryrefslogtreecommitdiff
path: root/lib/Support/PathV2.cpp
diff options
context:
space:
mode:
authorMichael J. Spencer <bigcheesegs@gmail.com>2010-12-28 01:49:01 +0000
committerMichael J. Spencer <bigcheesegs@gmail.com>2010-12-28 01:49:01 +0000
commit628467ef1f230e40ee00626ddfdcc7ca77b45a11 (patch)
treeb07d88dd20d7e07ca99d826c968cda2659a80c14 /lib/Support/PathV2.cpp
parentc3ab20e62e8be9b55cce0145d02ebdd20775a53a (diff)
downloadllvm-628467ef1f230e40ee00626ddfdcc7ca77b45a11.tar.gz
llvm-628467ef1f230e40ee00626ddfdcc7ca77b45a11.tar.bz2
llvm-628467ef1f230e40ee00626ddfdcc7ca77b45a11.tar.xz
Support/PathV2: Implement has_magic.
git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@122587 91177308-0d34-0410-b5e6-96231b3b80d8
Diffstat (limited to 'lib/Support/PathV2.cpp')
-rw-r--r--lib/Support/PathV2.cpp38
1 files changed, 38 insertions, 0 deletions
diff --git a/lib/Support/PathV2.cpp b/lib/Support/PathV2.cpp
index 335f7ff919..4cfb650a6c 100644
--- a/lib/Support/PathV2.cpp
+++ b/lib/Support/PathV2.cpp
@@ -15,6 +15,8 @@
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/ErrorHandling.h"
#include <cctype>
+#include <cstdio>
+#include <cstring>
namespace {
using llvm::StringRef;
@@ -659,6 +661,42 @@ void directory_entry::replace_filename(const Twine &filename, file_status st,
SymlinkStatus = symlink_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);
+
+ 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());
+ int 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.
+ result = false;
+ return success;
+ }
+ return error_code(error, posix_category());
+ }
+ std::fclose(file);
+
+ if (std::memcmp(BufferStorage.data(), Magic.data(), Magic.size()) != 0)
+ result = false;
+ else
+ result = true;
+ return success;
+}
+
} // end namespace fs
} // end namespace sys
} // end namespace llvm