1 | //======================================================================== |
2 | // |
3 | // InMemoryFile.h |
4 | // |
5 | // Represents a file in-memory with GNU's stdio wrappers. |
6 | // NOTE as of this writing, open() depends on the glibc 'fopencookie' |
7 | // extension and is not supported on other platforms. The |
8 | // HAVE_IN_MEMORY_FILE macro is intended to reflect whether this class is |
9 | // usable. |
10 | // |
11 | // This file is licensed under the GPLv2 or later |
12 | // |
13 | // Copyright (C) 2018, 2019 Greg Knight <lyngvi@gmail.com> |
14 | // Copyright (C) 2022 Albert Astals Cid <aacid@kde.org> |
15 | // |
16 | //======================================================================== |
17 | |
18 | #ifndef IN_MEMORY_FILE_H |
19 | #define IN_MEMORY_FILE_H |
20 | |
21 | #include <cstdio> |
22 | #include <string> |
23 | #include <vector> |
24 | |
25 | #if defined(__USE_GNU) && !defined(__ANDROID_API__) |
26 | # define HAVE_IN_MEMORY_FILE (1) |
27 | # define HAVE_IN_MEMORY_FILE_FOPENCOOKIE (1) // used internally |
28 | #endif |
29 | |
30 | class InMemoryFile |
31 | { |
32 | private: |
33 | #ifdef HAVE_IN_MEMORY_FILE_FOPENCOOKIE |
34 | size_t iohead = 0; |
35 | FILE *fptr = nullptr; |
36 | #endif |
37 | std::vector<char> data; |
38 | |
39 | #ifdef HAVE_IN_MEMORY_FILE_FOPENCOOKIE |
40 | ssize_t _read(char *buf, size_t sz); |
41 | ssize_t _write(const char *buf, size_t sz); |
42 | int _seek(off64_t *offset, int whence); |
43 | #endif |
44 | |
45 | public: |
46 | InMemoryFile(); |
47 | |
48 | public: |
49 | /* Returns a file handle for this file. This is scoped to this object |
50 | * and must be fclosed() by the caller before destruction. */ |
51 | FILE *open(const char *mode); |
52 | |
53 | const std::vector<char> &getBuffer() const { return data; } |
54 | }; |
55 | |
56 | #endif // IN_MEMORY_FILE_H |
57 | |