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 //
15 //========================================================================
16 
17 #ifndef IN_MEMORY_FILE_H
18 #define IN_MEMORY_FILE_H
19 
20 #include <cstdio>
21 #include <string>
22 #include <vector>
23 
24 #if defined(__USE_GNU) && !defined(__ANDROID_API__)
25 #    define HAVE_IN_MEMORY_FILE (1)
26 #    define HAVE_IN_MEMORY_FILE_FOPENCOOKIE (1) // used internally
27 #endif
28 
29 class InMemoryFile
30 {
31 private:
32     size_t iohead;
33     std::vector<char> data;
34     FILE *fptr;
35 
36 #ifdef HAVE_IN_MEMORY_FILE_FOPENCOOKIE
37     ssize_t _read(char *buf, size_t sz);
38     ssize_t _write(const char *buf, size_t sz);
39     int _seek(off64_t *offset, int whence);
40 #endif
41 
42 public:
43     InMemoryFile();
44 
45 public:
46     /* Returns a file handle for this file. This is scoped to this object
47      * and must be fclosed() by the caller before destruction. */
48     FILE *open(const char *mode);
49 
getBuffer()50     const std::vector<char> &getBuffer() const { return data; }
51 };
52 
53 #endif // IN_MEMORY_FILE_H
54