aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/src/utils/file.cpp
blob: c0bb4bdde771acf51f8f2a74633f5368f786916f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Copyright (c) 2017 Egor Tensin <Egor.Tensin@gmail.com>
// This file is part of the "PDB repository" project.
// For details, see https://github.com/egor-tensin/pdb-repo.
// Distributed under the MIT License.

#include "pdb/all.hpp"

#include <safeint.h>

#include <Windows.h>

#include <cstddef>

#include <stdexcept>
#include <string>

namespace pdb
{
    namespace file
    {
        std::size_t get_size(const std::string& path)
        {
            const Handle handle{CreateFileA(
                path.c_str(),
                FILE_READ_ATTRIBUTES,
                FILE_SHARE_READ,
                NULL,
                OPEN_EXISTING,
                FILE_ATTRIBUTE_NORMAL,
                NULL)};

            if (handle.get() == INVALID_HANDLE_VALUE)
                throw error::windows(GetLastError());

            LARGE_INTEGER size;

            if (!GetFileSizeEx(handle.get(), &size))
                throw error::windows(GetLastError());

            std::size_t result = 0;

            if (!msl::utilities::SafeCast(size.QuadPart, result))
                throw std::runtime_error{"invalid file size"};

            return result;
        }

        ID query_id(const std::string& path)
        {
            const Handle handle{CreateFileA(
                path.c_str(),
                FILE_READ_ATTRIBUTES,
                FILE_SHARE_READ | FILE_SHARE_WRITE,
                NULL,
                OPEN_EXISTING,
                FILE_ATTRIBUTE_NORMAL,
                NULL)};

            if (handle.get() == INVALID_HANDLE_VALUE)
                throw error::windows(GetLastError());

            FILE_ID_INFO id;

            if (!GetFileInformationByHandleEx(
                    handle.get(),
                    FileIdInfo,
                    &id,
                    sizeof(id)))
                throw error::windows(GetLastError());

            return {id};
        }
    }
}