Joedb 10.4.3
The Journal-Only Embedded Database
Loading...
Searching...
No Matches
Stream_File.cpp
Go to the documentation of this file.
3
4namespace joedb
5{
6 /////////////////////////////////////////////////////////////////////////////
8 /////////////////////////////////////////////////////////////////////////////
9 (
10 std::streambuf &streambuf,
11 Open_Mode mode
12 ):
13 Abstract_File(mode),
14 streambuf(streambuf)
15 {
16 streambuf.pubseekoff
17 (
18 0,
19 std::ios_base::beg,
20 std::ios_base::in
21 );
22 }
23
24 /////////////////////////////////////////////////////////////////////////////
25 int64_t Stream_File::get_size() const
26 /////////////////////////////////////////////////////////////////////////////
27 {
28 return streambuf.pubseekoff
29 (
30 0,
31 std::ios_base::end,
32 std::ios_base::in
33 );
34 }
35
36 /////////////////////////////////////////////////////////////////////////////
37 void Stream_File::seek
38 /////////////////////////////////////////////////////////////////////////////
39 (
40 int64_t offset,
41 std::ios_base::openmode which
42 ) const
43 {
44 if (offset >= 0)
45 {
46 const auto pos = streambuf.pubseekoff(offset, std::ios_base::beg, which);
47 if (int64_t(pos) == offset)
48 return;
49 }
50
51 throw Exception("seek error");
52 }
53
54 /////////////////////////////////////////////////////////////////////////////
55 size_t Stream_File::pread(char *data, size_t size, int64_t offset) const
56 /////////////////////////////////////////////////////////////////////////////
57 {
58 seek(offset, std::ios_base::in);
59 const std::streamsize n = streambuf.sgetn(data, std::streamsize(size));
60 return size_t(n);
61 }
62
63 /////////////////////////////////////////////////////////////////////////////
64 void Stream_File::pwrite(const char *data, size_t size, int64_t offset)
65 /////////////////////////////////////////////////////////////////////////////
66 {
67 seek(offset, std::ios_base::out);
68
69 size_t written = 0;
70
71 while (written < size)
72 {
73 const std::streamsize n = streambuf.sputn
74 (
75 data + written,
76 std::streamsize(size - written)
77 );
78
79 if (n <= 0)
80 throw Exception("Could not write to stream");
81
82 written += size_t(n);
83 }
84
85 if (streambuf.pubsync() < 0)
86 throw Exception("sync error");
87 }
88}
int64_t get_size() const override
Get the size of the file, or -1 if it is unknown.
size_t pread(char *data, size_t size, int64_t offset) const override
Read a range of bytes.
void pwrite(const char *data, size_t size, int64_t offset) override
Write a range of bytes. Extend file size if necessary.
Stream_File(std::streambuf &streambuf, Open_Mode mode)
Open_Mode
Definition Open_Mode.h:8